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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.950   ! raeburn     4: # $Id: lonnet.pm,v 1.949 2008/03/12 02:46:27 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.949     raeburn   451:     my ($newenv,$roles) = @_;
                    452:     if (ref($newenv) eq 'HASH') {
                    453:         foreach my $key (keys(%{$newenv})) {
                    454:             my $refused = 0;
                    455: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    456:                 $refused = 1;
                    457:                 if (ref($roles) eq 'ARRAY') {
                    458:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    459:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    460:                         $refused = 0;
                    461:                     }
                    462:                 }
                    463:             }
                    464:             if ($refused) {
                    465:                 &logthis("<font color=\"blue\">WARNING: ".
                    466:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    467:                          .'</font>');
                    468: 	        delete($newenv->{$key});
                    469:             } else {
                    470:                 $env{$key}=$newenv->{$key};
                    471:             }
                    472:         }
                    473:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    474:         if ($opened
                    475: 	    && &timed_flock($env_file,LOCK_EX)
                    476: 	    &&
                    477: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    478: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    479: 	    while (my ($key,$value) = each(%{$newenv})) {
                    480: 	        $disk_env{$key} = $value;
                    481: 	    }
                    482: 	    untie(%disk_env);
1.35      www       483:         }
1.191     harris41  484:     }
1.56      www       485:     return 'ok';
                    486: }
                    487: # ----------------------------------------------------- Delete from Environment
                    488: 
                    489: sub delenv {
                    490:     my $delthis=shift;
                    491:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  492:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       493:                 "Attempt to delete from environment ".$delthis);
                    494:         return 'error';
                    495:     }
1.917     albertel  496:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    497:     if ($opened
1.915     albertel  498: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  499: 	&&
                    500: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    501: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  502: 	foreach my $key (keys(%disk_env)) {
                    503: 	    if ($key=~/^$delthis/) { 
1.915     albertel  504: 		delete($env{$key});
                    505: 		delete($disk_env{$key});
                    506: 	    }
1.448     albertel  507: 	}
1.783     albertel  508: 	untie(%disk_env);
1.5       www       509:     }
                    510:     return 'ok';
1.369     albertel  511: }
                    512: 
1.790     albertel  513: sub get_env_multiple {
                    514:     my ($name) = @_;
                    515:     my @values;
                    516:     if (defined($env{$name})) {
                    517:         # exists is it an array
                    518:         if (ref($env{$name})) {
                    519:             @values=@{ $env{$name} };
                    520:         } else {
                    521:             $values[0]=$env{$name};
                    522:         }
                    523:     }
                    524:     return(@values);
                    525: }
                    526: 
1.369     albertel  527: # ------------------------------------------ Find out current server userload
                    528: sub userload {
                    529:     my $numusers=0;
                    530:     {
                    531: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    532: 	my $filename;
                    533: 	my $curtime=time;
                    534: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  535: 	    next if ($filename eq '.' || $filename eq '..');
                    536: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  537: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  538: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  539: 	}
                    540: 	closedir(LONIDS);
                    541:     }
                    542:     my $userloadpercent=0;
                    543:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    544:     if ($maxuserload) {
1.371     albertel  545: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  546:     }
1.372     albertel  547:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  548:     return $userloadpercent;
1.283     www       549: }
                    550: 
                    551: # ------------------------------------------ Fight off request when overloaded
                    552: 
                    553: sub overloaderror {
                    554:     my ($r,$checkserver)=@_;
                    555:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    556:     my $loadavg;
                    557:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  558:        open(my $loadfile,'/proc/loadavg');
1.283     www       559:        $loadavg=<$loadfile>;
                    560:        $loadavg =~ s/\s.*//g;
1.285     matthew   561:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  562:        close($loadfile);
1.283     www       563:     } else {
                    564:        $loadavg=&reply('load',$checkserver);
                    565:     }
1.285     matthew   566:     my $overload=$loadavg-100;
1.283     www       567:     if ($overload>0) {
1.285     matthew   568: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       569:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       570:         return 413;
1.283     www       571:     }    
                    572:     return '';
1.5       www       573: }
1.1       albertel  574: 
                    575: # ------------------------------ Find server with least workload from spare.tab
1.11      www       576: 
1.1       albertel  577: sub spareserver {
1.670     albertel  578:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  579:     my $spare_server;
1.370     albertel  580:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  581:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    582:                                                      :  $userloadpercent;
                    583:     
                    584:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    585: 	($spare_server, $lowest_load) =
                    586: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    587:     }
                    588: 
                    589:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    590: 
                    591:     if (!$found_server) {
                    592: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    593: 	    ($spare_server, $lowest_load) =
                    594: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    595: 	}
                    596:     }
                    597: 
                    598:     if (!$want_server_name) {
1.838     albertel  599: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  600:     }
                    601:     return $spare_server;
                    602: }
                    603: 
                    604: sub compare_server_load {
                    605:     my ($try_server, $spare_server, $lowest_load) = @_;
                    606: 
                    607:     my $loadans     = &reply('load',    $try_server);
                    608:     my $userloadans = &reply('userload',$try_server);
                    609: 
                    610:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    611: 	next; #didn't get a number from the server
                    612:     }
                    613: 
                    614:     my $load;
                    615:     if ($loadans =~ /\d/) {
                    616: 	if ($userloadans =~ /\d/) {
                    617: 	    #both are numbers, pick the bigger one
                    618: 	    $load = ($loadans > $userloadans) ? $loadans 
                    619: 		                              : $userloadans;
1.411     albertel  620: 	} else {
1.784     albertel  621: 	    $load = $loadans;
1.411     albertel  622: 	}
1.784     albertel  623:     } else {
                    624: 	$load = $userloadans;
                    625:     }
                    626: 
                    627:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    628: 	$spare_server = $try_server;
                    629: 	$lowest_load  = $load;
1.370     albertel  630:     }
1.784     albertel  631:     return ($spare_server,$lowest_load);
1.202     matthew   632: }
1.914     albertel  633: 
                    634: # --------------------------- ask offload servers if user already has a session
                    635: sub find_existing_session {
                    636:     my ($udom,$uname) = @_;
                    637:     foreach my $try_server (@{ $spareid{'primary'} },
                    638: 			    @{ $spareid{'default'} }) {
                    639: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    640:     }
                    641:     return;
                    642: }
                    643: 
                    644: # -------------------------------- ask if server already has a session for user
                    645: sub has_user_session {
                    646:     my ($lonid,$udom,$uname) = @_;
                    647:     my $result = &reply(join(':','userhassession',
                    648: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    649:     return 1 if ($result eq 'ok');
                    650: 
                    651:     return 0;
                    652: }
                    653: 
1.202     matthew   654: # --------------------------------------------- Try to change a user's password
                    655: 
                    656: sub changepass {
1.799     raeburn   657:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   658:     $currentpass = &escape($currentpass);
                    659:     $newpass     = &escape($newpass);
1.799     raeburn   660:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   661: 		       $server);
                    662:     if (! $answer) {
                    663: 	&logthis("No reply on password change request to $server ".
                    664: 		 "by $uname in domain $udom.");
                    665:     } elsif ($answer =~ "^ok") {
                    666:         &logthis("$uname in $udom successfully changed their password ".
                    667: 		 "on $server.");
                    668:     } elsif ($answer =~ "^pwchange_failure") {
                    669: 	&logthis("$uname in $udom was unable to change their password ".
                    670: 		 "on $server.  The action was blocked by either lcpasswd ".
                    671: 		 "or pwchange");
                    672:     } elsif ($answer =~ "^non_authorized") {
                    673:         &logthis("$uname in $udom did not get their password correct when ".
                    674: 		 "attempting to change it on $server.");
                    675:     } elsif ($answer =~ "^auth_mode_error") {
                    676:         &logthis("$uname in $udom attempted to change their password despite ".
                    677: 		 "not being locally or internally authenticated on $server.");
                    678:     } elsif ($answer =~ "^unknown_user") {
                    679:         &logthis("$uname in $udom attempted to change their password ".
                    680: 		 "on $server but were unable to because $server is not ".
                    681: 		 "their home server.");
                    682:     } elsif ($answer =~ "^refused") {
                    683: 	&logthis("$server refused to change $uname in $udom password because ".
                    684: 		 "it was sent an unencrypted request to change the password.");
                    685:     }
                    686:     return $answer;
1.1       albertel  687: }
                    688: 
1.169     harris41  689: # ----------------------- Try to determine user's current authentication scheme
                    690: 
                    691: sub queryauthenticate {
                    692:     my ($uname,$udom)=@_;
1.456     albertel  693:     my $uhome=&homeserver($uname,$udom);
                    694:     if (!$uhome) {
                    695: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    696: 	return 'no_host';
                    697:     }
                    698:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    699:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    700: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  701:     }
1.456     albertel  702:     return $answer;
1.169     harris41  703: }
                    704: 
1.1       albertel  705: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       706: 
1.1       albertel  707: sub authenticate {
                    708:     my ($uname,$upass,$udom)=@_;
1.807     albertel  709:     $upass=&escape($upass);
                    710:     $uname= &LONCAPA::clean_username($uname);
1.836     www       711:     my $uhome=&homeserver($uname,$udom,1);
                    712:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    713: # Maybe the machine was offline and only re-appeared again recently?
                    714:         &reconlonc();
                    715: # One more
                    716: 	my $uhome=&homeserver($uname,$udom,1);
                    717: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    718: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    719: 	}
1.471     albertel  720: 	return 'no_host';
1.1       albertel  721:     }
1.471     albertel  722:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    723:     if ($answer eq 'authorized') {
                    724: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    725: 	return $uhome; 
                    726:     }
                    727:     if ($answer eq 'non_authorized') {
                    728: 	&logthis("User $uname at $udom rejected by $uhome");
                    729: 	return 'no_host'; 
1.9       www       730:     }
1.471     albertel  731:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  732:     return 'no_host';
                    733: }
                    734: 
                    735: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       736: 
1.599     albertel  737: my %homecache;
1.1       albertel  738: sub homeserver {
1.230     stredwic  739:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  740:     my $index="$uname:$udom";
1.426     albertel  741: 
1.599     albertel  742:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  743: 
                    744:     my %servers = &get_servers($udom,'library');
                    745:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  746:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  747: 		 exists($badServerCache{$tryserver}));
1.841     albertel  748: 
                    749: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    750: 	if ($answer eq 'found') {
                    751: 	    delete($badServerCache{$tryserver}); 
                    752: 	    return $homecache{$index}=$tryserver;
                    753: 	} elsif ($answer eq 'no_host') {
                    754: 	    $badServerCache{$tryserver}=1;
                    755: 	}
1.1       albertel  756:     }    
                    757:     return 'no_host';
1.70      www       758: }
                    759: 
                    760: # ------------------------------------- Find the usernames behind a list of IDs
                    761: 
                    762: sub idget {
                    763:     my ($udom,@ids)=@_;
                    764:     my %returnhash=();
                    765:     
1.841     albertel  766:     my %servers = &get_servers($udom,'library');
                    767:     foreach my $tryserver (keys(%servers)) {
                    768: 	my $idlist=join('&',@ids);
                    769: 	$idlist=~tr/A-Z/a-z/; 
                    770: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    771: 	my @answer=();
                    772: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    773: 	    @answer=split(/\&/,$reply);
                    774: 	}                    ;
                    775: 	my $i;
                    776: 	for ($i=0;$i<=$#ids;$i++) {
                    777: 	    if ($answer[$i]) {
                    778: 		$returnhash{$ids[$i]}=$answer[$i];
                    779: 	    } 
                    780: 	}
                    781:     } 
1.70      www       782:     return %returnhash;
                    783: }
                    784: 
                    785: # ------------------------------------- Find the IDs behind a list of usernames
                    786: 
                    787: sub idrget {
                    788:     my ($udom,@unames)=@_;
                    789:     my %returnhash=();
1.800     albertel  790:     foreach my $uname (@unames) {
                    791:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  792:     }
1.70      www       793:     return %returnhash;
                    794: }
                    795: 
                    796: # ------------------------------- Store away a list of names and associated IDs
                    797: 
                    798: sub idput {
                    799:     my ($udom,%ids)=@_;
                    800:     my %servers=();
1.800     albertel  801:     foreach my $uname (keys(%ids)) {
                    802: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    803:         my $uhom=&homeserver($uname,$udom);
1.70      www       804:         if ($uhom ne 'no_host') {
1.800     albertel  805:             my $id=&escape($ids{$uname});
1.70      www       806:             $id=~tr/A-Z/a-z/;
1.800     albertel  807:             my $esc_unam=&escape($uname);
1.70      www       808: 	    if ($servers{$uhom}) {
1.800     albertel  809: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       810:             } else {
1.800     albertel  811:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       812:             }
                    813:         }
1.191     harris41  814:     }
1.800     albertel  815:     foreach my $server (keys(%servers)) {
                    816:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  817:     }
1.344     www       818: }
                    819: 
1.806     raeburn   820: # ------------------------------------------- get items from domain db files   
                    821: 
                    822: sub get_dom {
1.860     raeburn   823:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   824:     my $items='';
                    825:     foreach my $item (@$storearr) {
                    826:         $items.=&escape($item).'&';
                    827:     }
                    828:     $items=~s/\&$//;
1.860     raeburn   829:     if (!$udom) {
                    830:         $udom=$env{'user.domain'};
                    831:         if (defined(&domain($udom,'primary'))) {
                    832:             $uhome=&domain($udom,'primary');
                    833:         } else {
1.874     albertel  834:             undef($uhome);
1.860     raeburn   835:         }
                    836:     } else {
                    837:         if (!$uhome) {
                    838:             if (defined(&domain($udom,'primary'))) {
                    839:                 $uhome=&domain($udom,'primary');
                    840:             }
                    841:         }
                    842:     }
                    843:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   844:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   845:         my %returnhash;
1.875     albertel  846:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   847:             return %returnhash;
                    848:         }
1.806     raeburn   849:         my @pairs=split(/\&/,$rep);
                    850:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    851:             return @pairs;
                    852:         }
                    853:         my $i=0;
                    854:         foreach my $item (@$storearr) {
                    855:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    856:             $i++;
                    857:         }
                    858:         return %returnhash;
                    859:     } else {
1.880     banghart  860:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   861:     }
                    862: }
                    863: 
                    864: # -------------------------------------------- put items in domain db files 
                    865: 
                    866: sub put_dom {
1.860     raeburn   867:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    868:     if (!$udom) {
                    869:         $udom=$env{'user.domain'};
                    870:         if (defined(&domain($udom,'primary'))) {
                    871:             $uhome=&domain($udom,'primary');
                    872:         } else {
1.874     albertel  873:             undef($uhome);
1.860     raeburn   874:         }
                    875:     } else {
                    876:         if (!$uhome) {
                    877:             if (defined(&domain($udom,'primary'))) {
                    878:                 $uhome=&domain($udom,'primary');
                    879:             }
                    880:         }
                    881:     } 
                    882:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   883:         my $items='';
                    884:         foreach my $item (keys(%$storehash)) {
                    885:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    886:         }
                    887:         $items=~s/\&$//;
                    888:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    889:     } else {
1.860     raeburn   890:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   891:     }
                    892: }
                    893: 
1.837     raeburn   894: sub retrieve_inst_usertypes {
                    895:     my ($udom) = @_;
                    896:     my (%returnhash,@order);
1.846     albertel  897:     if (defined(&domain($udom,'primary'))) {
                    898:         my $uhome=&domain($udom,'primary');
1.837     raeburn   899:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    900:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    901:         my @pairs=split(/\&/,$hashitems);
                    902:         foreach my $item (@pairs) {
                    903:             my ($key,$value)=split(/=/,$item,2);
                    904:             $key = &unescape($key);
                    905:             next if ($key =~ /^error: 2 /);
                    906:             $returnhash{$key}=&thaw_unescape($value);
                    907:         }
                    908:         my @esc_order = split(/\&/,$orderitems);
                    909:         foreach my $item (@esc_order) {
                    910:             push(@order,&unescape($item));
                    911:         }
                    912:     } else {
                    913:         &logthis("get_dom failed - no primary domain server for $udom");
                    914:     }
                    915:     return (\%returnhash,\@order);
                    916: }
                    917: 
1.868     raeburn   918: sub is_domainimage {
                    919:     my ($url) = @_;
                    920:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    921:         if (&domain($1) ne '') {
                    922:             return '1';
                    923:         }
                    924:     }
                    925:     return;
                    926: }
                    927: 
1.899     raeburn   928: sub inst_directory_query {
                    929:     my ($srch) = @_;
                    930:     my $udom = $srch->{'srchdomain'};
                    931:     my %results;
                    932:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   933:     my $outcome;
1.899     raeburn   934:     if ($homeserver ne '') {
1.904     albertel  935: 	my $queryid=&reply("querysend:instdirsearch:".
                    936: 			   &escape($srch->{'srchby'}).':'.
                    937: 			   &escape($srch->{'srchterm'}).':'.
                    938: 			   &escape($srch->{'srchtype'}),$homeserver);
                    939: 	my $host=&hostname($homeserver);
                    940: 	if ($queryid !~/^\Q$host\E\_/) {
                    941: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    942: 	    return;
                    943: 	}
                    944: 	my $response = &get_query_reply($queryid);
                    945: 	my $maxtries = 5;
                    946: 	my $tries = 1;
                    947: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    948: 	    $response = &get_query_reply($queryid);
                    949: 	    $tries ++;
                    950: 	}
                    951: 
                    952:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn   953:             if ($response eq 'unavailable') {
                    954:                 $outcome = $response;
                    955:             } else {
                    956:                 $outcome = 'ok';
                    957:                 my @matches = split(/\n/,$response);
                    958:                 foreach my $match (@matches) {
                    959:                     my ($key,$value) = split(/=/,$match);
                    960:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                    961:                 }
1.899     raeburn   962:             }
                    963:         }
                    964:     }
1.909     raeburn   965:     return ($outcome,%results);
1.899     raeburn   966: }
                    967: 
                    968: sub usersearch {
                    969:     my ($srch) = @_;
                    970:     my $dom = $srch->{'srchdomain'};
                    971:     my %results;
                    972:     my %libserv = &all_library();
                    973:     my $query = 'usersearch';
                    974:     foreach my $tryserver (keys(%libserv)) {
                    975:         if (&host_domain($tryserver) eq $dom) {
                    976:             my $host=&hostname($tryserver);
                    977:             my $queryid=
1.911     raeburn   978:                 &reply("querysend:".&escape($query).':'.
                    979:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn   980:                        &escape($srch->{'srchtype'}).':'.
                    981:                        &escape($srch->{'srchterm'}),$tryserver);
                    982:             if ($queryid !~/^\Q$host\E\_/) {
                    983:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   984:                 next;
1.899     raeburn   985:             }
                    986:             my $reply = &get_query_reply($queryid);
                    987:             my $maxtries = 1;
                    988:             my $tries = 1;
                    989:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    990:                 $reply = &get_query_reply($queryid);
                    991:                 $tries ++;
                    992:             }
                    993:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    994:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    995:             } else {
1.911     raeburn   996:                 my @matches;
                    997:                 if ($reply =~ /\n/) {
                    998:                     @matches = split(/\n/,$reply);
                    999:                 } else {
                   1000:                     @matches = split(/\&/,$reply);
                   1001:                 }
1.899     raeburn  1002:                 foreach my $match (@matches) {
                   1003:                     my ($uname,$udom,%userhash);
1.911     raeburn  1004:                     foreach my $entry (split(/:/,$match)) {
                   1005:                         my ($key,$value) =
                   1006:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1007:                         $userhash{$key} = $value;
                   1008:                         if ($key eq 'username') {
                   1009:                             $uname = $value;
                   1010:                         } elsif ($key eq 'domain') {
                   1011:                             $udom = $value;
1.911     raeburn  1012:                         }
1.899     raeburn  1013:                     }
                   1014:                     $results{$uname.':'.$udom} = \%userhash;
                   1015:                 }
                   1016:             }
                   1017:         }
                   1018:     }
                   1019:     return %results;
                   1020: }
                   1021: 
1.912     raeburn  1022: sub get_instuser {
                   1023:     my ($udom,$uname,$id) = @_;
                   1024:     my $homeserver = &domain($udom,'primary');
                   1025:     my ($outcome,%results);
                   1026:     if ($homeserver ne '') {
                   1027:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1028:                            &escape($id).':'.&escape($udom),$homeserver);
                   1029:         my $host=&hostname($homeserver);
                   1030:         if ($queryid !~/^\Q$host\E\_/) {
                   1031:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1032:             return;
                   1033:         }
                   1034:         my $response = &get_query_reply($queryid);
                   1035:         my $maxtries = 5;
                   1036:         my $tries = 1;
                   1037:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1038:             $response = &get_query_reply($queryid);
                   1039:             $tries ++;
                   1040:         }
                   1041:         if (!&error($response) && $response ne 'refused') {
                   1042:             if ($response eq 'unavailable') {
                   1043:                 $outcome = $response;
                   1044:             } else {
                   1045:                 $outcome = 'ok';
                   1046:                 my @matches = split(/\n/,$response);
                   1047:                 foreach my $match (@matches) {
                   1048:                     my ($key,$value) = split(/=/,$match);
                   1049:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1050:                 }
                   1051:             }
                   1052:         }
                   1053:     }
                   1054:     my %userinfo;
                   1055:     if (ref($results{$uname}) eq 'HASH') {
                   1056:         %userinfo = %{$results{$uname}};
                   1057:     } 
                   1058:     return ($outcome,%userinfo);
                   1059: }
                   1060: 
                   1061: sub inst_rulecheck {
1.923     raeburn  1062:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1063:     my %returnhash;
                   1064:     if ($udom ne '') {
                   1065:         if (ref($rules) eq 'ARRAY') {
                   1066:             @{$rules} = map {&escape($_);} (@{$rules});
                   1067:             my $rulestr = join(':',@{$rules});
                   1068:             my $homeserver=&domain($udom,'primary');
                   1069:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1070:                 my $response;
                   1071:                 if ($item eq 'username') {                
                   1072:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1073:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1074:                                               $homeserver));
1.923     raeburn  1075:                 } elsif ($item eq 'id') {
                   1076:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1077:                                               ':'.&escape($id).':'.$rulestr,
                   1078:                                               $homeserver));
1.945     raeburn  1079:                 } elsif ($item eq 'selfcreate') {
                   1080:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1081:                                                &escape($udom).':'.&escape($uname).
                   1082:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1083:                 }
1.912     raeburn  1084:                 if ($response ne 'refused') {
                   1085:                     my @pairs=split(/\&/,$response);
                   1086:                     foreach my $item (@pairs) {
                   1087:                         my ($key,$value)=split(/=/,$item,2);
                   1088:                         $key = &unescape($key);
                   1089:                         next if ($key =~ /^error: 2 /);
                   1090:                         $returnhash{$key}=&thaw_unescape($value);
                   1091:                     }
                   1092:                 }
                   1093:             }
                   1094:         }
                   1095:     }
                   1096:     return %returnhash;
                   1097: }
                   1098: 
                   1099: sub inst_userrules {
1.923     raeburn  1100:     my ($udom,$check) = @_;
1.912     raeburn  1101:     my (%ruleshash,@ruleorder);
                   1102:     if ($udom ne '') {
                   1103:         my $homeserver=&domain($udom,'primary');
                   1104:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1105:             my $response;
                   1106:             if ($check eq 'id') {
                   1107:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1108:                                  $homeserver);
1.943     raeburn  1109:             } elsif ($check eq 'email') {
                   1110:                 $response=&reply('instemailrules:'.&escape($udom),
                   1111:                                  $homeserver);
1.923     raeburn  1112:             } else {
                   1113:                 $response=&reply('instuserrules:'.&escape($udom),
                   1114:                                  $homeserver);
                   1115:             }
1.912     raeburn  1116:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1117:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1118:                 ($response ne 'no_such_host')) {
                   1119:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1120:                 my @pairs=split(/\&/,$hashitems);
                   1121:                 foreach my $item (@pairs) {
                   1122:                     my ($key,$value)=split(/=/,$item,2);
                   1123:                     $key = &unescape($key);
                   1124:                     next if ($key =~ /^error: 2 /);
                   1125:                     $ruleshash{$key}=&thaw_unescape($value);
                   1126:                 }
                   1127:                 my @esc_order = split(/\&/,$orderitems);
                   1128:                 foreach my $item (@esc_order) {
                   1129:                     push(@ruleorder,&unescape($item));
                   1130:                 }
                   1131:             }
                   1132:         }
                   1133:     }
                   1134:     return (\%ruleshash,\@ruleorder);
                   1135: }
                   1136: 
1.943     raeburn  1137: # ------------------------- Get Authentication and Language Defaults for Domain
                   1138: 
                   1139: sub get_domain_defaults {
                   1140:     my ($domain) = @_;
                   1141:     my $cachetime = 60*60*24;
                   1142:     my ($defauthtype,$defautharg,$deflang);
                   1143:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1144:     if (defined($cached)) {
                   1145:         if (ref($result) eq 'HASH') {
                   1146:             return %{$result};
                   1147:         }
                   1148:     }
                   1149:     my %domdefaults;
                   1150:     my %domconfig =
                   1151:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
                   1152:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1153:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1154:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1155:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1156:     } else {
                   1157:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1158:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1159:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1160:     }
                   1161:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1162:                                   $cachetime);
                   1163:     return %domdefaults;
                   1164: }
                   1165: 
1.344     www      1166: # --------------------------------------------------- Assign a key to a student
                   1167: 
                   1168: sub assign_access_key {
1.364     www      1169: #
                   1170: # a valid key looks like uname:udom#comments
                   1171: # comments are being appended
                   1172: #
1.498     www      1173:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1174:     $kdom=
1.620     albertel 1175:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1176:     $knum=
1.620     albertel 1177:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1178:     $cdom=
1.620     albertel 1179:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1180:     $cnum=
1.620     albertel 1181:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1182:     $udom=$env{'user.name'} unless (defined($udom));
                   1183:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1184:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1185:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1186:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1187:                                                   # assigned to this person
                   1188:                                                   # - this should not happen,
1.345     www      1189:                                                   # unless something went wrong
                   1190:                                                   # the first time around
                   1191: # ready to assign
1.364     www      1192:         $logentry=$1.'; '.$logentry;
1.496     www      1193:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1194:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1195: # key now belongs to user
1.346     www      1196: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1197:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1198:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1199:                 return 'ok';
                   1200:             } else {
                   1201:                 return 
                   1202:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1203: 	    }
                   1204:         } else {
                   1205:             return 'error: Could not assign key, try again later.';
                   1206:         }
1.364     www      1207:     } elsif (!$existing{$ckey}) {
1.345     www      1208: # the key does not exist
                   1209: 	return 'error: The key does not exist';
                   1210:     } else {
                   1211: # the key is somebody else's
                   1212: 	return 'error: The key is already in use';
                   1213:     }
1.344     www      1214: }
                   1215: 
1.364     www      1216: # ------------------------------------------ put an additional comment on a key
                   1217: 
                   1218: sub comment_access_key {
                   1219: #
                   1220: # a valid key looks like uname:udom#comments
                   1221: # comments are being appended
                   1222: #
                   1223:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1224:     $cdom=
1.620     albertel 1225:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1226:     $cnum=
1.620     albertel 1227:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1228:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1229:     if ($existing{$ckey}) {
                   1230:         $existing{$ckey}.='; '.$logentry;
                   1231: # ready to assign
1.367     www      1232:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1233:                                                  $cdom,$cnum) eq 'ok') {
                   1234: 	    return 'ok';
                   1235:         } else {
                   1236: 	    return 'error: Count not store comment.';
                   1237:         }
                   1238:     } else {
                   1239: # the key does not exist
                   1240: 	return 'error: The key does not exist';
                   1241:     }
                   1242: }
                   1243: 
1.344     www      1244: # ------------------------------------------------------ Generate a set of keys
                   1245: 
                   1246: sub generate_access_keys {
1.364     www      1247:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1248:     $cdom=
1.620     albertel 1249:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1250:     $cnum=
1.620     albertel 1251:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1252:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1253:     unless (($cdom) && ($cnum)) { return 0; }
                   1254:     if ($number>10000) { return 0; }
                   1255:     sleep(2); # make sure don't get same seed twice
                   1256:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1257:     my $total=0;
                   1258:     for (my $i=1;$i<=$number;$i++) {
                   1259:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1260:                   sprintf("%lx",int(100000*rand)).'-'.
                   1261:                   sprintf("%lx",int(100000*rand));
                   1262:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1263:        $newkey=~s/0/h/g; # and also 0 and O
                   1264:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1265:        if ($existing{$newkey}) {
                   1266:            $i--;
                   1267:        } else {
1.364     www      1268: 	  if (&put('accesskeys',
                   1269:               { $newkey => '# generated '.localtime().
1.620     albertel 1270:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1271:                            '; '.$logentry },
                   1272: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1273:               $total++;
                   1274: 	  }
                   1275:        }
                   1276:     }
1.620     albertel 1277:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1278:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1279:     return $total;
                   1280: }
                   1281: 
                   1282: # ------------------------------------------------------- Validate an accesskey
                   1283: 
                   1284: sub validate_access_key {
                   1285:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1286:     $cdom=
1.620     albertel 1287:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1288:     $cnum=
1.620     albertel 1289:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1290:     $udom=$env{'user.domain'} unless (defined($udom));
                   1291:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1292:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1293:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1294: }
                   1295: 
                   1296: # ------------------------------------- Find the section of student in a course
1.652     albertel 1297: sub devalidate_getsection_cache {
                   1298:     my ($udom,$unam,$courseid)=@_;
                   1299:     my $hashid="$udom:$unam:$courseid";
                   1300:     &devalidate_cache_new('getsection',$hashid);
                   1301: }
1.298     matthew  1302: 
1.815     albertel 1303: sub courseid_to_courseurl {
                   1304:     my ($courseid) = @_;
                   1305:     #already url style courseid
                   1306:     return $courseid if ($courseid =~ m{^/});
                   1307: 
                   1308:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1309: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1310: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1311: 	return "/$cdom/$cnum";
                   1312:     }
                   1313: 
                   1314:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1315:     if (exists($courseinfo{'num'})) {
                   1316: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1317:     }
                   1318: 
                   1319:     return undef;
                   1320: }
                   1321: 
1.298     matthew  1322: sub getsection {
                   1323:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1324:     my $cachetime=1800;
1.551     albertel 1325: 
                   1326:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1327:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1328:     if (defined($cached)) { return $result; }
                   1329: 
1.298     matthew  1330:     my %Pending; 
                   1331:     my %Expired;
                   1332:     #
                   1333:     # Each role can either have not started yet (pending), be active, 
                   1334:     #    or have expired.
                   1335:     #
                   1336:     # If there is an active role, we are done.
                   1337:     #
                   1338:     # If there is more than one role which has not started yet, 
                   1339:     #     choose the one which will start sooner
                   1340:     # If there is one role which has not started yet, return it.
                   1341:     #
                   1342:     # If there is more than one expired role, choose the one which ended last.
                   1343:     # If there is a role which has expired, return it.
                   1344:     #
1.815     albertel 1345:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1346:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1347:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1348:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1349:         my $section=$1;
                   1350:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1351:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1352:         my $now=time;
1.548     albertel 1353:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1354:             $Expired{$end}=$section;
                   1355:             next;
                   1356:         }
1.548     albertel 1357:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1358:             $Pending{$start}=$section;
                   1359:             next;
                   1360:         }
1.599     albertel 1361:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1362:     }
                   1363:     #
                   1364:     # Presumedly there will be few matching roles from the above
                   1365:     # loop and the sorting time will be negligible.
                   1366:     if (scalar(keys(%Pending))) {
                   1367:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1368:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1369:     } 
                   1370:     if (scalar(keys(%Expired))) {
                   1371:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1372:         my $time = pop(@sorted);
1.599     albertel 1373:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1374:     }
1.599     albertel 1375:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1376: }
1.70      www      1377: 
1.599     albertel 1378: sub save_cache {
                   1379:     &purge_remembered();
1.722     albertel 1380:     #&Apache::loncommon::validate_page();
1.620     albertel 1381:     undef(%env);
1.780     albertel 1382:     undef($env_loaded);
1.599     albertel 1383: }
1.452     albertel 1384: 
1.599     albertel 1385: my $to_remember=-1;
                   1386: my %remembered;
                   1387: my %accessed;
                   1388: my $kicks=0;
                   1389: my $hits=0;
1.849     albertel 1390: sub make_key {
                   1391:     my ($name,$id) = @_;
1.872     albertel 1392:     if (length($id) > 65 
                   1393: 	&& length(&escape($id)) > 200) {
                   1394: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1395:     }
1.849     albertel 1396:     return &escape($name.':'.$id);
                   1397: }
                   1398: 
1.599     albertel 1399: sub devalidate_cache_new {
                   1400:     my ($name,$id,$debug) = @_;
                   1401:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1402:     $id=&make_key($name,$id);
1.599     albertel 1403:     $memcache->delete($id);
                   1404:     delete($remembered{$id});
                   1405:     delete($accessed{$id});
                   1406: }
                   1407: 
                   1408: sub is_cached_new {
                   1409:     my ($name,$id,$debug) = @_;
1.849     albertel 1410:     $id=&make_key($name,$id);
1.599     albertel 1411:     if (exists($remembered{$id})) {
                   1412: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1413: 	$accessed{$id}=[&gettimeofday()];
                   1414: 	$hits++;
                   1415: 	return ($remembered{$id},1);
                   1416:     }
                   1417:     my $value = $memcache->get($id);
                   1418:     if (!(defined($value))) {
                   1419: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1420: 	return (undef,undef);
1.416     albertel 1421:     }
1.599     albertel 1422:     if ($value eq '__undef__') {
                   1423: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1424: 	$value=undef;
                   1425:     }
                   1426:     &make_room($id,$value,$debug);
                   1427:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1428:     return ($value,1);
                   1429: }
                   1430: 
                   1431: sub do_cache_new {
                   1432:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1433:     $id=&make_key($name,$id);
1.599     albertel 1434:     my $setvalue=$value;
                   1435:     if (!defined($setvalue)) {
                   1436: 	$setvalue='__undef__';
                   1437:     }
1.623     albertel 1438:     if (!defined($time) ) {
                   1439: 	$time=600;
                   1440:     }
1.599     albertel 1441:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1442:     my $result = $memcache->set($id,$setvalue,$time);
                   1443:     if (! $result) {
1.872     albertel 1444: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1445: 	$memcache->disconnect_all();
1.872     albertel 1446:     }
1.600     albertel 1447:     # need to make a copy of $value
1.919     albertel 1448:     &make_room($id,$value,$debug);
1.599     albertel 1449:     return $value;
                   1450: }
                   1451: 
                   1452: sub make_room {
                   1453:     my ($id,$value,$debug)=@_;
1.919     albertel 1454: 
                   1455:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1456:                                     : $value;
1.599     albertel 1457:     if ($to_remember<0) { return; }
                   1458:     $accessed{$id}=[&gettimeofday()];
                   1459:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1460:     my $to_kick;
                   1461:     my $max_time=0;
                   1462:     foreach my $other (keys(%accessed)) {
                   1463: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1464: 	    $to_kick=$other;
                   1465: 	    $max_time=&tv_interval($accessed{$other});
                   1466: 	}
                   1467:     }
                   1468:     delete($remembered{$to_kick});
                   1469:     delete($accessed{$to_kick});
                   1470:     $kicks++;
                   1471:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1472:     return;
                   1473: }
                   1474: 
1.599     albertel 1475: sub purge_remembered {
1.604     albertel 1476:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1477:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1478:     undef(%remembered);
                   1479:     undef(%accessed);
1.428     albertel 1480: }
1.70      www      1481: # ------------------------------------- Read an entry from a user's environment
                   1482: 
                   1483: sub userenvironment {
                   1484:     my ($udom,$unam,@what)=@_;
                   1485:     my %returnhash=();
                   1486:     my @answer=split(/\&/,
                   1487:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1488:                       &homeserver($unam,$udom)));
                   1489:     my $i;
                   1490:     for ($i=0;$i<=$#what;$i++) {
                   1491: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1492:     }
                   1493:     return %returnhash;
1.1       albertel 1494: }
                   1495: 
1.617     albertel 1496: # ---------------------------------------------------------- Get a studentphoto
                   1497: sub studentphoto {
                   1498:     my ($udom,$unam,$ext) = @_;
                   1499:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1500:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1501:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1502:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1503:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1504:             } else {
                   1505:                 my ($result,$perm_reqd)=
1.707     albertel 1506: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1507:                 if ($result eq 'ok') {
                   1508:                     if (!($perm_reqd eq 'yes')) {
                   1509:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1510:                     }
                   1511:                 }
                   1512:             }
                   1513:         }
                   1514:     } else {
                   1515:         my ($result,$perm_reqd) = 
1.707     albertel 1516: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1517:         if ($result eq 'ok') {
                   1518:             if (!($perm_reqd eq 'yes')) {
                   1519:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1520:             }
                   1521:         }
                   1522:     }
                   1523:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1524: }
                   1525: 
                   1526: sub retrievestudentphoto {
                   1527:     my ($udom,$unam,$ext,$type) = @_;
                   1528:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1529:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1530:     if ($ret eq 'ok') {
                   1531:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1532:         if ($type eq 'thumbnail') {
                   1533:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1534:         }
                   1535:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1536:         return $tokenurl;
                   1537:     } else {
                   1538:         if ($type eq 'thumbnail') {
                   1539:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1540:         } else { 
                   1541:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1542:         }
1.617     albertel 1543:     }
                   1544: }
                   1545: 
1.263     www      1546: # -------------------------------------------------------------------- New chat
                   1547: 
                   1548: sub chatsend {
1.724     raeburn  1549:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1550:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1551:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1552:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1553:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1554: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1555: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1556: }
                   1557: 
                   1558: # ------------------------------------------ Find current version of a resource
                   1559: 
                   1560: sub getversion {
                   1561:     my $fname=&clutter(shift);
                   1562:     unless ($fname=~/^\/res\//) { return -1; }
                   1563:     return &currentversion(&filelocation('',$fname));
                   1564: }
                   1565: 
                   1566: sub currentversion {
                   1567:     my $fname=shift;
1.599     albertel 1568:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1569:     if (defined($cached)) { return $result; }
1.292     www      1570:     my $author=$fname;
                   1571:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1572:     my ($udom,$uname)=split(/\//,$author);
                   1573:     my $home=homeserver($uname,$udom);
                   1574:     if ($home eq 'no_host') { 
                   1575:         return -1; 
                   1576:     }
                   1577:     my $answer=reply("currentversion:$fname",$home);
                   1578:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1579: 	return -1;
                   1580:     }
1.599     albertel 1581:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1582: }
                   1583: 
1.1       albertel 1584: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1585: 
1.1       albertel 1586: sub subscribe {
                   1587:     my $fname=shift;
1.761     raeburn  1588:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1589:     $fname=~s/[\n\r]//g;
1.1       albertel 1590:     my $author=$fname;
                   1591:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1592:     my ($udom,$uname)=split(/\//,$author);
                   1593:     my $home=homeserver($uname,$udom);
1.335     albertel 1594:     if ($home eq 'no_host') {
                   1595:         return 'not_found';
1.1       albertel 1596:     }
                   1597:     my $answer=reply("sub:$fname",$home);
1.64      www      1598:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1599: 	$answer.=' by '.$home;
                   1600:     }
1.1       albertel 1601:     return $answer;
                   1602: }
                   1603:     
1.8       www      1604: # -------------------------------------------------------------- Replicate file
                   1605: 
                   1606: sub repcopy {
                   1607:     my $filename=shift;
1.23      www      1608:     $filename=~s/\/+/\//g;
1.607     raeburn  1609:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1610:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1611:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1612: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1613: 	return &repcopy_userfile($filename);
                   1614:     }
1.532     albertel 1615:     $filename=~s/[\n\r]//g;
1.8       www      1616:     my $transname="$filename.in.transfer";
1.828     www      1617: # FIXME: this should flock
1.607     raeburn  1618:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1619:     my $remoteurl=subscribe($filename);
1.64      www      1620:     if ($remoteurl =~ /^con_lost by/) {
                   1621: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1622:            return 'unavailable';
1.8       www      1623:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1624: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1625: 	   return 'not_found';
1.64      www      1626:     } elsif ($remoteurl =~ /^rejected by/) {
                   1627: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1628:            return 'forbidden';
1.20      www      1629:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1630:            return 'ok';
1.8       www      1631:     } else {
1.290     www      1632:         my $author=$filename;
                   1633:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1634:         my ($udom,$uname)=split(/\//,$author);
                   1635:         my $home=homeserver($uname,$udom);
                   1636:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1637:            my @parts=split(/\//,$filename);
                   1638:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1639:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1640:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1641: 	       return 'bad_request';
1.8       www      1642:            }
                   1643:            my $count;
                   1644:            for ($count=5;$count<$#parts;$count++) {
                   1645:                $path.="/$parts[$count]";
                   1646:                if ((-e $path)!=1) {
                   1647: 		   mkdir($path,0777);
                   1648:                }
                   1649:            }
                   1650:            my $ua=new LWP::UserAgent;
                   1651:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1652:            my $response=$ua->request($request,$transname);
                   1653:            if ($response->is_error()) {
                   1654: 	       unlink($transname);
                   1655:                my $message=$response->status_line;
1.672     albertel 1656:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1657:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1658:                return 'unavailable';
1.8       www      1659:            } else {
1.16      www      1660: 	       if ($remoteurl!~/\.meta$/) {
                   1661:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1662:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1663:                   if ($mresponse->is_error()) {
                   1664: 		      unlink($filename.'.meta');
                   1665:                       &logthis(
1.672     albertel 1666:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1667:                   }
                   1668: 	       }
1.8       www      1669:                rename($transname,$filename);
1.607     raeburn  1670:                return 'ok';
1.8       www      1671:            }
1.290     www      1672:        }
1.8       www      1673:     }
1.330     www      1674: }
                   1675: 
                   1676: # ------------------------------------------------ Get server side include body
                   1677: sub ssi_body {
1.381     albertel 1678:     my ($filelink,%form)=@_;
1.606     matthew  1679:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1680:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1681:     }
1.330     www      1682:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1683:                                      &ssi($filelink,%form));
1.778     albertel 1684:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1685:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1686:     $output=~s/\<\/body\s*\>.*?$//si;
1.330     www      1687:     return $output;
1.8       www      1688: }
                   1689: 
1.15      www      1690: # --------------------------------------------------------- Server Side Include
                   1691: 
1.782     albertel 1692: sub absolute_url {
                   1693:     my ($host_name) = @_;
                   1694:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1695:     if ($host_name eq '') {
                   1696: 	$host_name = $ENV{'SERVER_NAME'};
                   1697:     }
                   1698:     return $protocol.$host_name;
                   1699: }
                   1700: 
1.942     foxr     1701: #
                   1702: #   Server side include.
                   1703: # Parameters:
                   1704: #  fn     Possibly encrypted resource name/id.
                   1705: #  form   Hash that describes how the rendering should be done
                   1706: #         and other things.
1.944     foxr     1707: # Returns:
1.950   ! raeburn  1708: #   Scalar context: The content of the response.
        !          1709: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1710: #     
1.15      www      1711: sub ssi {
                   1712: 
1.944     foxr     1713:     my ($fn,%form)=@_;
1.15      www      1714:     my $ua=new LWP::UserAgent;
1.23      www      1715:     my $request;
1.711     albertel 1716: 
                   1717:     $form{'no_update_last_known'}=1;
1.895     albertel 1718:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1719:     if (%form) {
1.782     albertel 1720:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1721:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1722:     } else {
1.782     albertel 1723:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1724:     }
                   1725: 
1.15      www      1726:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1727:     my $response=$ua->request($request);
                   1728: 
1.944     foxr     1729:     if (wantarray) {
                   1730: 	return ($response->content, $response);
                   1731:     } else {
                   1732: 	return $response->content;
1.942     foxr     1733:     }
1.324     www      1734: }
                   1735: 
                   1736: sub externalssi {
                   1737:     my ($url)=@_;
                   1738:     my $ua=new LWP::UserAgent;
                   1739:     my $request=new HTTP::Request('GET',$url);
                   1740:     my $response=$ua->request($request);
1.15      www      1741:     return $response->content;
                   1742: }
1.254     www      1743: 
1.492     albertel 1744: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1745: 
                   1746: sub allowuploaded {
                   1747:     my ($srcurl,$url)=@_;
                   1748:     $url=&clutter(&declutter($url));
                   1749:     my $dir=$url;
                   1750:     $dir=~s/\/[^\/]+$//;
                   1751:     my %httpref=();
                   1752:     my $httpurl=&hreflocation('',$url);
                   1753:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1754:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1755: }
1.477     raeburn  1756: 
1.478     albertel 1757: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1758: # input: action, courseID, current domain, intended
1.637     raeburn  1759: #        path to file, source of file, instruction to parse file for objects,
                   1760: #        ref to hash for embedded objects,
                   1761: #        ref to hash for codebase of java objects.
                   1762: #
1.485     raeburn  1763: # output: url to file (if action was uploaddoc), 
                   1764: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1765: #
1.478     albertel 1766: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1767: # course.
1.477     raeburn  1768: #
1.478     albertel 1769: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1770: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1771: #          course's home server.
1.477     raeburn  1772: #
1.478     albertel 1773: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1774: #          be copied from $source (current location) to 
                   1775: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1776: #         and will then be copied to
                   1777: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1778: #         course's home server.
1.485     raeburn  1779: #
1.481     raeburn  1780: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1781: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1782: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1783: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1784: #         in course's home server.
1.637     raeburn  1785: #
1.477     raeburn  1786: 
                   1787: sub process_coursefile {
1.638     albertel 1788:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1789:     my $fetchresult;
1.638     albertel 1790:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1791:     if ($action eq 'propagate') {
1.638     albertel 1792:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1793: 			     $home);
1.481     raeburn  1794:     } else {
1.477     raeburn  1795:         my $fpath = '';
                   1796:         my $fname = $file;
1.478     albertel 1797:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1798:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1799:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1800:         if ($action eq 'copy') {
                   1801:             if ($source eq '') {
                   1802:                 $fetchresult = 'no source file';
                   1803:                 return $fetchresult;
                   1804:             } else {
                   1805:                 my $destination = $filepath.'/'.$fname;
                   1806:                 rename($source,$destination);
                   1807:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1808:                                  $home);
1.481     raeburn  1809:             }
                   1810:         } elsif ($action eq 'uploaddoc') {
                   1811:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1812:             print $fh $env{'form.'.$source};
1.481     raeburn  1813:             close($fh);
1.637     raeburn  1814:             if ($parser eq 'parse') {
                   1815:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1816:                 unless ($parse_result eq 'ok') {
                   1817:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1818:                 }
                   1819:             }
1.477     raeburn  1820:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1821:                                  $home);
1.481     raeburn  1822:             if ($fetchresult eq 'ok') {
                   1823:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1824:             } else {
                   1825:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1826:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1827:                 return '/adm/notfound.html';
                   1828:             }
1.477     raeburn  1829:         }
                   1830:     }
1.485     raeburn  1831:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1832:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1833:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1834:     }
                   1835:     return $fetchresult;
                   1836: }
                   1837: 
1.637     raeburn  1838: sub build_filepath {
                   1839:     my ($fpath) = @_;
                   1840:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1841:     unless ($fpath eq '') {
                   1842:         my @parts=split('/',$fpath);
                   1843:         foreach my $part (@parts) {
                   1844:             $filepath.= '/'.$part;
                   1845:             if ((-e $filepath)!=1) {
                   1846:                 mkdir($filepath,0777);
                   1847:             }
                   1848:         }
                   1849:     }
                   1850:     return $filepath;
                   1851: }
                   1852: 
                   1853: sub store_edited_file {
1.638     albertel 1854:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1855:     my $file = $primary_url;
                   1856:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1857:     my $fpath = '';
                   1858:     my $fname = $file;
                   1859:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1860:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1861:     my $filepath = &build_filepath($fpath);
                   1862:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1863:     print $fh $content;
                   1864:     close($fh);
1.638     albertel 1865:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1866:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1867: 			  $home);
1.637     raeburn  1868:     if ($$fetchresult eq 'ok') {
                   1869:         return '/uploaded/'.$fpath.'/'.$fname;
                   1870:     } else {
1.638     albertel 1871:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1872: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1873:         return '/adm/notfound.html';
                   1874:     }
                   1875: }
                   1876: 
1.531     albertel 1877: sub clean_filename {
1.831     albertel 1878:     my ($fname,$args)=@_;
1.315     www      1879: # Replace Windows backslashes by forward slashes
1.257     www      1880:     $fname=~s/\\/\//g;
1.831     albertel 1881:     if (!$args->{'keep_path'}) {
                   1882:         # Get rid of everything but the actual filename
                   1883: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1884:     }
1.315     www      1885: # Replace spaces by underscores
                   1886:     $fname=~s/\s+/\_/g;
                   1887: # Replace all other weird characters by nothing
1.831     albertel 1888:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1889: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1890: # numbers
                   1891:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1892:     return $fname;
                   1893: }
                   1894: 
1.608     albertel 1895: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1896: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1897: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1898: #        $coursedoc - if true up to the current course
                   1899: #                     if false
                   1900: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1901: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1902: #        $allfiles - reference to hash for embedded objects
                   1903: #        $codebase - reference to hash for codebase of java objects
                   1904: #        $desuname - username for permanent storage of uploaded file
                   1905: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1906: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1907: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1908: # 
1.686     albertel 1909: # output: url of file in userspace, or error: <message> 
                   1910: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1911: 
                   1912: 
1.531     albertel 1913: sub userfileupload {
1.860     raeburn  1914:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1915:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1916:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1917:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1918:     $fname=&clean_filename($fname);
1.315     www      1919: # See if there is anything left
1.257     www      1920:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1921:     chop($env{'form.'.$formname});
1.523     raeburn  1922:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1923:         my $now = time;
                   1924:         my $filepath = 'tmp/helprequests/'.$now;
                   1925:         my @parts=split(/\//,$filepath);
                   1926:         my $fullpath = $perlvar{'lonDaemons'};
                   1927:         for (my $i=0;$i<@parts;$i++) {
                   1928:             $fullpath .= '/'.$parts[$i];
                   1929:             if ((-e $fullpath)!=1) {
                   1930:                 mkdir($fullpath,0777);
                   1931:             }
                   1932:         }
                   1933:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1934:         print $fh $env{'form.'.$formname};
1.523     raeburn  1935:         close($fh);
1.741     raeburn  1936:         return $fullpath.'/'.$fname;
                   1937:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1938:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1939:                        '_'.$env{'user.domain'}.'/pending';
                   1940:         my @parts=split(/\//,$filepath);
                   1941:         my $fullpath = $perlvar{'lonDaemons'};
                   1942:         for (my $i=0;$i<@parts;$i++) {
                   1943:             $fullpath .= '/'.$parts[$i];
                   1944:             if ((-e $fullpath)!=1) {
                   1945:                 mkdir($fullpath,0777);
                   1946:             }
                   1947:         }
                   1948:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1949:         print $fh $env{'form.'.$formname};
                   1950:         close($fh);
                   1951:         return $fullpath.'/'.$fname;
1.523     raeburn  1952:     }
1.719     banghart 1953:     
1.258     www      1954: # Create the directory if not present
1.493     albertel 1955:     $fname="$subdir/$fname";
1.259     www      1956:     if ($coursedoc) {
1.638     albertel 1957: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1958: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1959:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1960:             return &finishuserfileupload($docuname,$docudom,
                   1961: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1962: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1963:         } else {
1.620     albertel 1964:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1965:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1966: 				       $fname,$formname,$parser,
                   1967: 				       $allfiles,$codebase);
1.481     raeburn  1968:         }
1.719     banghart 1969:     } elsif (defined($destuname)) {
                   1970:         my $docuname=$destuname;
                   1971:         my $docudom=$destudom;
1.860     raeburn  1972: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1973: 				     $parser,$allfiles,$codebase,
                   1974:                                      $thumbwidth,$thumbheight);
1.719     banghart 1975:         
1.259     www      1976:     } else {
1.638     albertel 1977:         my $docuname=$env{'user.name'};
                   1978:         my $docudom=$env{'user.domain'};
1.714     raeburn  1979:         if (exists($env{'form.group'})) {
                   1980:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1981:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1982:         }
1.860     raeburn  1983: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1984: 				     $parser,$allfiles,$codebase,
                   1985:                                      $thumbwidth,$thumbheight);
1.259     www      1986:     }
1.271     www      1987: }
                   1988: 
                   1989: sub finishuserfileupload {
1.860     raeburn  1990:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1991:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1992:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1993:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1994:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1995:     $file=$fname;
                   1996:     if ($fname=~m|/|) {
                   1997:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1998: 	$path.=$fnamepath.'/';
                   1999:     }
1.259     www      2000:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2001:     my $count;
                   2002:     for ($count=4;$count<=$#parts;$count++) {
                   2003:         $filepath.="/$parts[$count]";
                   2004:         if ((-e $filepath)!=1) {
                   2005: 	    mkdir($filepath,0777);
                   2006:         }
                   2007:     }
                   2008: # Save the file
                   2009:     {
1.701     albertel 2010: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2011: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2012: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2013: 	    return '/adm/notfound.html';
                   2014: 	}
                   2015: 	if (!print FH ($env{'form.'.$formname})) {
                   2016: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2017: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2018: 	    return '/adm/notfound.html';
                   2019: 	}
1.570     albertel 2020: 	close(FH);
1.258     www      2021:     }
1.637     raeburn  2022:     if ($parser eq 'parse') {
1.638     albertel 2023:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2024: 						   $codebase);
1.637     raeburn  2025:         unless ($parse_result eq 'ok') {
1.638     albertel 2026:             &logthis('Failed to parse '.$filepath.$file.
                   2027: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2028:         }
                   2029:     }
1.860     raeburn  2030:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2031:         my $input = $filepath.'/'.$file;
                   2032:         my $output = $filepath.'/'.'tn-'.$file;
                   2033:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2034:         system("convert -sample $thumbsize $input $output");
                   2035:         if (-e $filepath.'/'.'tn-'.$file) {
                   2036:             $fetchthumb  = 1; 
                   2037:         }
                   2038:     }
1.858     raeburn  2039:  
1.259     www      2040: # Notify homeserver to grep it
                   2041: #
1.638     albertel 2042:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2043:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2044:     if ($fetchresult eq 'ok') {
1.860     raeburn  2045:         if ($fetchthumb) {
                   2046:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2047:             if ($thumbresult ne 'ok') {
                   2048:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2049:                          $docuhome.': '.$thumbresult);
                   2050:             }
                   2051:         }
1.259     www      2052: #
1.258     www      2053: # Return the URL to it
1.494     albertel 2054:         return '/uploaded/'.$path.$file;
1.263     www      2055:     } else {
1.494     albertel 2056:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2057: 		 ': '.$fetchresult);
1.263     www      2058:         return '/adm/notfound.html';
1.858     raeburn  2059:     }
1.493     albertel 2060: }
                   2061: 
1.637     raeburn  2062: sub extract_embedded_items {
1.648     raeburn  2063:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2064:     my @state = ();
                   2065:     my %javafiles = (
                   2066:                       codebase => '',
                   2067:                       code => '',
                   2068:                       archive => ''
                   2069:                     );
                   2070:     my %mediafiles = (
                   2071:                       src => '',
                   2072:                       movie => '',
                   2073:                      );
1.648     raeburn  2074:     my $p;
                   2075:     if ($content) {
                   2076:         $p = HTML::LCParser->new($content);
                   2077:     } else {
                   2078:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2079:     }
1.641     albertel 2080:     while (my $t=$p->get_token()) {
1.640     albertel 2081: 	if ($t->[0] eq 'S') {
                   2082: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2083: 	    push(@state, $tagname);
1.648     raeburn  2084:             if (lc($tagname) eq 'allow') {
                   2085:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2086:             }
1.640     albertel 2087: 	    if (lc($tagname) eq 'img') {
                   2088: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2089: 	    }
1.886     albertel 2090: 	    if (lc($tagname) eq 'a') {
                   2091: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2092: 	    }
1.645     raeburn  2093:             if (lc($tagname) eq 'script') {
                   2094:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2095:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2096:                 } else {
                   2097:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2098:                 }
                   2099:             }
                   2100:             if (lc($tagname) eq 'link') {
                   2101:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2102:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2103:                 }
                   2104:             }
1.640     albertel 2105: 	    if (lc($tagname) eq 'object' ||
                   2106: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2107: 		foreach my $item (keys(%javafiles)) {
                   2108: 		    $javafiles{$item} = '';
                   2109: 		}
                   2110: 	    }
                   2111: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2112: 		my $name = lc($attr->{'name'});
                   2113: 		foreach my $item (keys(%javafiles)) {
                   2114: 		    if ($name eq $item) {
                   2115: 			$javafiles{$item} = $attr->{'value'};
                   2116: 			last;
                   2117: 		    }
                   2118: 		}
                   2119: 		foreach my $item (keys(%mediafiles)) {
                   2120: 		    if ($name eq $item) {
                   2121: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2122: 			last;
                   2123: 		    }
                   2124: 		}
                   2125: 	    }
                   2126: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2127: 		foreach my $item (keys(%javafiles)) {
                   2128: 		    if ($attr->{$item}) {
                   2129: 			$javafiles{$item} = $attr->{$item};
                   2130: 			last;
                   2131: 		    }
                   2132: 		}
                   2133: 		foreach my $item (keys(%mediafiles)) {
                   2134: 		    if ($attr->{$item}) {
                   2135: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2136: 			last;
                   2137: 		    }
                   2138: 		}
                   2139: 	    }
                   2140: 	} elsif ($t->[0] eq 'E') {
                   2141: 	    my ($tagname) = ($t->[1]);
                   2142: 	    if ($javafiles{'codebase'} ne '') {
                   2143: 		$javafiles{'codebase'} .= '/';
                   2144: 	    }  
                   2145: 	    if (lc($tagname) eq 'applet' ||
                   2146: 		lc($tagname) eq 'object' ||
                   2147: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2148: 		) {
                   2149: 		foreach my $item (keys(%javafiles)) {
                   2150: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2151: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2152: 			&add_filetype($allfiles,$file,$item);
                   2153: 		    }
                   2154: 		}
                   2155: 	    } 
                   2156: 	    pop @state;
                   2157: 	}
                   2158:     }
1.637     raeburn  2159:     return 'ok';
                   2160: }
                   2161: 
1.639     albertel 2162: sub add_filetype {
                   2163:     my ($allfiles,$file,$type)=@_;
                   2164:     if (exists($allfiles->{$file})) {
                   2165: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2166: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2167: 	}
                   2168:     } else {
                   2169: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2170:     }
                   2171: }
                   2172: 
1.493     albertel 2173: sub removeuploadedurl {
                   2174:     my ($url)=@_;
                   2175:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2176:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2177: }
                   2178: 
                   2179: sub removeuserfile {
                   2180:     my ($docuname,$docudom,$fname)=@_;
                   2181:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2182:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2183:     if ($result eq 'ok') {
                   2184:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2185:             my $metafile = $fname.'.meta';
                   2186:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2187: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2188:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2189:             my $sqlresult = 
1.823     albertel 2190:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2191:                                         'portfolio_metadata',$group,
                   2192:                                         'delete');
1.798     raeburn  2193:         }
                   2194:     }
                   2195:     return $result;
1.257     www      2196: }
1.15      www      2197: 
1.530     albertel 2198: sub mkdiruserfile {
                   2199:     my ($docuname,$docudom,$dir)=@_;
                   2200:     my $home=&homeserver($docuname,$docudom);
                   2201:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2202: }
                   2203: 
1.531     albertel 2204: sub renameuserfile {
                   2205:     my ($docuname,$docudom,$old,$new)=@_;
                   2206:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2207:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2208:                         &escape("$old").':'.&escape("$new"),$home);
                   2209:     if ($result eq 'ok') {
                   2210:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2211:             my $oldmeta = $old.'.meta';
                   2212:             my $newmeta = $new.'.meta';
                   2213:             my $metaresult = 
                   2214:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2215: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2216:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2217:             my $sqlresult = 
1.823     albertel 2218:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2219:                                         'portfolio_metadata',$group,
                   2220:                                         'delete');
1.798     raeburn  2221:         }
                   2222:     }
                   2223:     return $result;
1.531     albertel 2224: }
                   2225: 
1.14      www      2226: # ------------------------------------------------------------------------- Log
                   2227: 
                   2228: sub log {
                   2229:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2230:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2231: }
                   2232: 
                   2233: # ------------------------------------------------------------------ Course Log
1.352     www      2234: #
                   2235: # This routine flushes several buffers of non-mission-critical nature
                   2236: #
1.157     www      2237: 
                   2238: sub flushcourselogs {
1.352     www      2239:     &logthis('Flushing log buffers');
                   2240: #
                   2241: # course logs
                   2242: # This is a log of all transactions in a course, which can be used
                   2243: # for data mining purposes
                   2244: #
                   2245: # It also collects the courseid database, which lists last transaction
                   2246: # times and course titles for all courseids
                   2247: #
                   2248:     my %courseidbuffer=();
1.921     raeburn  2249:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2250:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2251: 		          &escape($courselogs{$crsid}),
                   2252: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2253: 	    delete $courselogs{$crsid};
                   2254:         } else {
                   2255:             &logthis('Failed to flush log buffer for '.$crsid);
                   2256:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2257:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2258:                         " exceeded maximum size, deleting.</font>");
                   2259:                delete $courselogs{$crsid};
                   2260:             }
1.352     www      2261:         }
1.920     raeburn  2262:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2263:             'description' => $coursedescrbuf{$crsid},
                   2264:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2265:             'type'        => $coursetypebuf{$crsid},
                   2266:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2267:         };
1.191     harris41 2268:     }
1.352     www      2269: #
                   2270: # Write course id database (reverse lookup) to homeserver of courses 
                   2271: # Is used in pickcourse
                   2272: #
1.840     albertel 2273:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2274:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2275:                                     $courseidbuffer{$crs_home},
                   2276:                                     $crs_home,'timeonly');
1.352     www      2277:     }
                   2278: #
                   2279: # File accesses
                   2280: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2281: #
1.449     matthew  2282:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2283:         if ($entry =~ /___count$/) {
                   2284:             my ($dom,$name);
1.807     albertel 2285:             ($dom,$name,undef)=
1.811     albertel 2286: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2287:             if (! defined($dom) || $dom eq '' || 
                   2288:                 ! defined($name) || $name eq '') {
1.620     albertel 2289:                 my $cid = $env{'request.course.id'};
                   2290:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2291:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2292:             }
1.450     matthew  2293:             my $value = $accesshash{$entry};
                   2294:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2295:             my %temphash=($url => $value);
1.449     matthew  2296:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2297:             if ($result eq 'ok') {
                   2298:                 delete $accesshash{$entry};
                   2299:             } elsif ($result eq 'unknown_cmd') {
                   2300:                 # Target server has old code running on it.
1.450     matthew  2301:                 my %temphash=($entry => $value);
1.449     matthew  2302:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2303:                     delete $accesshash{$entry};
                   2304:                 }
                   2305:             }
                   2306:         } else {
1.811     albertel 2307:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2308:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2309:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2310:                 delete $accesshash{$entry};
                   2311:             }
1.185     www      2312:         }
1.191     harris41 2313:     }
1.352     www      2314: #
                   2315: # Roles
                   2316: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2317: #
1.800     albertel 2318:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2319:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2320: 	    split(/\:/,$entry);
                   2321:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2322:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2323:                 $rudom,$runame) eq 'ok') {
                   2324: 	    delete $userrolehash{$entry};
                   2325:         }
                   2326:     }
1.662     raeburn  2327: #
                   2328: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2329: #
                   2330:     my %domrolebuffer = ();
                   2331:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2332:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2333:         if ($domrolebuffer{$rudom}) {
                   2334:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2335:                       '='.&escape($domainrolehash{$entry});
                   2336:         } else {
                   2337:             $domrolebuffer{$rudom}.=&escape($entry).
                   2338:                       '='.&escape($domainrolehash{$entry});
                   2339:         }
                   2340:         delete $domainrolehash{$entry};
                   2341:     }
                   2342:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2343: 	my %servers = &get_servers($dom,'library');
                   2344: 	foreach my $tryserver (keys(%servers)) {
                   2345: 	    unless (&reply('domroleput:'.$dom.':'.
                   2346: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2347: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2348: 	    }
1.662     raeburn  2349:         }
                   2350:     }
1.186     www      2351:     $dumpcount++;
1.157     www      2352: }
                   2353: 
                   2354: sub courselog {
                   2355:     my $what=shift;
1.158     www      2356:     $what=time.':'.$what;
1.620     albertel 2357:     unless ($env{'request.course.id'}) { return ''; }
                   2358:     $coursedombuf{$env{'request.course.id'}}=
                   2359:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2360:     $coursenumbuf{$env{'request.course.id'}}=
                   2361:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2362:     $coursehombuf{$env{'request.course.id'}}=
                   2363:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2364:     $coursedescrbuf{$env{'request.course.id'}}=
                   2365:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2366:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2367:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2368:     $courseownerbuf{$env{'request.course.id'}}=
                   2369:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2370:     $coursetypebuf{$env{'request.course.id'}}=
                   2371:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2372:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2373: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2374:     } else {
1.620     albertel 2375: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2376:     }
1.620     albertel 2377:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2378: 	&flushcourselogs();
                   2379:     }
1.158     www      2380: }
                   2381: 
                   2382: sub courseacclog {
                   2383:     my $fnsymb=shift;
1.620     albertel 2384:     unless ($env{'request.course.id'}) { return ''; }
                   2385:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2386:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2387:         $what.=':POST';
1.583     matthew  2388:         # FIXME: Probably ought to escape things....
1.800     albertel 2389: 	foreach my $key (keys(%env)) {
                   2390:             if ($key=~/^form\.(.*)/) {
                   2391: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2392:             }
1.191     harris41 2393:         }
1.583     matthew  2394:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2395:         # FIXME: We should not be depending on a form parameter that someone
                   2396:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2397:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2398:             $what.= ':POST';
                   2399:             # FIXME: Probably ought to escape things....
                   2400:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2401:                                  'crsdiscuss') {
1.620     albertel 2402:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2403:             }
                   2404:         }
1.158     www      2405:     }
                   2406:     &courselog($what);
1.149     www      2407: }
                   2408: 
1.185     www      2409: sub countacc {
                   2410:     my $url=&declutter(shift);
1.458     matthew  2411:     return if (! defined($url) || $url eq '');
1.620     albertel 2412:     unless ($env{'request.course.id'}) { return ''; }
                   2413:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2414:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2415:     $accesshash{$key}++;
1.185     www      2416: }
1.349     www      2417: 
1.361     www      2418: sub linklog {
                   2419:     my ($from,$to)=@_;
                   2420:     $from=&declutter($from);
                   2421:     $to=&declutter($to);
                   2422:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2423:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2424: }
                   2425:   
1.349     www      2426: sub userrolelog {
                   2427:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2428:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2429:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2430:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2431:         ($trole=~/^ta/)) {
1.350     www      2432:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2433:        $userrolehash
                   2434:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2435:                     =$tend.':'.$tstart;
1.662     raeburn  2436:     }
1.898     albertel 2437:     if (($env{'request.role'} =~ /dc\./) &&
                   2438: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2439: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2440: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2441:        $userrolehash
                   2442:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2443:                     =$tend.':'.$tstart;
                   2444:     }
1.662     raeburn  2445:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2446:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2447:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2448:         ($trole=~/^sc/)) {
                   2449:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2450:        $domainrolehash
                   2451:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2452:                     = $tend.':'.$tstart;
                   2453:     }
1.351     www      2454: }
                   2455: 
                   2456: sub get_course_adv_roles {
1.948     raeburn  2457:     my ($cid,$codes) = @_;
1.620     albertel 2458:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2459:     my %coursehash=&coursedescription($cid);
1.470     www      2460:     my %nothide=();
1.800     albertel 2461:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2462:         if ($user !~ /:/) {
                   2463: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2464:         } else {
                   2465:             $nothide{$user}=1;
                   2466:         }
1.470     www      2467:     }
1.351     www      2468:     my %returnhash=();
                   2469:     my %dumphash=
                   2470:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2471:     my $now=time;
1.800     albertel 2472:     foreach my $entry (keys %dumphash) {
                   2473: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2474:         if (($tstart) && ($tstart<0)) { next; }
                   2475:         if (($tend) && ($tend<$now)) { next; }
                   2476:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2477:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2478: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2479: 	if ((&privileged($username,$domain)) && 
                   2480: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2481: 	if ($role eq 'cr') { next; }
1.948     raeburn  2482:         if ($codes) {
                   2483:             if ($section) { $role .= ':'.$section; }
                   2484:             if ($returnhash{$role}) {
                   2485:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2486:             } else {
                   2487:                 $returnhash{$role}=$username.':'.$domain;
                   2488:             }
1.351     www      2489:         } else {
1.948     raeburn  2490:             my $key=&plaintext($role);
                   2491:             if ($section) { $key.=' (Section '.$section.')'; }
                   2492:             if ($returnhash{$key}) {
                   2493: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2494:             } else {
                   2495:                 $returnhash{$key}=$username.':'.$domain;
                   2496:             }
1.351     www      2497:         }
1.948     raeburn  2498:     }
1.400     www      2499:     return %returnhash;
                   2500: }
                   2501: 
                   2502: sub get_my_roles {
1.937     raeburn  2503:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2504:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2505:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2506:     my (%dumphash,%nothide);
1.858     raeburn  2507:     if ($context eq 'userroles') { 
                   2508:         %dumphash = &dump('roles',$udom,$uname);
                   2509:     } else {
                   2510:         %dumphash=
1.400     www      2511:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2512:         if ($hidepriv) {
                   2513:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2514:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2515:                 if ($user !~ /:/) {
                   2516:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2517:                 } else {
                   2518:                     $nothide{$user} = 1;
                   2519:                 }
                   2520:             }
                   2521:         }
1.858     raeburn  2522:     }
1.400     www      2523:     my %returnhash=();
                   2524:     my $now=time;
1.800     albertel 2525:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2526:         my ($role,$tend,$tstart);
                   2527:         if ($context eq 'userroles') {
                   2528: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2529:         } else {
                   2530:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2531:         }
1.400     www      2532:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2533:         my $status = 'active';
1.939     raeburn  2534:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2535:             $status = 'previous';
                   2536:         } 
                   2537:         if (($tstart) && ($now<$tstart)) {
                   2538:             $status = 'future';
                   2539:         }
                   2540:         if (ref($types) eq 'ARRAY') {
                   2541:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2542:                 next;
                   2543:             } 
                   2544:         } else {
                   2545:             if ($status ne 'active') {
                   2546:                 next;
                   2547:             }
                   2548:         }
1.867     raeburn  2549:         my ($rolecode,$username,$domain,$section,$area);
                   2550:         if ($context eq 'userroles') {
                   2551:             ($area,$rolecode) = split(/_/,$entry);
                   2552:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2553:         } else {
                   2554:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2555:         }
1.832     raeburn  2556:         if (ref($roledoms) eq 'ARRAY') {
                   2557:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2558:                 next;
                   2559:             }
                   2560:         }
                   2561:         if (ref($roles) eq 'ARRAY') {
                   2562:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2563:                 if ($role =~ /^cr\//) {
                   2564:                     if (!grep(/^cr$/,@{$roles})) {
                   2565:                         next;
                   2566:                     }
                   2567:                 } else {
                   2568:                     next;
                   2569:                 }
1.832     raeburn  2570:             }
1.867     raeburn  2571:         }
1.937     raeburn  2572:         if ($hidepriv) {
                   2573:             if ((&privileged($username,$domain)) &&
                   2574:                 (!$nothide{$username.':'.$domain})) { 
                   2575:                 next;
                   2576:             }
                   2577:         }
1.933     raeburn  2578:         if ($withsec) {
                   2579:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2580:                 $tstart.':'.$tend;
                   2581:         } else {
                   2582:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2583:         }
1.832     raeburn  2584:     }
1.373     www      2585:     return %returnhash;
1.399     www      2586: }
                   2587: 
                   2588: # ----------------------------------------------------- Frontpage Announcements
                   2589: #
                   2590: #
                   2591: 
                   2592: sub postannounce {
                   2593:     my ($server,$text)=@_;
1.844     albertel 2594:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2595:     unless ($text=~/\w/) { $text=''; }
                   2596:     return &reply('setannounce:'.&escape($text),$server);
                   2597: }
                   2598: 
                   2599: sub getannounce {
1.448     albertel 2600: 
                   2601:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2602: 	my $announcement='';
1.800     albertel 2603: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2604: 	close($fh);
1.399     www      2605: 	if ($announcement=~/\w/) { 
                   2606: 	    return 
                   2607:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2608:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2609: 	} else {
                   2610: 	    return '';
                   2611: 	}
                   2612:     } else {
                   2613: 	return '';
                   2614:     }
1.351     www      2615: }
1.353     www      2616: 
                   2617: # ---------------------------------------------------------- Course ID routines
                   2618: # Deal with domain's nohist_courseid.db files
                   2619: #
                   2620: 
                   2621: sub courseidput {
1.921     raeburn  2622:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2623:     my $outcome;
                   2624:     if ($caller eq 'timeonly') {
                   2625:         my $cids = '';
                   2626:         foreach my $item (keys(%$storehash)) {
                   2627:             $cids.=&escape($item).'&';
                   2628:         }
                   2629:         $cids=~s/\&$//;
                   2630:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2631:                           $coursehome);       
                   2632:     } else {
                   2633:         my $items = '';
                   2634:         foreach my $item (keys(%$storehash)) {
                   2635:             $items.= &escape($item).'='.
                   2636:                      &freeze_escape($$storehash{$item}).'&';
                   2637:         }
                   2638:         $items=~s/\&$//;
                   2639:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2640:                           $coursehome);
1.918     raeburn  2641:     }
                   2642:     if ($outcome eq 'unknown_cmd') {
                   2643:         my $what;
                   2644:         foreach my $cid (keys(%$storehash)) {
                   2645:             $what .= &escape($cid).'=';
1.921     raeburn  2646:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2647:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2648:             }
                   2649:             $what =~ s/\:$/&/;
                   2650:         }
                   2651:         $what =~ s/\&$//;  
                   2652:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2653:     } else {
                   2654:         return $outcome;
                   2655:     }
1.353     www      2656: }
                   2657: 
                   2658: sub courseiddump {
1.921     raeburn  2659:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2660:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
                   2661:         $selfenrollonly)=@_;
1.918     raeburn  2662:     my $as_hash = 1;
                   2663:     my %returnhash;
                   2664:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2665:     my %libserv = &all_library();
                   2666:     foreach my $tryserver (keys(%libserv)) {
                   2667:         if ( (  $hostidflag == 1 
                   2668: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2669: 	     || (!defined($hostidflag)) ) {
                   2670: 
1.918     raeburn  2671: 	    if (($domfilter eq '') ||
                   2672: 		(&host_domain($tryserver) eq $domfilter)) {
                   2673:                 my $rep = 
                   2674:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2675:                          $sincefilter.':'.&escape($descfilter).':'.
                   2676:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2677:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2678:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   2679:                          &escape($selfenrollonly),$tryserver);
1.918     raeburn  2680:                 my @pairs=split(/\&/,$rep);
                   2681:                 foreach my $item (@pairs) {
                   2682:                     my ($key,$value)=split(/\=/,$item,2);
                   2683:                     $key = &unescape($key);
                   2684:                     next if ($key =~ /^error: 2 /);
                   2685:                     my $result = &thaw_unescape($value);
                   2686:                     if (ref($result) eq 'HASH') {
                   2687:                         $returnhash{$key}=$result;
                   2688:                     } else {
1.921     raeburn  2689:                         my @responses = split(/:/,$value);
                   2690:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2691:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2692:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2693:                         }
                   2694:                     } 
1.353     www      2695:                 }
                   2696:             }
                   2697:         }
                   2698:     }
                   2699:     return %returnhash;
                   2700: }
                   2701: 
1.658     raeburn  2702: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2703: 
                   2704: sub dcmailput {
1.685     raeburn  2705:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2706:     my $status = &Apache::lonnet::critical(
1.740     www      2707:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2708:        &escape($message),$server);
1.662     raeburn  2709:     return $status;
                   2710: }
                   2711: 
1.658     raeburn  2712: sub dcmaildump {
                   2713:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2714:     my %returnhash=();
1.846     albertel 2715: 
                   2716:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2717:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2718:                                                          &escape($enddate).':';
                   2719: 	my @esc_senders=map { &escape($_)} @$senders;
                   2720: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2721: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2722:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2723:             if (($key) && ($value)) {
                   2724:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2725:             }
                   2726:         }
                   2727:     }
                   2728:     return %returnhash;
                   2729: }
1.662     raeburn  2730: # ---------------------------------------------------------- Domain roles
                   2731: 
                   2732: sub get_domain_roles {
                   2733:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2734:     if (undef($startdate) || $startdate eq '') {
                   2735:         $startdate = '.';
                   2736:     }
                   2737:     if (undef($enddate) || $enddate eq '') {
                   2738:         $enddate = '.';
                   2739:     }
1.922     raeburn  2740:     my $rolelist;
                   2741:     if (ref($roles) eq 'ARRAY') {
                   2742:         $rolelist = join(':',@{$roles});
                   2743:     }
1.662     raeburn  2744:     my %personnel = ();
1.841     albertel 2745: 
                   2746:     my %servers = &get_servers($dom,'library');
                   2747:     foreach my $tryserver (keys(%servers)) {
                   2748: 	%{$personnel{$tryserver}}=();
                   2749: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2750: 					    &escape($startdate).':'.
                   2751: 					    &escape($enddate).':'.
                   2752: 					    &escape($rolelist), $tryserver))) {
                   2753: 	    my ($key,$value) = split(/\=/,$line,2);
                   2754: 	    if (($key) && ($value)) {
                   2755: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2756: 	    }
                   2757: 	}
1.662     raeburn  2758:     }
                   2759:     return %personnel;
                   2760: }
1.658     raeburn  2761: 
1.149     www      2762: # ----------------------------------------------------------- Check out an item
                   2763: 
1.504     albertel 2764: sub get_first_access {
                   2765:     my ($type,$argsymb)=@_;
1.790     albertel 2766:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2767:     if ($argsymb) { $symb=$argsymb; }
                   2768:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2769:     if ($type eq 'course') {
                   2770: 	$res='course';
                   2771:     } elsif ($type eq 'map') {
1.588     albertel 2772: 	$res=&symbread($map);
                   2773:     } else {
                   2774: 	$res=$symb;
                   2775:     }
                   2776:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2777:     return $times{"$courseid\0$res"};
1.504     albertel 2778: }
                   2779: 
                   2780: sub set_first_access {
                   2781:     my ($type)=@_;
1.790     albertel 2782:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2783:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2784:     if ($type eq 'course') {
                   2785: 	$res='course';
                   2786:     } elsif ($type eq 'map') {
1.588     albertel 2787: 	$res=&symbread($map);
                   2788:     } else {
                   2789: 	$res=$symb;
                   2790:     }
                   2791:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2792:     if (!$firstaccess) {
1.588     albertel 2793: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2794:     }
                   2795:     return 'already_set';
1.504     albertel 2796: }
                   2797: 
1.149     www      2798: sub checkout {
                   2799:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2800:     my $now=time;
                   2801:     my $lonhost=$perlvar{'lonHostID'};
                   2802:     my $infostr=&escape(
1.234     www      2803:                  'CHECKOUTTOKEN&'.
1.149     www      2804:                  $tuname.'&'.
                   2805:                  $tudom.'&'.
                   2806:                  $tcrsid.'&'.
                   2807:                  $symb.'&'.
                   2808: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2809:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2810:     if ($token=~/^error\:/) { 
1.672     albertel 2811:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2812:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2813:                  "</font>");
                   2814:         return ''; 
                   2815:     }
                   2816: 
1.149     www      2817:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2818:     $token=~tr/a-z/A-Z/;
                   2819: 
1.153     www      2820:     my %infohash=('resource.0.outtoken' => $token,
                   2821:                   'resource.0.checkouttime' => $now,
                   2822:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2823: 
                   2824:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2825:        return '';
1.151     www      2826:     } else {
1.672     albertel 2827:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2828:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2829:                  "</font>");
1.149     www      2830:     }    
                   2831: 
                   2832:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2833:                          &escape('Checkout '.$infostr.' - '.
                   2834:                                                  $token)) ne 'ok') {
                   2835: 	return '';
1.151     www      2836:     } else {
1.672     albertel 2837:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2838:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2839:                  "</font>");
1.149     www      2840:     }
1.151     www      2841:     return $token;
1.149     www      2842: }
                   2843: 
                   2844: # ------------------------------------------------------------ Check in an item
                   2845: 
                   2846: sub checkin {
                   2847:     my $token=shift;
1.150     www      2848:     my $now=time;
                   2849:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2850:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2851:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2852:     $dtoken=~s/\W/\_/g;
1.234     www      2853:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2854:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2855: 
1.154     www      2856:     unless (($tuname) && ($tudom)) {
                   2857:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2858:         return '';
                   2859:     }
                   2860:     
                   2861:     unless (&allowed('mgr',$tcrsid)) {
                   2862:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2863:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2864:         return '';
                   2865:     }
                   2866: 
1.153     www      2867:     my %infohash=('resource.0.intoken' => $token,
                   2868:                   'resource.0.checkintime' => $now,
                   2869:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2870: 
                   2871:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2872:        return '';
                   2873:     }    
                   2874: 
                   2875:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2876:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2877: 	return '';
                   2878:     }
                   2879: 
                   2880:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2881: }
                   2882: 
                   2883: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2884: 
                   2885: sub expirespread {
                   2886:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2887:     my $cid=$env{'request.course.id'}; 
1.110     www      2888:     if ($cid) {
                   2889:        my $now=time;
                   2890:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2891:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2892:                             $env{'course.'.$cid.'.num'}.
1.110     www      2893: 	        	    ':nohist_expirationdates:'.
                   2894:                             &escape($key).'='.$now,
1.620     albertel 2895:                             $env{'course.'.$cid.'.home'})
1.110     www      2896:     }
                   2897:     return 'ok';
1.14      www      2898: }
                   2899: 
1.109     www      2900: # ----------------------------------------------------- Devalidate Spreadsheets
                   2901: 
                   2902: sub devalidate {
1.325     www      2903:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2904:     my $cid=$env{'request.course.id'}; 
1.109     www      2905:     if ($cid) {
1.391     matthew  2906:         # delete the stored spreadsheets for
                   2907:         # - the student level sheet of this user in course's homespace
                   2908:         # - the assessment level sheet for this resource 
                   2909:         #   for this user in user's homespace
1.553     albertel 2910: 	# - current conditional state info
1.325     www      2911: 	my $key=$uname.':'.$udom.':';
1.109     www      2912:         my $status=
1.299     matthew  2913: 	    &del('nohist_calculatedsheets',
1.391     matthew  2914: 		 [$key.'studentcalc:'],
1.620     albertel 2915: 		 $env{'course.'.$cid.'.domain'},
                   2916: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2917: 		.' '.
                   2918: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2919: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2920:         unless ($status eq 'ok ok') {
                   2921:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2922:                     $uname.' at '.$udom.' for '.
1.109     www      2923: 		    $symb.': '.$status);
1.133     albertel 2924:         }
1.553     albertel 2925: 	&delenv('user.state.'.$cid);
1.109     www      2926:     }
                   2927: }
                   2928: 
1.265     albertel 2929: sub get_scalar {
                   2930:     my ($string,$end) = @_;
                   2931:     my $value;
                   2932:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2933: 	$value = $1;
                   2934:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2935: 	$value = $1;
                   2936:     }
                   2937:     return &unescape($value);
                   2938: }
                   2939: 
                   2940: sub array2str {
                   2941:   my (@array) = @_;
                   2942:   my $result=&arrayref2str(\@array);
                   2943:   $result=~s/^__ARRAY_REF__//;
                   2944:   $result=~s/__END_ARRAY_REF__$//;
                   2945:   return $result;
                   2946: }
                   2947: 
1.204     albertel 2948: sub arrayref2str {
                   2949:   my ($arrayref) = @_;
1.265     albertel 2950:   my $result='__ARRAY_REF__';
1.204     albertel 2951:   foreach my $elem (@$arrayref) {
1.265     albertel 2952:     if(ref($elem) eq 'ARRAY') {
                   2953:       $result.=&arrayref2str($elem).'&';
                   2954:     } elsif(ref($elem) eq 'HASH') {
                   2955:       $result.=&hashref2str($elem).'&';
                   2956:     } elsif(ref($elem)) {
                   2957:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2958:     } else {
                   2959:       $result.=&escape($elem).'&';
                   2960:     }
                   2961:   }
                   2962:   $result=~s/\&$//;
1.265     albertel 2963:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2964:   return $result;
                   2965: }
                   2966: 
1.168     albertel 2967: sub hash2str {
1.204     albertel 2968:   my (%hash) = @_;
                   2969:   my $result=&hashref2str(\%hash);
1.265     albertel 2970:   $result=~s/^__HASH_REF__//;
                   2971:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2972:   return $result;
                   2973: }
                   2974: 
                   2975: sub hashref2str {
                   2976:   my ($hashref)=@_;
1.265     albertel 2977:   my $result='__HASH_REF__';
1.800     albertel 2978:   foreach my $key (sort(keys(%$hashref))) {
                   2979:     if (ref($key) eq 'ARRAY') {
                   2980:       $result.=&arrayref2str($key).'=';
                   2981:     } elsif (ref($key) eq 'HASH') {
                   2982:       $result.=&hashref2str($key).'=';
                   2983:     } elsif (ref($key)) {
1.265     albertel 2984:       $result.='=';
1.800     albertel 2985:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2986:     } else {
1.800     albertel 2987: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2988:     }
                   2989: 
1.800     albertel 2990:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2991:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2992:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2993:       $result.=&hashref2str($hashref->{$key}).'&';
                   2994:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2995:        $result.='&';
1.800     albertel 2996:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2997:     } else {
1.800     albertel 2998:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2999:     }
                   3000:   }
1.168     albertel 3001:   $result=~s/\&$//;
1.265     albertel 3002:   $result .= '__END_HASH_REF__';
1.168     albertel 3003:   return $result;
                   3004: }
                   3005: 
                   3006: sub str2hash {
1.265     albertel 3007:     my ($string)=@_;
                   3008:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3009:     return %$hash;
                   3010: }
                   3011: 
                   3012: sub str2hashref {
1.168     albertel 3013:   my ($string) = @_;
1.265     albertel 3014: 
                   3015:   my %hash;
                   3016: 
                   3017:   if($string !~ /^__HASH_REF__/) {
                   3018:       if (! ($string eq '' || !defined($string))) {
                   3019: 	  $hash{'error'}='Not hash reference';
                   3020:       }
                   3021:       return (\%hash, $string);
                   3022:   }
                   3023: 
                   3024:   $string =~ s/^__HASH_REF__//;
                   3025: 
                   3026:   while($string !~ /^__END_HASH_REF__/) {
                   3027:       #key
                   3028:       my $key='';
                   3029:       if($string =~ /^__HASH_REF__/) {
                   3030:           ($key, $string)=&str2hashref($string);
                   3031:           if(defined($key->{'error'})) {
                   3032:               $hash{'error'}='Bad data';
                   3033:               return (\%hash, $string);
                   3034:           }
                   3035:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3036:           ($key, $string)=&str2arrayref($string);
                   3037:           if($key->[0] eq 'Array reference error') {
                   3038:               $hash{'error'}='Bad data';
                   3039:               return (\%hash, $string);
                   3040:           }
                   3041:       } else {
                   3042:           $string =~ s/^(.*?)=//;
1.267     albertel 3043: 	  $key=&unescape($1);
1.265     albertel 3044:       }
                   3045:       $string =~ s/^=//;
                   3046: 
                   3047:       #value
                   3048:       my $value='';
                   3049:       if($string =~ /^__HASH_REF__/) {
                   3050:           ($value, $string)=&str2hashref($string);
                   3051:           if(defined($value->{'error'})) {
                   3052:               $hash{'error'}='Bad data';
                   3053:               return (\%hash, $string);
                   3054:           }
                   3055:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3056:           ($value, $string)=&str2arrayref($string);
                   3057:           if($value->[0] eq 'Array reference error') {
                   3058:               $hash{'error'}='Bad data';
                   3059:               return (\%hash, $string);
                   3060:           }
                   3061:       } else {
                   3062: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3063:       }
                   3064:       $string =~ s/^&//;
                   3065: 
                   3066:       $hash{$key}=$value;
1.204     albertel 3067:   }
1.265     albertel 3068: 
                   3069:   $string =~ s/^__END_HASH_REF__//;
                   3070: 
                   3071:   return (\%hash, $string);
1.204     albertel 3072: }
                   3073: 
                   3074: sub str2array {
1.265     albertel 3075:     my ($string)=@_;
                   3076:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3077:     return @$array;
                   3078: }
                   3079: 
                   3080: sub str2arrayref {
1.204     albertel 3081:   my ($string) = @_;
1.265     albertel 3082:   my @array;
                   3083: 
                   3084:   if($string !~ /^__ARRAY_REF__/) {
                   3085:       if (! ($string eq '' || !defined($string))) {
                   3086: 	  $array[0]='Array reference error';
                   3087:       }
                   3088:       return (\@array, $string);
                   3089:   }
                   3090: 
                   3091:   $string =~ s/^__ARRAY_REF__//;
                   3092: 
                   3093:   while($string !~ /^__END_ARRAY_REF__/) {
                   3094:       my $value='';
                   3095:       if($string =~ /^__HASH_REF__/) {
                   3096:           ($value, $string)=&str2hashref($string);
                   3097:           if(defined($value->{'error'})) {
                   3098:               $array[0] ='Array reference error';
                   3099:               return (\@array, $string);
                   3100:           }
                   3101:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3102:           ($value, $string)=&str2arrayref($string);
                   3103:           if($value->[0] eq 'Array reference error') {
                   3104:               $array[0] ='Array reference error';
                   3105:               return (\@array, $string);
                   3106:           }
                   3107:       } else {
                   3108: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3109:       }
                   3110:       $string =~ s/^&//;
                   3111: 
                   3112:       push(@array, $value);
1.191     harris41 3113:   }
1.265     albertel 3114: 
                   3115:   $string =~ s/^__END_ARRAY_REF__//;
                   3116: 
                   3117:   return (\@array, $string);
1.168     albertel 3118: }
                   3119: 
1.167     albertel 3120: # -------------------------------------------------------------------Temp Store
                   3121: 
1.168     albertel 3122: sub tmpreset {
                   3123:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3124:   if (!$symb) {
                   3125:     $symb=&symbread();
1.620     albertel 3126:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3127:   }
                   3128:   $symb=escape($symb);
                   3129: 
1.620     albertel 3130:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3131:   $namespace=~s/\//\_/g;
                   3132:   $namespace=~s/\W//g;
                   3133: 
1.620     albertel 3134:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3135:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3136:   if ($domain eq 'public' && $stuname eq 'public') {
                   3137:       $stuname=$ENV{'REMOTE_ADDR'};
                   3138:   }
1.168     albertel 3139:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3140:   my %hash;
                   3141:   if (tie(%hash,'GDBM_File',
                   3142: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3143: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3144:     foreach my $key (keys %hash) {
1.180     albertel 3145:       if ($key=~ /:$symb/) {
1.168     albertel 3146: 	delete($hash{$key});
                   3147:       }
                   3148:     }
                   3149:   }
                   3150: }
                   3151: 
1.167     albertel 3152: sub tmpstore {
1.168     albertel 3153:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3154: 
                   3155:   if (!$symb) {
                   3156:     $symb=&symbread();
1.620     albertel 3157:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3158:   }
                   3159:   $symb=escape($symb);
                   3160: 
                   3161:   if (!$namespace) {
                   3162:     # I don't think we would ever want to store this for a course.
                   3163:     # it seems this will only be used if we don't have a course.
1.620     albertel 3164:     #$namespace=$env{'request.course.id'};
1.168     albertel 3165:     #if (!$namespace) {
1.620     albertel 3166:       $namespace=$env{'request.state'};
1.168     albertel 3167:     #}
                   3168:   }
                   3169:   $namespace=~s/\//\_/g;
                   3170:   $namespace=~s/\W//g;
1.620     albertel 3171:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3172:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3173:   if ($domain eq 'public' && $stuname eq 'public') {
                   3174:       $stuname=$ENV{'REMOTE_ADDR'};
                   3175:   }
1.168     albertel 3176:   my $now=time;
                   3177:   my %hash;
                   3178:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3179:   if (tie(%hash,'GDBM_File',
                   3180: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3181: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3182:     $hash{"version:$symb"}++;
                   3183:     my $version=$hash{"version:$symb"};
                   3184:     my $allkeys=''; 
                   3185:     foreach my $key (keys(%$storehash)) {
                   3186:       $allkeys.=$key.':';
1.591     albertel 3187:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3188:     }
                   3189:     $hash{"$version:$symb:timestamp"}=$now;
                   3190:     $allkeys.='timestamp';
                   3191:     $hash{"$version:keys:$symb"}=$allkeys;
                   3192:     if (untie(%hash)) {
                   3193:       return 'ok';
                   3194:     } else {
                   3195:       return "error:$!";
                   3196:     }
                   3197:   } else {
                   3198:     return "error:$!";
                   3199:   }
                   3200: }
1.167     albertel 3201: 
1.168     albertel 3202: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3203: 
1.168     albertel 3204: sub tmprestore {
                   3205:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3206: 
1.168     albertel 3207:   if (!$symb) {
                   3208:     $symb=&symbread();
1.620     albertel 3209:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3210:   }
                   3211:   $symb=escape($symb);
                   3212: 
1.620     albertel 3213:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3214: 
1.620     albertel 3215:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3216:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3217:   if ($domain eq 'public' && $stuname eq 'public') {
                   3218:       $stuname=$ENV{'REMOTE_ADDR'};
                   3219:   }
1.168     albertel 3220:   my %returnhash;
                   3221:   $namespace=~s/\//\_/g;
                   3222:   $namespace=~s/\W//g;
                   3223:   my %hash;
                   3224:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3225:   if (tie(%hash,'GDBM_File',
                   3226: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3227: 	  &GDBM_READER(),0640)) {
1.168     albertel 3228:     my $version=$hash{"version:$symb"};
                   3229:     $returnhash{'version'}=$version;
                   3230:     my $scope;
                   3231:     for ($scope=1;$scope<=$version;$scope++) {
                   3232:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3233:       my @keys=split(/:/,$vkeys);
                   3234:       my $key;
                   3235:       $returnhash{"$scope:keys"}=$vkeys;
                   3236:       foreach $key (@keys) {
1.591     albertel 3237: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3238: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3239:       }
                   3240:     }
1.168     albertel 3241:     if (!(untie(%hash))) {
                   3242:       return "error:$!";
                   3243:     }
                   3244:   } else {
                   3245:     return "error:$!";
                   3246:   }
                   3247:   return %returnhash;
1.167     albertel 3248: }
                   3249: 
1.9       www      3250: # ----------------------------------------------------------------------- Store
                   3251: 
                   3252: sub store {
1.124     www      3253:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3254:     my $home='';
                   3255: 
1.168     albertel 3256:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3257: 
1.213     www      3258:     $symb=&symbclean($symb);
1.122     albertel 3259:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3260: 
1.620     albertel 3261:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3262:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3263: 
                   3264:     &devalidate($symb,$stuname,$domain);
1.109     www      3265: 
                   3266:     $symb=escape($symb);
1.187     www      3267:     if (!$namespace) { 
1.620     albertel 3268:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3269:           return ''; 
                   3270:        } 
                   3271:     }
1.620     albertel 3272:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3273: 
                   3274:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3275:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3276: 
1.12      www      3277:     my $namevalue='';
1.800     albertel 3278:     foreach my $key (keys(%$storehash)) {
                   3279:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3280:     }
1.12      www      3281:     $namevalue=~s/\&$//;
1.187     www      3282:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3283:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3284: }
                   3285: 
1.47      www      3286: # -------------------------------------------------------------- Critical Store
                   3287: 
                   3288: sub cstore {
1.124     www      3289:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3290:     my $home='';
                   3291: 
1.168     albertel 3292:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3293: 
1.213     www      3294:     $symb=&symbclean($symb);
1.122     albertel 3295:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3296: 
1.620     albertel 3297:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3298:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3299: 
                   3300:     &devalidate($symb,$stuname,$domain);
1.109     www      3301: 
                   3302:     $symb=escape($symb);
1.187     www      3303:     if (!$namespace) { 
1.620     albertel 3304:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3305:           return ''; 
                   3306:        } 
                   3307:     }
1.620     albertel 3308:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3309: 
                   3310:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3311:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3312: 
1.47      www      3313:     my $namevalue='';
1.800     albertel 3314:     foreach my $key (keys(%$storehash)) {
                   3315:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3316:     }
1.47      www      3317:     $namevalue=~s/\&$//;
1.187     www      3318:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3319:     return critical
                   3320:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3321: }
                   3322: 
1.9       www      3323: # --------------------------------------------------------------------- Restore
                   3324: 
                   3325: sub restore {
1.124     www      3326:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3327:     my $home='';
                   3328: 
1.168     albertel 3329:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3330: 
1.122     albertel 3331:     if (!$symb) {
                   3332:       unless ($symb=escape(&symbread())) { return ''; }
                   3333:     } else {
1.213     www      3334:       $symb=&escape(&symbclean($symb));
1.122     albertel 3335:     }
1.188     www      3336:     if (!$namespace) { 
1.620     albertel 3337:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3338:           return ''; 
                   3339:        } 
                   3340:     }
1.620     albertel 3341:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3342:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3343:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3344:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3345: 
1.12      www      3346:     my %returnhash=();
1.800     albertel 3347:     foreach my $line (split(/\&/,$answer)) {
                   3348: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3349:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3350:     }
1.75      www      3351:     my $version;
                   3352:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3353:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3354:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3355:        }
1.75      www      3356:     }
1.13      www      3357:     return %returnhash;
1.34      www      3358: }
                   3359: 
                   3360: # ---------------------------------------------------------- Course Description
                   3361: 
                   3362: sub coursedescription {
1.731     albertel 3363:     my ($courseid,$args)=@_;
1.34      www      3364:     $courseid=~s/^\///;
1.49      www      3365:     $courseid=~s/\_/\//g;
1.34      www      3366:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3367:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3368:     my $normalid=$cdomain.'_'.$cnum;
                   3369:     # need to always cache even if we get errors otherwise we keep 
                   3370:     # trying and trying and trying to get the course description.
                   3371:     my %envhash=();
                   3372:     my %returnhash=();
1.731     albertel 3373:     
                   3374:     my $expiretime=600;
                   3375:     if ($env{'request.course.id'} eq $normalid) {
                   3376: 	$expiretime=120;
                   3377:     }
                   3378: 
                   3379:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3380:     if (!$args->{'freshen_cache'}
                   3381: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3382: 	foreach my $key (keys(%env)) {
                   3383: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3384: 	    my ($setting) = $1;
                   3385: 	    $returnhash{$setting} = $env{$key};
                   3386: 	}
                   3387: 	return %returnhash;
                   3388:     }
                   3389: 
                   3390:     # get the data agin
                   3391:     if (!$args->{'one_time'}) {
                   3392: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3393:     }
1.811     albertel 3394: 
1.34      www      3395:     if ($chome ne 'no_host') {
1.302     albertel 3396:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3397:        if (!exists($returnhash{'con_lost'})) {
                   3398:            $returnhash{'home'}= $chome;
                   3399: 	   $returnhash{'domain'} = $cdomain;
                   3400: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3401:            if (!defined($returnhash{'type'})) {
                   3402:                $returnhash{'type'} = 'Course';
                   3403:            }
1.130     albertel 3404:            while (my ($name,$value) = each %returnhash) {
1.53      www      3405:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3406:            }
1.270     www      3407:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3408:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3409: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3410:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3411:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3412:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3413:        }
                   3414:     }
1.731     albertel 3415:     if (!$args->{'one_time'}) {
1.949     raeburn  3416: 	&appenv(\%envhash);
1.731     albertel 3417:     }
1.302     albertel 3418:     return %returnhash;
1.461     www      3419: }
                   3420: 
                   3421: # -------------------------------------------------See if a user is privileged
                   3422: 
                   3423: sub privileged {
                   3424:     my ($username,$domain)=@_;
                   3425:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3426: 			&homeserver($username,$domain));
                   3427:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3428:     my $now=time;
                   3429:     if ($rolesdump ne '') {
1.800     albertel 3430:         foreach my $entry (split(/&/,$rolesdump)) {
                   3431: 	    if ($entry!~/^rolesdef_/) {
                   3432: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3433: 		$area=~s/\_\w\w$//;
                   3434: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3435: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3436: 		    my $active=1;
                   3437: 		    if ($tend) {
                   3438: 			if ($tend<$now) { $active=0; }
                   3439: 		    }
                   3440: 		    if ($tstart) {
                   3441: 			if ($tstart>$now) { $active=0; }
                   3442: 		    }
                   3443: 		    if ($active) { return 1; }
                   3444: 		}
                   3445: 	    }
                   3446: 	}
                   3447:     }
                   3448:     return 0;
1.9       www      3449: }
1.1       albertel 3450: 
1.103     harris41 3451: # -------------------------------------------------------- Get user privileges
1.11      www      3452: 
                   3453: sub rolesinit {
                   3454:     my ($domain,$username,$authhost)=@_;
                   3455:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3456:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3457:     my %allroles=();
1.678     raeburn  3458:     my %allgroups=();   
1.11      www      3459:     my $now=time;
1.743     albertel 3460:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3461:     my $group_privs;
1.11      www      3462: 
                   3463:     if ($rolesdump ne '') {
1.800     albertel 3464:         foreach my $entry (split(/&/,$rolesdump)) {
                   3465: 	  if ($entry!~/^rolesdef_/) {
                   3466:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3467: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3468:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3469: 	    if ($role=~/^cr/) { 
1.807     albertel 3470: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3471: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3472: 		    ($tend,$tstart)=split('_',$trest);
                   3473: 		} else {
                   3474: 		    $trole=$role;
                   3475: 		}
1.678     raeburn  3476:             } elsif ($role =~ m|^gr/|) {
                   3477:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3478:                 ($trole,$group_privs) = split(/\//,$trole);
                   3479:                 $group_privs = &unescape($group_privs);
1.587     albertel 3480: 	    } else {
                   3481: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3482: 	    }
1.743     albertel 3483: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3484: 					 $username);
                   3485: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3486:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3487:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3488:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3489: 		my $spec=$trole.'.'.$area;
                   3490: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3491: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3492:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3493:                 } elsif ($trole eq 'gr') {
                   3494:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3495: 		} else {
1.567     raeburn  3496:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3497: 		}
1.12      www      3498:             }
1.662     raeburn  3499:           }
1.191     harris41 3500:         }
1.743     albertel 3501:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3502:         $userroles{'user.adv'}    = $adv;
                   3503: 	$userroles{'user.author'} = $author;
1.620     albertel 3504:         $env{'user.adv'}=$adv;
1.11      www      3505:     }
1.743     albertel 3506:     return \%userroles;  
1.11      www      3507: }
                   3508: 
1.567     raeburn  3509: sub set_arearole {
                   3510:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3511: # log the associated role with the area
                   3512:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3513:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3514: }
                   3515: 
                   3516: sub custom_roleprivs {
                   3517:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3518:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3519:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3520:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3521:         my ($rdummy,$roledef)=
                   3522:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3523:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3524:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3525:             if (defined($syspriv)) {
                   3526:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3527:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3528:             }
                   3529:             if ($tdomain ne '') {
                   3530:                 if (defined($dompriv)) {
                   3531:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3532:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3533:                 }
                   3534:                 if (($trest ne '') && (defined($coursepriv))) {
                   3535:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3536:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3537:                 }
                   3538:             }
                   3539:         }
                   3540:     }
                   3541: }
                   3542: 
1.678     raeburn  3543: sub group_roleprivs {
                   3544:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3545:     my $access = 1;
                   3546:     my $now = time;
                   3547:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3548:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3549:     if ($access) {
1.811     albertel 3550:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3551:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3552:     }
                   3553: }
1.567     raeburn  3554: 
                   3555: sub standard_roleprivs {
                   3556:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3557:     if (defined($pr{$trole.':s'})) {
                   3558:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3559:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3560:     }
                   3561:     if ($tdomain ne '') {
                   3562:         if (defined($pr{$trole.':d'})) {
                   3563:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3564:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3565:         }
                   3566:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3567:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3568:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3569:         }
                   3570:     }
                   3571: }
                   3572: 
                   3573: sub set_userprivs {
1.678     raeburn  3574:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3575:     my $author=0;
                   3576:     my $adv=0;
1.678     raeburn  3577:     my %grouproles = ();
                   3578:     if (keys(%{$allgroups}) > 0) {
                   3579:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3580:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3581:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3582:                 $trole = $1;
                   3583:                 $area = $2;
1.681     raeburn  3584:                 $sec = $3;
                   3585:                 $extendedarea = $area.$sec;
                   3586:                 if (exists($$allgroups{$area})) {
                   3587:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3588:                         my $spec = $trole.'.'.$extendedarea;
                   3589:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3590:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3591:                     }
                   3592:                 }
                   3593:             }
                   3594:         }
                   3595:     }
1.800     albertel 3596:     foreach my $group (keys(%grouproles)) {
                   3597:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3598:     }
1.800     albertel 3599:     foreach my $role (keys(%{$allroles})) {
                   3600:         my %thesepriv;
1.941     raeburn  3601:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3602:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3603:             if ($item ne '') {
                   3604:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3605:                 if ($restrictions eq '') {
                   3606:                     $thesepriv{$privilege}='F';
                   3607:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3608:                     $thesepriv{$privilege}.=$restrictions;
                   3609:                 }
                   3610:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3611:             }
                   3612:         }
                   3613:         my $thesestr='';
1.800     albertel 3614:         foreach my $priv (keys(%thesepriv)) {
                   3615: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3616: 	}
                   3617:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3618:     }
                   3619:     return ($author,$adv);
                   3620: }
                   3621: 
1.12      www      3622: # --------------------------------------------------------------- get interface
                   3623: 
                   3624: sub get {
1.131     albertel 3625:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3626:    my $items='';
1.800     albertel 3627:    foreach my $item (@$storearr) {
                   3628:        $items.=&escape($item).'&';
1.191     harris41 3629:    }
1.12      www      3630:    $items=~s/\&$//;
1.620     albertel 3631:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3632:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3633:    my $uhome=&homeserver($uname,$udomain);
                   3634: 
1.133     albertel 3635:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3636:    my @pairs=split(/\&/,$rep);
1.273     albertel 3637:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3638:      return @pairs;
                   3639:    }
1.15      www      3640:    my %returnhash=();
1.42      www      3641:    my $i=0;
1.800     albertel 3642:    foreach my $item (@$storearr) {
                   3643:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3644:       $i++;
1.191     harris41 3645:    }
1.15      www      3646:    return %returnhash;
1.27      www      3647: }
                   3648: 
                   3649: # --------------------------------------------------------------- del interface
                   3650: 
                   3651: sub del {
1.133     albertel 3652:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3653:    my $items='';
1.800     albertel 3654:    foreach my $item (@$storearr) {
                   3655:        $items.=&escape($item).'&';
1.191     harris41 3656:    }
1.27      www      3657:    $items=~s/\&$//;
1.620     albertel 3658:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3659:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3660:    my $uhome=&homeserver($uname,$udomain);
                   3661: 
                   3662:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3663: }
                   3664: 
                   3665: # -------------------------------------------------------------- dump interface
                   3666: 
                   3667: sub dump {
1.755     albertel 3668:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3669:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3670:     if (!$uname) { $uname=$env{'user.name'}; }
                   3671:     my $uhome=&homeserver($uname,$udomain);
                   3672:     if ($regexp) {
                   3673: 	$regexp=&escape($regexp);
                   3674:     } else {
                   3675: 	$regexp='.';
                   3676:     }
                   3677:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3678:     my @pairs=split(/\&/,$rep);
                   3679:     my %returnhash=();
                   3680:     foreach my $item (@pairs) {
                   3681: 	my ($key,$value)=split(/=/,$item,2);
                   3682: 	$key = &unescape($key);
                   3683: 	next if ($key =~ /^error: 2 /);
                   3684: 	$returnhash{$key}=&thaw_unescape($value);
                   3685:     }
                   3686:     return %returnhash;
1.407     www      3687: }
                   3688: 
1.717     albertel 3689: # --------------------------------------------------------- dumpstore interface
                   3690: 
                   3691: sub dumpstore {
                   3692:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3693:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3694:    if (!$uname) { $uname=$env{'user.name'}; }
                   3695:    my $uhome=&homeserver($uname,$udomain);
                   3696:    if ($regexp) {
                   3697:        $regexp=&escape($regexp);
                   3698:    } else {
                   3699:        $regexp='.';
                   3700:    }
                   3701:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3702:    my @pairs=split(/\&/,$rep);
                   3703:    my %returnhash=();
                   3704:    foreach my $item (@pairs) {
                   3705:        my ($key,$value)=split(/=/,$item,2);
                   3706:        next if ($key =~ /^error: 2 /);
                   3707:        $returnhash{$key}=&thaw_unescape($value);
                   3708:    }
                   3709:    return %returnhash;
1.717     albertel 3710: }
                   3711: 
1.407     www      3712: # -------------------------------------------------------------- keys interface
                   3713: 
                   3714: sub getkeys {
                   3715:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3716:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3717:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3718:    my $uhome=&homeserver($uname,$udomain);
                   3719:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3720:    my @keyarray=();
1.800     albertel 3721:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3722:       next if ($key =~ /^error: 2 /);
1.800     albertel 3723:       push(@keyarray,&unescape($key));
1.407     www      3724:    }
                   3725:    return @keyarray;
1.318     matthew  3726: }
                   3727: 
1.319     matthew  3728: # --------------------------------------------------------------- currentdump
                   3729: sub currentdump {
1.328     matthew  3730:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3731:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3732:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3733:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3734:    my $uhome = &homeserver($sname,$sdom);
                   3735:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3736:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3737:    #
1.318     matthew  3738:    my %returnhash=();
1.319     matthew  3739:    #
                   3740:    if ($rep eq "unknown_cmd") { 
                   3741:        # an old lond will not know currentdump
                   3742:        # Do a dump and make it look like a currentdump
1.822     albertel 3743:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3744:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3745:        my %hash = @tmp;
                   3746:        @tmp=();
1.424     matthew  3747:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3748:    } else {
                   3749:        my @pairs=split(/\&/,$rep);
1.800     albertel 3750:        foreach my $pair (@pairs) {
                   3751:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3752:            my ($symb,$param) = split(/:/,$key);
                   3753:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3754:                                                         &thaw_unescape($value);
1.319     matthew  3755:        }
1.191     harris41 3756:    }
1.12      www      3757:    return %returnhash;
1.424     matthew  3758: }
                   3759: 
                   3760: sub convert_dump_to_currentdump{
                   3761:     my %hash = %{shift()};
                   3762:     my %returnhash;
                   3763:     # Code ripped from lond, essentially.  The only difference
                   3764:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3765:     # we might run in to problems with parameter names =~ /^v\./
                   3766:     while (my ($key,$value) = each(%hash)) {
                   3767:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3768: 	$symb  = &unescape($symb);
                   3769: 	$param = &unescape($param);
1.424     matthew  3770:         next if ($v eq 'version' || $symb eq 'keys');
                   3771:         next if (exists($returnhash{$symb}) &&
                   3772:                  exists($returnhash{$symb}->{$param}) &&
                   3773:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3774:         $returnhash{$symb}->{$param}=$value;
                   3775:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3776:     }
                   3777:     #
                   3778:     # Remove all of the keys in the hashes which keep track of
                   3779:     # the version of the parameter.
                   3780:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3781:         # use a foreach because we are going to delete from the hash.
                   3782:         foreach my $key (keys(%$param_hash)) {
                   3783:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3784:         }
                   3785:     }
                   3786:     return \%returnhash;
1.12      www      3787: }
                   3788: 
1.627     albertel 3789: # ------------------------------------------------------ critical inc interface
                   3790: 
                   3791: sub cinc {
                   3792:     return &inc(@_,'critical');
                   3793: }
                   3794: 
1.449     matthew  3795: # --------------------------------------------------------------- inc interface
                   3796: 
                   3797: sub inc {
1.627     albertel 3798:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3799:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3800:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3801:     my $uhome=&homeserver($uname,$udomain);
                   3802:     my $items='';
                   3803:     if (! ref($store)) {
                   3804:         # got a single value, so use that instead
                   3805:         $items = &escape($store).'=&';
                   3806:     } elsif (ref($store) eq 'SCALAR') {
                   3807:         $items = &escape($$store).'=&';        
                   3808:     } elsif (ref($store) eq 'ARRAY') {
                   3809:         $items = join('=&',map {&escape($_);} @{$store});
                   3810:     } elsif (ref($store) eq 'HASH') {
                   3811:         while (my($key,$value) = each(%{$store})) {
                   3812:             $items.= &escape($key).'='.&escape($value).'&';
                   3813:         }
                   3814:     }
                   3815:     $items=~s/\&$//;
1.627     albertel 3816:     if ($critical) {
                   3817: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3818:     } else {
                   3819: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3820:     }
1.449     matthew  3821: }
                   3822: 
1.12      www      3823: # --------------------------------------------------------------- put interface
                   3824: 
                   3825: sub put {
1.134     albertel 3826:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3827:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3828:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3829:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3830:    my $items='';
1.800     albertel 3831:    foreach my $item (keys(%$storehash)) {
                   3832:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3833:    }
1.12      www      3834:    $items=~s/\&$//;
1.134     albertel 3835:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3836: }
                   3837: 
1.631     albertel 3838: # ------------------------------------------------------------ newput interface
                   3839: 
                   3840: sub newput {
                   3841:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3842:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3843:    if (!$uname) { $uname=$env{'user.name'}; }
                   3844:    my $uhome=&homeserver($uname,$udomain);
                   3845:    my $items='';
                   3846:    foreach my $key (keys(%$storehash)) {
                   3847:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3848:    }
                   3849:    $items=~s/\&$//;
                   3850:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3851: }
                   3852: 
                   3853: # ---------------------------------------------------------  putstore interface
                   3854: 
1.524     raeburn  3855: sub putstore {
1.715     albertel 3856:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3857:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3858:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3859:    my $uhome=&homeserver($uname,$udomain);
                   3860:    my $items='';
1.715     albertel 3861:    foreach my $key (keys(%$storehash)) {
                   3862:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3863:    }
1.715     albertel 3864:    $items=~s/\&$//;
1.716     albertel 3865:    my $esc_symb=&escape($symb);
                   3866:    my $esc_v=&escape($version);
1.715     albertel 3867:    my $reply =
1.716     albertel 3868:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3869: 	      $uhome);
                   3870:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3871:        # gfall back to way things use to be done
1.715     albertel 3872:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3873: 			    $uname);
1.524     raeburn  3874:    }
1.715     albertel 3875:    return $reply;
                   3876: }
                   3877: 
                   3878: sub old_putstore {
1.716     albertel 3879:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3880:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3881:     if (!$uname) { $uname=$env{'user.name'}; }
                   3882:     my $uhome=&homeserver($uname,$udomain);
                   3883:     my %newstorehash;
1.800     albertel 3884:     foreach my $item (keys(%$storehash)) {
                   3885: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3886: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3887:     }
                   3888:     my $items='';
                   3889:     my %allitems = ();
1.800     albertel 3890:     foreach my $item (keys(%newstorehash)) {
                   3891: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3892: 	    my $key = $1.':keys:'.$2;
                   3893: 	    $allitems{$key} .= $3.':';
                   3894: 	}
1.800     albertel 3895: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3896:     }
1.800     albertel 3897:     foreach my $item (keys(%allitems)) {
                   3898: 	$allitems{$item} =~ s/\:$//;
                   3899: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3900:     }
                   3901:     $items=~s/\&$//;
                   3902:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3903: }
                   3904: 
1.47      www      3905: # ------------------------------------------------------ critical put interface
                   3906: 
                   3907: sub cput {
1.134     albertel 3908:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3909:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3910:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3911:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3912:    my $items='';
1.800     albertel 3913:    foreach my $item (keys(%$storehash)) {
                   3914:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3915:    }
1.47      www      3916:    $items=~s/\&$//;
1.134     albertel 3917:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3918: }
                   3919: 
                   3920: # -------------------------------------------------------------- eget interface
                   3921: 
                   3922: sub eget {
1.133     albertel 3923:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3924:    my $items='';
1.800     albertel 3925:    foreach my $item (@$storearr) {
                   3926:        $items.=&escape($item).'&';
1.191     harris41 3927:    }
1.12      www      3928:    $items=~s/\&$//;
1.620     albertel 3929:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3930:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3931:    my $uhome=&homeserver($uname,$udomain);
                   3932:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3933:    my @pairs=split(/\&/,$rep);
                   3934:    my %returnhash=();
1.42      www      3935:    my $i=0;
1.800     albertel 3936:    foreach my $item (@$storearr) {
                   3937:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3938:       $i++;
1.191     harris41 3939:    }
1.12      www      3940:    return %returnhash;
                   3941: }
                   3942: 
1.667     albertel 3943: # ------------------------------------------------------------ tmpput interface
                   3944: sub tmpput {
1.802     raeburn  3945:     my ($storehash,$server,$context)=@_;
1.667     albertel 3946:     my $items='';
1.800     albertel 3947:     foreach my $item (keys(%$storehash)) {
                   3948: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3949:     }
                   3950:     $items=~s/\&$//;
1.802     raeburn  3951:     if (defined($context)) {
                   3952:         $items .= ':'.&escape($context);
                   3953:     }
1.667     albertel 3954:     return &reply("tmpput:$items",$server);
                   3955: }
                   3956: 
                   3957: # ------------------------------------------------------------ tmpget interface
                   3958: sub tmpget {
1.688     albertel 3959:     my ($token,$server)=@_;
                   3960:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3961:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3962:     my %returnhash;
                   3963:     foreach my $item (split(/\&/,$rep)) {
                   3964: 	my ($key,$value)=split(/=/,$item);
                   3965: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3966:     }
                   3967:     return %returnhash;
                   3968: }
                   3969: 
1.688     albertel 3970: # ------------------------------------------------------------ tmpget interface
                   3971: sub tmpdel {
                   3972:     my ($token,$server)=@_;
                   3973:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3974:     return &reply("tmpdel:$token",$server);
                   3975: }
                   3976: 
1.765     albertel 3977: # -------------------------------------------------- portfolio access checking
                   3978: 
                   3979: sub portfolio_access {
1.766     albertel 3980:     my ($requrl) = @_;
1.765     albertel 3981:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3982:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3983:     if ($result) {
                   3984:         my %setters;
                   3985:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3986:             my ($startblock,$endblock) =
                   3987:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3988:             if ($startblock && $endblock) {
                   3989:                 return 'B';
                   3990:             }
                   3991:         } else {
                   3992:             my ($startblock,$endblock) =
                   3993:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3994:             if ($startblock && $endblock) {
                   3995:                 return 'B';
                   3996:             }
                   3997:         }
                   3998:     }
1.765     albertel 3999:     if ($result eq 'ok') {
1.766     albertel 4000:        return 'F';
1.765     albertel 4001:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4002:        return 'A';
1.765     albertel 4003:     }
1.766     albertel 4004:     return '';
1.765     albertel 4005: }
                   4006: 
                   4007: sub get_portfolio_access {
1.767     albertel 4008:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4009: 
                   4010:     if (!ref($access_hash)) {
                   4011: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4012: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4013: 						   $file_name);
                   4014: 	$access_hash = $access_controls{$file_name};
                   4015:     }
                   4016: 
1.765     albertel 4017:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4018:     my $now = time;
                   4019:     if (ref($access_hash) eq 'HASH') {
                   4020:         foreach my $key (keys(%{$access_hash})) {
                   4021:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4022:             if ($start > $now) {
                   4023:                 next;
                   4024:             }
                   4025:             if ($end && $end<$now) {
                   4026:                 next;
                   4027:             }
                   4028:             if ($scope eq 'public') {
                   4029:                 $public = $key;
                   4030:                 last;
                   4031:             } elsif ($scope eq 'guest') {
                   4032:                 $guest = $key;
                   4033:             } elsif ($scope eq 'domains') {
                   4034:                 push(@domains,$key);
                   4035:             } elsif ($scope eq 'users') {
                   4036:                 push(@users,$key);
                   4037:             } elsif ($scope eq 'course') {
                   4038:                 push(@courses,$key);
                   4039:             } elsif ($scope eq 'group') {
                   4040:                 push(@groups,$key);
                   4041:             }
                   4042:         }
                   4043:         if ($public) {
                   4044:             return 'ok';
                   4045:         }
                   4046:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4047:             if ($guest) {
                   4048:                 return $guest;
                   4049:             }
                   4050:         } else {
                   4051:             if (@domains > 0) {
                   4052:                 foreach my $domkey (@domains) {
                   4053:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4054:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4055:                             return 'ok';
                   4056:                         }
                   4057:                     }
                   4058:                 }
                   4059:             }
                   4060:             if (@users > 0) {
                   4061:                 foreach my $userkey (@users) {
1.865     raeburn  4062:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4063:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4064:                             if (ref($item) eq 'HASH') {
                   4065:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4066:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4067:                                     return 'ok';
                   4068:                                 }
                   4069:                             }
                   4070:                         }
                   4071:                     } 
1.765     albertel 4072:                 }
                   4073:             }
                   4074:             my %roleshash;
                   4075:             my @courses_and_groups = @courses;
                   4076:             push(@courses_and_groups,@groups); 
                   4077:             if (@courses_and_groups > 0) {
                   4078:                 my (%allgroups,%allroles); 
                   4079:                 my ($start,$end,$role,$sec,$group);
                   4080:                 foreach my $envkey (%env) {
1.811     albertel 4081:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4082:                         my $cid = $2.'_'.$3; 
                   4083:                         if ($1 eq 'gr') {
                   4084:                             $group = $4;
                   4085:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4086:                         } else {
                   4087:                             if ($4 eq '') {
                   4088:                                 $sec = 'none';
                   4089:                             } else {
                   4090:                                 $sec = $4;
                   4091:                             }
                   4092:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4093:                         }
1.811     albertel 4094:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4095:                         my $cid = $2.'_'.$3;
                   4096:                         if ($4 eq '') {
                   4097:                             $sec = 'none';
                   4098:                         } else {
                   4099:                             $sec = $4;
                   4100:                         }
                   4101:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4102:                     }
                   4103:                 }
                   4104:                 if (keys(%allroles) == 0) {
                   4105:                     return;
                   4106:                 }
                   4107:                 foreach my $key (@courses_and_groups) {
                   4108:                     my %content = %{$$access_hash{$key}};
                   4109:                     my $cnum = $content{'number'};
                   4110:                     my $cdom = $content{'domain'};
                   4111:                     my $cid = $cdom.'_'.$cnum;
                   4112:                     if (!exists($allroles{$cid})) {
                   4113:                         next;
                   4114:                     }    
                   4115:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4116:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4117:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4118:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4119:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4120:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4121:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4122:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4123:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4124:                                         if (grep/^all$/,@sections) {
                   4125:                                             return 'ok';
                   4126:                                         } else {
                   4127:                                             if (grep/^$sec$/,@sections) {
                   4128:                                                 return 'ok';
                   4129:                                             }
                   4130:                                         }
                   4131:                                     }
                   4132:                                 }
                   4133:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4134:                                     if (grep/^none$/,@groups) {
                   4135:                                         return 'ok';
                   4136:                                     }
                   4137:                                 } else {
                   4138:                                     if (grep/^all$/,@groups) {
                   4139:                                         return 'ok';
                   4140:                                     } 
                   4141:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4142:                                         if (grep/^$group$/,@groups) {
                   4143:                                             return 'ok';
                   4144:                                         }
                   4145:                                     }
                   4146:                                 } 
                   4147:                             }
                   4148:                         }
                   4149:                     }
                   4150:                 }
                   4151:             }
                   4152:             if ($guest) {
                   4153:                 return $guest;
                   4154:             }
                   4155:         }
                   4156:     }
                   4157:     return;
                   4158: }
                   4159: 
                   4160: sub course_group_datechecker {
                   4161:     my ($dates,$now,$status) = @_;
                   4162:     my ($start,$end) = split(/\./,$dates);
                   4163:     if (!$start && !$end) {
                   4164:         return 'ok';
                   4165:     }
                   4166:     if (grep/^active$/,@{$status}) {
                   4167:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4168:             return 'ok';
                   4169:         }
                   4170:     }
                   4171:     if (grep/^previous$/,@{$status}) {
                   4172:         if ($end > $now ) {
                   4173:             return 'ok';
                   4174:         }
                   4175:     }
                   4176:     if (grep/^future$/,@{$status}) {
                   4177:         if ($start > $now) {
                   4178:             return 'ok';
                   4179:         }
                   4180:     }
                   4181:     return; 
                   4182: }
                   4183: 
                   4184: sub parse_portfolio_url {
                   4185:     my ($url) = @_;
                   4186: 
                   4187:     my ($type,$udom,$unum,$group,$file_name);
                   4188:     
1.823     albertel 4189:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4190: 	$type = 1;
                   4191:         $udom = $1;
                   4192:         $unum = $2;
                   4193:         $file_name = $3;
1.823     albertel 4194:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4195: 	$type = 2;
                   4196:         $udom = $1;
                   4197:         $unum = $2;
                   4198:         $group = $3;
                   4199:         $file_name = $3.'/'.$4;
                   4200:     }
                   4201:     if (wantarray) {
                   4202: 	return ($type,$udom,$unum,$file_name,$group);
                   4203:     }
                   4204:     return $type;
                   4205: }
                   4206: 
                   4207: sub is_portfolio_url {
                   4208:     my ($url) = @_;
                   4209:     return scalar(&parse_portfolio_url($url));
                   4210: }
                   4211: 
1.798     raeburn  4212: sub is_portfolio_file {
                   4213:     my ($file) = @_;
1.820     raeburn  4214:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4215:         return 1;
                   4216:     }
                   4217:     return;
                   4218: }
                   4219: 
                   4220: 
1.341     www      4221: # ---------------------------------------------- Custom access rule evaluation
                   4222: 
                   4223: sub customaccess {
                   4224:     my ($priv,$uri)=@_;
1.807     albertel 4225:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4226:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4227:     $udom = &LONCAPA::clean_domain($udom);
                   4228:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4229:     my $access=0;
1.800     albertel 4230:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4231: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4232: 	if ($type eq 'user') {
                   4233: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4234: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4235: 		if ($tdom) {
                   4236: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4237: 		}
1.896     albertel 4238: 		if ($tuname) {
                   4239: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4240: 		}
                   4241: 		$access=($effect eq 'allow');
                   4242: 		last;
                   4243: 	    }
                   4244: 	} else {
                   4245: 	    if ($role) {
                   4246: 		if ($role ne $urole) { next; }
                   4247: 	    }
                   4248: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4249: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4250: 		if ($tdom) {
                   4251: 		    if ($tdom ne $udom) { next; }
                   4252: 		}
                   4253: 		if ($tcrs) {
                   4254: 		    if ($tcrs ne $ucrs) { next; }
                   4255: 		}
                   4256: 		if ($tsec) {
                   4257: 		    if ($tsec ne $usec) { next; }
                   4258: 		}
                   4259: 		$access=($effect eq 'allow');
                   4260: 		last;
                   4261: 	    }
                   4262: 	    if ($realm eq '' && $role eq '') {
                   4263: 		$access=($effect eq 'allow');
                   4264: 	    }
1.402     bowersj2 4265: 	}
1.341     www      4266:     }
                   4267:     return $access;
                   4268: }
                   4269: 
1.103     harris41 4270: # ------------------------------------------------- Check for a user privilege
1.12      www      4271: 
                   4272: sub allowed {
1.810     raeburn  4273:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4274:     my $ver_orguri=$uri;
1.439     www      4275:     $uri=&deversion($uri);
1.152     www      4276:     my $orguri=$uri;
1.52      www      4277:     $uri=&declutter($uri);
1.809     raeburn  4278: 
1.810     raeburn  4279:     if ($priv eq 'evb') {
                   4280: # Evade communication block restrictions for specified role in a course
                   4281:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4282:             return $1;
                   4283:         } else {
                   4284:             return;
                   4285:         }
                   4286:     }
                   4287: 
1.620     albertel 4288:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4289: # Free bre access to adm and meta resources
1.775     albertel 4290:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4291: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4292: 	&& ($priv eq 'bre')) {
1.14      www      4293: 	return 'F';
1.159     www      4294:     }
                   4295: 
1.545     banghart 4296: # Free bre access to user's own portfolio contents
1.714     raeburn  4297:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4298:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4299: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4300:         my %setters;
                   4301:         my ($startblock,$endblock) = 
                   4302:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4303:         if ($startblock && $endblock) {
                   4304:             return 'B';
                   4305:         } else {
                   4306:             return 'F';
                   4307:         }
1.545     banghart 4308:     }
                   4309: 
1.762     raeburn  4310: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4311:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4312:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4313:         if (exists($env{'request.course.id'})) {
                   4314:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4315:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4316:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4317:                 my $courseprivid=$env{'request.course.id'};
                   4318:                 $courseprivid=~s/\_/\//;
                   4319:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4320:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4321:                     return $1; 
1.762     raeburn  4322:                 } else {
                   4323:                     if ($env{'request.course.sec'}) {
                   4324:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4325:                     }
                   4326:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4327:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4328:                         return $2;
                   4329:                     }
1.714     raeburn  4330:                 }
                   4331:             }
                   4332:         }
                   4333:     }
                   4334: 
1.159     www      4335: # Free bre to public access
                   4336: 
                   4337:     if ($priv eq 'bre') {
1.238     www      4338:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4339: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4340:            return 'F'; 
                   4341:         }
1.238     www      4342:         if ($copyright eq 'priv') {
                   4343:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4344: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4345: 		return '';
                   4346:             }
                   4347:         }
                   4348:         if ($copyright eq 'domain') {
                   4349:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4350: 	    unless (($env{'user.domain'} eq $1) ||
                   4351:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4352: 		return '';
                   4353:             }
1.262     matthew  4354:         }
1.620     albertel 4355:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4356:             # Library role, so allow browsing of resources in this domain.
                   4357:             return 'F';
1.238     www      4358:         }
1.341     www      4359:         if ($copyright eq 'custom') {
                   4360: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4361:         }
1.14      www      4362:     }
1.264     matthew  4363:     # Domain coordinator is trying to create a course
1.620     albertel 4364:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4365:         # uri is the requested domain in this case.
                   4366:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4367:         # a role of dc for the domain in question.
1.620     albertel 4368:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4369:     }
1.29      www      4370: 
1.52      www      4371:     my $thisallowed='';
                   4372:     my $statecond=0;
                   4373:     my $courseprivid='';
                   4374: 
                   4375: # Course
                   4376: 
1.620     albertel 4377:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4378:        $thisallowed.=$1;
                   4379:     }
1.29      www      4380: 
1.52      www      4381: # Domain
                   4382: 
1.620     albertel 4383:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4384:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4385:        $thisallowed.=$1;
                   4386:     }
1.52      www      4387: 
                   4388: # Course: uri itself is a course
1.66      www      4389:     my $courseuri=$uri;
                   4390:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4391:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4392: 
1.620     albertel 4393:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4394:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4395:        $thisallowed.=$1;
                   4396:     }
1.29      www      4397: 
1.665     albertel 4398: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4399: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4400:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4401: 	$thisallowed='';
1.671     raeburn  4402:         my ($match)=&is_on_map($uri);
                   4403:         if ($match) {
                   4404:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4405:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4406:                 $thisallowed.=$1;
                   4407:             }
                   4408:         } else {
1.705     albertel 4409:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4410:             if ($refuri) {
                   4411:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4412:                     $thisallowed='F';
1.671     raeburn  4413:                 } else {
                   4414:                     $refuri=&declutter($refuri);
                   4415:                     my ($match) = &is_on_map($refuri);
                   4416:                     if ($match) {
                   4417:                         $thisallowed='F';
                   4418:                     }
1.669     raeburn  4419:                 }
1.671     raeburn  4420:             }
                   4421:         }
1.314     www      4422:     }
1.492     albertel 4423: 
1.766     albertel 4424:     if ($priv eq 'bre'
                   4425: 	&& $thisallowed ne 'F' 
                   4426: 	&& $thisallowed ne '2'
                   4427: 	&& &is_portfolio_url($uri)) {
                   4428: 	$thisallowed = &portfolio_access($uri);
                   4429:     }
                   4430:     
1.52      www      4431: # Full access at system, domain or course-wide level? Exit.
1.29      www      4432: 
                   4433:     if ($thisallowed=~/F/) {
                   4434: 	return 'F';
                   4435:     }
                   4436: 
1.52      www      4437: # If this is generating or modifying users, exit with special codes
1.29      www      4438: 
1.643     www      4439:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4440: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4441: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4442: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4443: 	    unless ($auname) { return $thisallowed; }
                   4444: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4445: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4446: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4447: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4448: 	}
1.52      www      4449: 	return $thisallowed;
                   4450:     }
                   4451: #
1.103     harris41 4452: # Gathered so far: system, domain and course wide privileges
1.52      www      4453: #
                   4454: # Course: See if uri or referer is an individual resource that is part of 
                   4455: # the course
                   4456: 
1.620     albertel 4457:     if ($env{'request.course.id'}) {
1.232     www      4458: 
1.620     albertel 4459:        $courseprivid=$env{'request.course.id'};
                   4460:        if ($env{'request.course.sec'}) {
                   4461:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4462:        }
                   4463:        $courseprivid=~s/\_/\//;
                   4464:        my $checkreferer=1;
1.232     www      4465:        my ($match,$cond)=&is_on_map($uri);
                   4466:        if ($match) {
                   4467:            $statecond=$cond;
1.620     albertel 4468:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4469:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4470:                $thisallowed.=$1;
                   4471:                $checkreferer=0;
                   4472:            }
1.29      www      4473:        }
1.83      www      4474:        
1.148     www      4475:        if ($checkreferer) {
1.620     albertel 4476: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4477:             unless ($refuri) {
1.800     albertel 4478:                 foreach my $key (keys(%env)) {
                   4479: 		    if ($key=~/^httpref\..*\*/) {
                   4480: 			my $pattern=$key;
1.156     www      4481:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4482:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4483:                         $pattern=~s/\//\\\//g;
1.152     www      4484:                         if ($orguri=~/$pattern/) {
1.800     albertel 4485: 			    $refuri=$env{$key};
1.148     www      4486:                         }
                   4487:                     }
1.191     harris41 4488:                 }
1.148     www      4489:             }
1.232     www      4490: 
1.148     www      4491:          if ($refuri) { 
1.152     www      4492: 	  $refuri=&declutter($refuri);
1.232     www      4493:           my ($match,$cond)=&is_on_map($refuri);
                   4494:             if ($match) {
                   4495:               my $refstatecond=$cond;
1.620     albertel 4496:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4497:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4498:                   $thisallowed.=$1;
1.53      www      4499:                   $uri=$refuri;
                   4500:                   $statecond=$refstatecond;
1.52      www      4501:               }
                   4502:           }
1.148     www      4503:         }
1.29      www      4504:        }
1.52      www      4505:    }
1.29      www      4506: 
1.52      www      4507: #
1.103     harris41 4508: # Gathered now: all privileges that could apply, and condition number
1.52      www      4509: # 
                   4510: #
                   4511: # Full or no access?
                   4512: #
1.29      www      4513: 
1.52      www      4514:     if ($thisallowed=~/F/) {
                   4515: 	return 'F';
                   4516:     }
1.29      www      4517: 
1.52      www      4518:     unless ($thisallowed) {
                   4519:         return '';
                   4520:     }
1.29      www      4521: 
1.52      www      4522: # Restrictions exist, deal with them
                   4523: #
                   4524: #   C:according to course preferences
                   4525: #   R:according to resource settings
                   4526: #   L:unless locked
                   4527: #   X:according to user session state
                   4528: #
                   4529: 
                   4530: # Possibly locked functionality, check all courses
1.54      www      4531: # Locks might take effect only after 10 minutes cache expiration for other
                   4532: # courses, and 2 minutes for current course
1.52      www      4533: 
                   4534:     my $envkey;
                   4535:     if ($thisallowed=~/L/) {
1.620     albertel 4536:         foreach $envkey (keys %env) {
1.54      www      4537:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4538:                my $courseid=$2;
                   4539:                my $roleid=$1.'.'.$2;
1.92      www      4540:                $courseid=~s/^\///;
1.54      www      4541:                my $expiretime=600;
1.620     albertel 4542:                if ($env{'request.role'} eq $roleid) {
1.54      www      4543: 		  $expiretime=120;
                   4544:                }
                   4545: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4546:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4547:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4548: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4549:                }
1.620     albertel 4550:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4551:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4552: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4553:                        &log($env{'user.domain'},$env{'user.name'},
                   4554:                             $env{'user.home'},
1.57      www      4555:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4556:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4557:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4558: 		       return '';
                   4559:                    }
                   4560:                }
1.620     albertel 4561:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4562:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4563: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4564:                        &log($env{'user.domain'},$env{'user.name'},
                   4565:                             $env{'user.home'},
1.57      www      4566:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4567:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4568:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4569: 		       return '';
                   4570:                    }
                   4571:                }
                   4572: 	   }
1.29      www      4573:        }
1.52      www      4574:     }
                   4575:    
                   4576: #
                   4577: # Rest of the restrictions depend on selected course
                   4578: #
                   4579: 
1.620     albertel 4580:     unless ($env{'request.course.id'}) {
1.766     albertel 4581: 	if ($thisallowed eq 'A') {
                   4582: 	    return 'A';
1.814     raeburn  4583:         } elsif ($thisallowed eq 'B') {
                   4584:             return 'B';
1.766     albertel 4585: 	} else {
                   4586: 	    return '1';
                   4587: 	}
1.52      www      4588:     }
1.29      www      4589: 
1.52      www      4590: #
                   4591: # Now user is definitely in a course
                   4592: #
1.53      www      4593: 
                   4594: 
                   4595: # Course preferences
                   4596: 
                   4597:    if ($thisallowed=~/C/) {
1.620     albertel 4598:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4599:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4600:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4601: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4602: 	   if ($priv ne 'pch') { 
                   4603: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4604: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4605: 			$env{'request.course.id'});
                   4606: 	   }
1.237     www      4607:            return '';
                   4608:        }
                   4609: 
1.620     albertel 4610:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4611: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4612: 	   if ($priv ne 'pch') { 
                   4613: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4614: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4615: 			$env{'request.course.id'});
                   4616: 	   }
1.54      www      4617:            return '';
                   4618:        }
1.53      www      4619:    }
                   4620: 
                   4621: # Resource preferences
                   4622: 
                   4623:    if ($thisallowed=~/R/) {
1.620     albertel 4624:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4625:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4626: 	   if ($priv ne 'pch') { 
                   4627: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4628: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4629: 	   }
                   4630: 	   return '';
1.54      www      4631:        }
1.53      www      4632:    }
1.30      www      4633: 
1.246     www      4634: # Restricted by state or randomout?
1.30      www      4635: 
1.52      www      4636:    if ($thisallowed=~/X/) {
1.620     albertel 4637:       if ($env{'acc.randomout'}) {
1.579     albertel 4638: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4639:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4640:             return ''; 
                   4641:          }
1.247     www      4642:       }
                   4643:       if (&condval($statecond)) {
1.52      www      4644: 	 return '2';
                   4645:       } else {
                   4646:          return '';
                   4647:       }
                   4648:    }
1.30      www      4649: 
1.766     albertel 4650:     if ($thisallowed eq 'A') {
                   4651: 	return 'A';
1.814     raeburn  4652:     } elsif ($thisallowed eq 'B') {
                   4653:         return 'B';
1.766     albertel 4654:     }
1.52      www      4655:    return 'F';
1.232     www      4656: }
                   4657: 
1.710     albertel 4658: sub split_uri_for_cond {
                   4659:     my $uri=&deversion(&declutter(shift));
                   4660:     my @uriparts=split(/\//,$uri);
                   4661:     my $filename=pop(@uriparts);
                   4662:     my $pathname=join('/',@uriparts);
                   4663:     return ($pathname,$filename);
                   4664: }
1.232     www      4665: # --------------------------------------------------- Is a resource on the map?
                   4666: 
                   4667: sub is_on_map {
1.710     albertel 4668:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4669:     #Trying to find the conditional for the file
1.620     albertel 4670:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4671: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4672:     if ($match) {
1.289     bowersj2 4673: 	return (1,$1);
                   4674:     } else {
1.434     www      4675: 	return (0,0);
1.289     bowersj2 4676:     }
1.12      www      4677: }
                   4678: 
1.427     www      4679: # --------------------------------------------------------- Get symb from alias
                   4680: 
                   4681: sub get_symb_from_alias {
                   4682:     my $symb=shift;
                   4683:     my ($map,$resid,$url)=&decode_symb($symb);
                   4684: # Already is a symb
                   4685:     if ($url) { return $symb; }
                   4686: # Must be an alias
                   4687:     my $aliassymb='';
                   4688:     my %bighash;
1.620     albertel 4689:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4690:                             &GDBM_READER(),0640)) {
                   4691:         my $rid=$bighash{'mapalias_'.$symb};
                   4692: 	if ($rid) {
                   4693: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4694: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4695: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4696: 	}
                   4697:         untie %bighash;
                   4698:     }
                   4699:     return $aliassymb;
                   4700: }
                   4701: 
1.12      www      4702: # ----------------------------------------------------------------- Define Role
                   4703: 
                   4704: sub definerole {
                   4705:   if (allowed('mcr','/')) {
                   4706:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4707:     foreach my $role (split(':',$sysrole)) {
                   4708: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4709:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4710:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4711: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4712:                return "refused:s:$crole&$cqual"; 
                   4713:             }
                   4714:         }
1.191     harris41 4715:     }
1.800     albertel 4716:     foreach my $role (split(':',$domrole)) {
                   4717: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4718:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4719:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4720: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4721:                return "refused:d:$crole&$cqual"; 
                   4722:             }
                   4723:         }
1.191     harris41 4724:     }
1.800     albertel 4725:     foreach my $role (split(':',$courole)) {
                   4726: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4727:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4728:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4729: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4730:                return "refused:c:$crole&$cqual"; 
                   4731:             }
                   4732:         }
1.191     harris41 4733:     }
1.620     albertel 4734:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4735:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4736: 	        "rolesdef_$rolename=".
                   4737:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4738:     return reply($command,$env{'user.home'});
1.12      www      4739:   } else {
                   4740:     return 'refused';
                   4741:   }
1.105     harris41 4742: }
                   4743: 
                   4744: # ---------------- Make a metadata query against the network of library servers
                   4745: 
                   4746: sub metadata_query {
1.244     matthew  4747:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4748:     my %rhash;
1.845     albertel 4749:     my %libserv = &all_library();
1.244     matthew  4750:     my @server_list = (defined($server_array) ? @$server_array
                   4751:                                               : keys(%libserv) );
                   4752:     for my $server (@server_list) {
1.118     harris41 4753: 	unless ($custom or $customshow) {
                   4754: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4755: 	    $rhash{$server}=$reply;
                   4756: 	}
                   4757: 	else {
                   4758: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4759: 			     &escape($custom).':'.&escape($customshow),
                   4760: 			     $server);
                   4761: 	    $rhash{$server}=$reply;
                   4762: 	}
1.112     harris41 4763:     }
1.118     harris41 4764:     return \%rhash;
1.240     www      4765: }
                   4766: 
                   4767: # ----------------------------------------- Send log queries and wait for reply
                   4768: 
                   4769: sub log_query {
                   4770:     my ($uname,$udom,$query,%filters)=@_;
                   4771:     my $uhome=&homeserver($uname,$udom);
                   4772:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4773:     my $uhost=&hostname($uhome);
1.800     albertel 4774:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4775:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4776:                        $uhome);
1.479     albertel 4777:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4778:     return get_query_reply($queryid);
                   4779: }
                   4780: 
1.818     raeburn  4781: # -------------------------- Update MySQL table for portfolio file
                   4782: 
                   4783: sub update_portfolio_table {
1.821     raeburn  4784:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4785:     my $homeserver = &homeserver($uname,$udom);
                   4786:     my $queryid=
1.821     raeburn  4787:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4788:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4789:     my $reply = &get_query_reply($queryid);
                   4790:     return $reply;
                   4791: }
                   4792: 
1.899     raeburn  4793: # -------------------------- Update MySQL allusers table
                   4794: 
                   4795: sub update_allusers_table {
                   4796:     my ($uname,$udom,$names) = @_;
                   4797:     my $homeserver = &homeserver($uname,$udom);
                   4798:     my $queryid=
                   4799:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4800:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4801:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4802:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4803:                'generation='.&escape($names->{'generation'}).'%%'.
                   4804:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4805:                'id='.&escape($names->{'id'}),$homeserver);
                   4806:     my $reply = &get_query_reply($queryid);
                   4807:     return $reply;
                   4808: }
                   4809: 
1.508     raeburn  4810: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4811: 
                   4812: sub fetch_enrollment_query {
1.511     raeburn  4813:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4814:     my $homeserver;
1.547     raeburn  4815:     my $maxtries = 1;
1.508     raeburn  4816:     if ($context eq 'automated') {
                   4817:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4818:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4819:     } else {
                   4820:         $homeserver = &homeserver($cnum,$dom);
                   4821:     }
1.838     albertel 4822:     my $host=&hostname($homeserver);
1.506     raeburn  4823:     my $cmd = '';
1.800     albertel 4824:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4825:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4826:     }
                   4827:     $cmd =~ s/%%$//;
                   4828:     $cmd = &escape($cmd);
                   4829:     my $query = 'fetchenrollment';
1.620     albertel 4830:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4831:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4832:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4833:         return 'error: '.$queryid;
                   4834:     }
1.506     raeburn  4835:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4836:     my $tries = 1;
                   4837:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4838:         $reply = &get_query_reply($queryid);
                   4839:         $tries ++;
                   4840:     }
1.526     raeburn  4841:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4842:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4843:     } else {
1.901     albertel 4844:         my @responses = split(/:/,$reply);
1.515     raeburn  4845:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4846:             foreach my $line (@responses) {
                   4847:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4848:                 $$replyref{$key} = $value;
                   4849:             }
                   4850:         } else {
1.506     raeburn  4851:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4852:             foreach my $line (@responses) {
                   4853:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4854:                 $$replyref{$key} = $value;
                   4855:                 if ($value > 0) {
1.800     albertel 4856:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4857:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4858:                         my $destname = $pathname.'/'.$filename;
                   4859:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4860:                         if ($xml_classlist =~ /^error/) {
                   4861:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4862:                         } else {
1.506     raeburn  4863:                             if ( open(FILE,">$destname") ) {
                   4864:                                 print FILE &unescape($xml_classlist);
                   4865:                                 close(FILE);
1.526     raeburn  4866:                             } else {
                   4867:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4868:                             }
                   4869:                         }
                   4870:                     }
                   4871:                 }
                   4872:             }
                   4873:         }
                   4874:         return 'ok';
                   4875:     }
                   4876:     return 'error';
                   4877: }
                   4878: 
1.242     www      4879: sub get_query_reply {
                   4880:     my $queryid=shift;
1.240     www      4881:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4882:     my $reply='';
                   4883:     for (1..100) {
                   4884: 	sleep 2;
                   4885:         if (-e $replyfile.'.end') {
1.448     albertel 4886: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4887: 		$reply = join('',<$fh>);
                   4888: 		close($fh);
1.240     www      4889: 	   } else { return 'error: reply_file_error'; }
1.242     www      4890:            return &unescape($reply);
                   4891: 	}
1.240     www      4892:     }
1.242     www      4893:     return 'timeout:'.$queryid;
1.240     www      4894: }
                   4895: 
                   4896: sub courselog_query {
1.241     www      4897: #
                   4898: # possible filters:
                   4899: # url: url or symb
                   4900: # username
                   4901: # domain
                   4902: # action: view, submit, grade
                   4903: # start: timestamp
                   4904: # end: timestamp
                   4905: #
1.240     www      4906:     my (%filters)=@_;
1.620     albertel 4907:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4908:     if ($filters{'url'}) {
                   4909: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4910:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4911:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4912:     }
1.620     albertel 4913:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4914:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4915:     return &log_query($cname,$cdom,'courselog',%filters);
                   4916: }
                   4917: 
                   4918: sub userlog_query {
1.858     raeburn  4919: #
                   4920: # possible filters:
                   4921: # action: log check role
                   4922: # start: timestamp
                   4923: # end: timestamp
                   4924: #
1.240     www      4925:     my ($uname,$udom,%filters)=@_;
                   4926:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4927: }
                   4928: 
1.506     raeburn  4929: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4930: 
                   4931: sub auto_run {
1.508     raeburn  4932:     my ($cnum,$cdom) = @_;
1.876     raeburn  4933:     my $response = 0;
                   4934:     my $settings;
                   4935:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4936:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4937:         $settings = $domconfig{'autoenroll'};
                   4938:         if ($settings->{'run'} eq '1') {
                   4939:             $response = 1;
                   4940:         }
                   4941:     } else {
1.934     raeburn  4942:         my $homeserver;
                   4943:         if (&is_course($cdom,$cnum)) {
                   4944:             $homeserver = &homeserver($cnum,$cdom);
                   4945:         } else {
                   4946:             $homeserver = &domain($cdom,'primary');
                   4947:         }
                   4948:         if ($homeserver ne 'no_host') {
                   4949:             $response = &reply('autorun:'.$cdom,$homeserver);
                   4950:         }
1.876     raeburn  4951:     }
1.506     raeburn  4952:     return $response;
                   4953: }
1.776     albertel 4954: 
1.506     raeburn  4955: sub auto_get_sections {
1.508     raeburn  4956:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4957:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4958:     my @secs = ();
1.511     raeburn  4959:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4960:     unless ($response eq 'refused') {
1.901     albertel 4961:         @secs = split(/:/,$response);
1.506     raeburn  4962:     }
                   4963:     return @secs;
                   4964: }
1.776     albertel 4965: 
1.506     raeburn  4966: sub auto_new_course {
1.508     raeburn  4967:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4968:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4969:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4970:     return $response;
                   4971: }
1.776     albertel 4972: 
1.506     raeburn  4973: sub auto_validate_courseID {
1.508     raeburn  4974:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4975:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4976:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4977:     return $response;
                   4978: }
1.776     albertel 4979: 
1.506     raeburn  4980: sub auto_create_password {
1.873     raeburn  4981:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4982:     my ($homeserver,$response);
1.506     raeburn  4983:     my $create_passwd = 0;
                   4984:     my $authchk = '';
1.873     raeburn  4985:     if ($udom =~ /^$match_domain$/) {
                   4986:         $homeserver = &domain($udom,'primary');
                   4987:     }
                   4988:     if ($homeserver eq '') {
                   4989:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4990:             $homeserver = &homeserver($cnum,$cdom);
                   4991:         }
                   4992:     }
                   4993:     if ($homeserver eq '') {
                   4994:         $authchk = 'nodomain';
1.506     raeburn  4995:     } else {
1.873     raeburn  4996:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4997:         if ($response eq 'refused') {
                   4998:             $authchk = 'refused';
                   4999:         } else {
1.901     albertel 5000:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5001:         }
1.506     raeburn  5002:     }
                   5003:     return ($authparam,$create_passwd,$authchk);
                   5004: }
                   5005: 
1.706     raeburn  5006: sub auto_photo_permission {
                   5007:     my ($cnum,$cdom,$students) = @_;
                   5008:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5009:     my ($outcome,$perm_reqd,$conditions) = 
                   5010: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5011:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5012: 	return (undef,undef);
                   5013:     }
1.706     raeburn  5014:     return ($outcome,$perm_reqd,$conditions);
                   5015: }
                   5016: 
                   5017: sub auto_checkphotos {
                   5018:     my ($uname,$udom,$pid) = @_;
                   5019:     my $homeserver = &homeserver($uname,$udom);
                   5020:     my ($result,$resulttype);
                   5021:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5022: 				   &escape($uname).':'.&escape($pid),
                   5023: 				   $homeserver));
1.709     albertel 5024:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5025: 	return (undef,undef);
                   5026:     }
1.706     raeburn  5027:     if ($outcome) {
                   5028:         ($result,$resulttype) = split(/:/,$outcome);
                   5029:     } 
                   5030:     return ($result,$resulttype);
                   5031: }
                   5032: 
                   5033: sub auto_photochoice {
                   5034:     my ($cnum,$cdom) = @_;
                   5035:     my $homeserver = &homeserver($cnum,$cdom);
                   5036:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5037: 						       &escape($cdom),
                   5038: 						       $homeserver)));
1.709     albertel 5039:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5040: 	return (undef,undef);
                   5041:     }
1.706     raeburn  5042:     return ($update,$comment);
                   5043: }
                   5044: 
                   5045: sub auto_photoupdate {
                   5046:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5047:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5048:     my $host=&hostname($homeserver);
1.706     raeburn  5049:     my $cmd = '';
                   5050:     my $maxtries = 1;
1.800     albertel 5051:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5052:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5053:     }
                   5054:     $cmd =~ s/%%$//;
                   5055:     $cmd = &escape($cmd);
                   5056:     my $query = 'institutionalphotos';
                   5057:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5058:     unless ($queryid=~/^\Q$host\E\_/) {
                   5059:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5060:         return 'error: '.$queryid;
                   5061:     }
                   5062:     my $reply = &get_query_reply($queryid);
                   5063:     my $tries = 1;
                   5064:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5065:         $reply = &get_query_reply($queryid);
                   5066:         $tries ++;
                   5067:     }
                   5068:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5069:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5070:     } else {
                   5071:         my @responses = split(/:/,$reply);
                   5072:         my $outcome = shift(@responses); 
                   5073:         foreach my $item (@responses) {
                   5074:             my ($key,$value) = split(/=/,$item);
                   5075:             $$photo{$key} = $value;
                   5076:         }
                   5077:         return $outcome;
                   5078:     }
                   5079:     return 'error';
                   5080: }
                   5081: 
1.521     raeburn  5082: sub auto_instcode_format {
1.793     albertel 5083:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5084: 	$cat_order) = @_;
1.521     raeburn  5085:     my $courses = '';
1.772     raeburn  5086:     my @homeservers;
1.521     raeburn  5087:     if ($caller eq 'global') {
1.841     albertel 5088: 	my %servers = &get_servers($codedom,'library');
                   5089: 	foreach my $tryserver (keys(%servers)) {
                   5090: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5091: 		push(@homeservers,$tryserver);
                   5092: 	    }
1.584     raeburn  5093:         }
1.521     raeburn  5094:     } else {
1.772     raeburn  5095:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5096:     }
1.793     albertel 5097:     foreach my $code (keys(%{$instcodes})) {
                   5098:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5099:     }
                   5100:     chop($courses);
1.772     raeburn  5101:     my $ok_response = 0;
                   5102:     my $response;
                   5103:     while (@homeservers > 0 && $ok_response == 0) {
                   5104:         my $server = shift(@homeservers); 
                   5105:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5106:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5107:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5108: 		split(/:/,$response);
1.772     raeburn  5109:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5110:             push(@{$codetitles},&str2array($codetitles_str));
                   5111:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5112:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5113:             $ok_response = 1;
                   5114:         }
                   5115:     }
                   5116:     if ($ok_response) {
1.521     raeburn  5117:         return 'ok';
1.772     raeburn  5118:     } else {
                   5119:         return $response;
1.521     raeburn  5120:     }
                   5121: }
                   5122: 
1.792     raeburn  5123: sub auto_instcode_defaults {
                   5124:     my ($domain,$returnhash,$code_order) = @_;
                   5125:     my @homeservers;
1.841     albertel 5126: 
                   5127:     my %servers = &get_servers($domain,'library');
                   5128:     foreach my $tryserver (keys(%servers)) {
                   5129: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5130: 	    push(@homeservers,$tryserver);
                   5131: 	}
1.792     raeburn  5132:     }
1.841     albertel 5133: 
1.792     raeburn  5134:     my $response;
1.841     albertel 5135:     foreach my $server (@homeservers) {
1.792     raeburn  5136:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5137:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5138: 	
                   5139: 	foreach my $pair (split(/\&/,$response)) {
                   5140: 	    my ($name,$value)=split(/\=/,$pair);
                   5141: 	    if ($name eq 'code_order') {
                   5142: 		@{$code_order} = split(/\&/,&unescape($value));
                   5143: 	    } else {
                   5144: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5145: 	    }
                   5146: 	}
                   5147: 	return 'ok';
1.792     raeburn  5148:     }
1.841     albertel 5149: 
                   5150:     return $response;
1.792     raeburn  5151: } 
                   5152: 
1.777     albertel 5153: sub auto_validate_class_sec {
1.918     raeburn  5154:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5155:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5156:     my $ownerlist;
                   5157:     if (ref($owners) eq 'ARRAY') {
                   5158:         $ownerlist = join(',',@{$owners});
                   5159:     } else {
                   5160:         $ownerlist = $owners;
                   5161:     }
1.773     raeburn  5162:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5163:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5164:     return $response;
                   5165: }
                   5166: 
1.679     raeburn  5167: # ------------------------------------------------------- Course Group routines
                   5168: 
                   5169: sub get_coursegroups {
1.809     raeburn  5170:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5171:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5172: }
                   5173: 
1.679     raeburn  5174: sub modify_coursegroup {
                   5175:     my ($cdom,$cnum,$groupsettings) = @_;
                   5176:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5177: }
                   5178: 
1.809     raeburn  5179: sub toggle_coursegroup_status {
                   5180:     my ($cdom,$cnum,$group,$action) = @_;
                   5181:     my ($from_namespace,$to_namespace);
                   5182:     if ($action eq 'delete') {
                   5183:         $from_namespace = 'coursegroups';
                   5184:         $to_namespace = 'deleted_groups';
                   5185:     } else {
                   5186:         $from_namespace = 'deleted_groups';
                   5187:         $to_namespace = 'coursegroups';
                   5188:     }
                   5189:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5190:     if (my $tmp = &error(%curr_group)) {
                   5191:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5192:         return ('read error',$tmp);
                   5193:     } else {
                   5194:         my %savedsettings = %curr_group; 
1.809     raeburn  5195:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5196:         my $deloutcome;
                   5197:         if ($result eq 'ok') {
1.809     raeburn  5198:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5199:         } else {
                   5200:             return ('write error',$result);
                   5201:         }
                   5202:         if ($deloutcome eq 'ok') {
                   5203:             return 'ok';
                   5204:         } else {
                   5205:             return ('delete error',$deloutcome);
                   5206:         }
                   5207:     }
                   5208: }
                   5209: 
1.679     raeburn  5210: sub modify_group_roles {
                   5211:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5212:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5213:     my $role = 'gr/'.&escape($userprivs);
                   5214:     my ($uname,$udom) = split(/:/,$user);
                   5215:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5216:     if ($result eq 'ok') {
                   5217:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5218:     }
1.679     raeburn  5219:     return $result;
                   5220: }
                   5221: 
                   5222: sub modify_coursegroup_membership {
                   5223:     my ($cdom,$cnum,$membership) = @_;
                   5224:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5225:     return $result;
                   5226: }
                   5227: 
1.682     raeburn  5228: sub get_active_groups {
                   5229:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5230:     my $now = time;
                   5231:     my %groups = ();
                   5232:     foreach my $key (keys(%env)) {
1.811     albertel 5233:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5234:             my ($start,$end) = split(/\./,$env{$key});
                   5235:             if (($end!=0) && ($end<$now)) { next; }
                   5236:             if (($start!=0) && ($start>$now)) { next; }
                   5237:             if ($1 eq $cdom && $2 eq $cnum) {
                   5238:                 $groups{$3} = $env{$key} ;
                   5239:             }
                   5240:         }
                   5241:     }
                   5242:     return %groups;
                   5243: }
                   5244: 
1.683     raeburn  5245: sub get_group_membership {
                   5246:     my ($cdom,$cnum,$group) = @_;
                   5247:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5248: }
                   5249: 
                   5250: sub get_users_groups {
                   5251:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5252:     my @usersgroups;
1.683     raeburn  5253:     my $cachetime=1800;
                   5254: 
                   5255:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5256:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5257:     if (defined($cached)) {
1.734     albertel 5258:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5259:     } else {  
                   5260:         $grouplist = '';
1.816     raeburn  5261:         my $courseurl = &courseid_to_courseurl($courseid);
                   5262:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5263:         my $access_end = $env{'course.'.$courseid.
                   5264:                               '.default_enrollment_end_date'};
                   5265:         my $now = time;
                   5266:         foreach my $key (keys(%roleshash)) {
                   5267:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5268:                 my $group = $1;
                   5269:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5270:                     my $start = $2;
                   5271:                     my $end = $1;
                   5272:                     if ($start == -1) { next; } # deleted from group
                   5273:                     if (($start!=0) && ($start>$now)) { next; }
                   5274:                     if (($end!=0) && ($end<$now)) {
                   5275:                         if ($access_end && $access_end < $now) {
                   5276:                             if ($access_end - $end < 86400) {
                   5277:                                 push(@usersgroups,$group);
1.733     raeburn  5278:                             }
                   5279:                         }
1.817     raeburn  5280:                         next;
1.733     raeburn  5281:                     }
1.817     raeburn  5282:                     push(@usersgroups,$group);
1.683     raeburn  5283:                 }
                   5284:             }
                   5285:         }
1.817     raeburn  5286:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5287:         $grouplist = join(':',@usersgroups);
                   5288:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5289:     }
1.733     raeburn  5290:     return @usersgroups;
1.683     raeburn  5291: }
                   5292: 
                   5293: sub devalidate_getgroups_cache {
                   5294:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5295:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5296: 
1.683     raeburn  5297:     my $hashid="$udom:$uname:$courseid";
                   5298:     &devalidate_cache_new('getgroups',$hashid);
                   5299: }
                   5300: 
1.12      www      5301: # ------------------------------------------------------------------ Plain Text
                   5302: 
                   5303: sub plaintext {
1.742     raeburn  5304:     my ($short,$type,$cid) = @_;
1.758     albertel 5305:     if ($short =~ /^cr/) {
                   5306: 	return (split('/',$short))[-1];
                   5307:     }
1.742     raeburn  5308:     if (!defined($cid)) {
                   5309:         $cid = $env{'request.course.id'};
                   5310:     }
                   5311:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5312:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5313:                                           '.plaintext'});
                   5314:     }
                   5315:     my %rolenames = (
                   5316:                       Course => 'std',
                   5317:                       Group => 'alt1',
                   5318:                     );
                   5319:     if (defined($type) && 
                   5320:          defined($rolenames{$type}) && 
                   5321:          defined($prp{$short}{$rolenames{$type}})) {
                   5322:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5323:     } else {
                   5324:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5325:     }
1.12      www      5326: }
                   5327: 
                   5328: # ----------------------------------------------------------------- Assign Role
                   5329: 
                   5330: sub assignrole {
1.947     raeburn  5331:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
1.21      www      5332:     my $mrole;
                   5333:     if ($role =~ /^cr\//) {
1.393     www      5334:         my $cwosec=$url;
1.811     albertel 5335:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5336: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5337:            &logthis('Refused custom assignrole: '.
                   5338:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5339: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5340:            return 'refused'; 
                   5341:         }
1.21      www      5342:         $mrole='cr';
1.678     raeburn  5343:     } elsif ($role =~ /^gr\//) {
                   5344:         my $cwogrp=$url;
1.811     albertel 5345:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5346:         unless (&allowed('mdg',$cwogrp)) {
                   5347:             &logthis('Refused group assignrole: '.
                   5348:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5349:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5350:             return 'refused';
                   5351:         }
                   5352:         $mrole='gr';
1.21      www      5353:     } else {
1.82      www      5354:         my $cwosec=$url;
1.811     albertel 5355:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5356:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5357:             my $refused;
                   5358:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5359:                 if (!(&allowed('c'.$role,$url))) {
                   5360:                     $refused = 1;
                   5361:                 }
                   5362:             } else {
                   5363:                 $refused = 1;
                   5364:             }
1.947     raeburn  5365:             if ($refused) {
                   5366:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5367:                     $refused = '';
                   5368:                 } else {
                   5369:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5370:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5371: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5372:                     return 'refused';
                   5373:                 }
1.932     raeburn  5374:             }
1.104     www      5375:         }
1.21      www      5376:         $mrole=$role;
                   5377:     }
1.620     albertel 5378:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5379:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5380:     if ($end) { $command.='_'.$end; }
1.21      www      5381:     if ($start) {
                   5382: 	if ($end) { 
1.81      www      5383:            $command.='_'.$start; 
1.21      www      5384:         } else {
1.81      www      5385:            $command.='_0_'.$start;
1.21      www      5386:         }
                   5387:     }
1.739     raeburn  5388:     my $origstart = $start;
                   5389:     my $origend = $end;
1.357     www      5390: # actually delete
                   5391:     if ($deleteflag) {
1.373     www      5392: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5393: # modify command to delete the role
1.620     albertel 5394:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5395:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5396: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5397: # set start and finish to negative values for userrolelog
                   5398:            $start=-1;
                   5399:            $end=-1;
                   5400:         }
                   5401:     }
                   5402: # send command
1.349     www      5403:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5404: # log new user role if status is ok
1.349     www      5405:     if ($answer eq 'ok') {
1.663     raeburn  5406: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5407: # for course roles, perform group memberships changes triggered by role change.
                   5408:         unless ($role =~ /^gr/) {
                   5409:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5410:                                              $origstart);
                   5411:         }
1.349     www      5412:     }
                   5413:     return $answer;
1.169     harris41 5414: }
                   5415: 
                   5416: # -------------------------------------------------- Modify user authentication
1.197     www      5417: # Overrides without validation
                   5418: 
1.169     harris41 5419: sub modifyuserauth {
                   5420:     my ($udom,$uname,$umode,$upass)=@_;
                   5421:     my $uhome=&homeserver($uname,$udom);
1.197     www      5422:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5423:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5424:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5425:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5426:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5427: 		     &escape($upass),$uhome);
1.620     albertel 5428:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5429:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5430:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5431:     &log($udom,,$uname,$uhome,
1.620     albertel 5432:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5433:                                      $env{'user.name'}.', '.$umode.
1.197     www      5434:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5435:     unless ($reply eq 'ok') {
1.197     www      5436:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5437: 	return 'error: '.$reply;
                   5438:     }   
1.170     harris41 5439:     return 'ok';
1.80      www      5440: }
                   5441: 
1.81      www      5442: # --------------------------------------------------------------- Modify a user
1.80      www      5443: 
1.81      www      5444: sub modifyuser {
1.206     matthew  5445:     my ($udom,    $uname, $uid,
                   5446:         $umode,   $upass, $first,
                   5447:         $middle,  $last,  $gene,
1.387     www      5448:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5449:     $udom= &LONCAPA::clean_domain($udom);
                   5450:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5451:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5452:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5453: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5454:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5455:                                      ' desiredhome not specified'). 
1.620     albertel 5456:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5457:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5458:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5459: # ----------------------------------------------------------------- Create User
1.406     albertel 5460:     if (($uhome eq 'no_host') && 
                   5461: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5462:         my $unhome='';
1.844     albertel 5463:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5464:             $unhome = $desiredhome;
1.620     albertel 5465: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5466: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5467:         } else { # load balancing routine for determining $unhome
1.81      www      5468:             my $loadm=10000000;
1.841     albertel 5469: 	    my %servers = &get_servers($udom,'library');
                   5470: 	    foreach my $tryserver (keys(%servers)) {
                   5471: 		my $answer=reply('load',$tryserver);
                   5472: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5473: 		    $loadm=$answer;
                   5474: 		    $unhome=$tryserver;
                   5475: 		}
1.80      www      5476: 	    }
                   5477:         }
                   5478:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5479: 	    return 'error: unable to find a home server for '.$uname.
                   5480:                    ' in domain '.$udom;
1.80      www      5481:         }
                   5482:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5483:                          &escape($upass),$unhome);
                   5484: 	unless ($reply eq 'ok') {
                   5485:             return 'error: '.$reply;
                   5486:         }   
1.230     stredwic 5487:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5488:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5489: 	    return 'error: unable verify users home machine.';
1.80      www      5490:         }
1.209     matthew  5491:     }   # End of creation of new user
1.80      www      5492: # ---------------------------------------------------------------------- Add ID
                   5493:     if ($uid) {
                   5494:        $uid=~tr/A-Z/a-z/;
                   5495:        my %uidhash=&idrget($udom,$uname);
1.196     www      5496:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5497:          && (!$forceid)) {
1.80      www      5498: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5499: 	      return 'error: user id "'.$uid.'" does not match '.
                   5500:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5501:           }
                   5502:        } else {
                   5503: 	  &idput($udom,($uname => $uid));
                   5504:        }
                   5505:     }
                   5506: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5507:     my @tmp=&get('environment',
1.899     raeburn  5508: 		   ['firstname','middlename','lastname','generation','id',
                   5509:                     'permanentemail'],
1.134     albertel 5510: 		   $udom,$uname);
1.313     matthew  5511:     my %names;
                   5512:     if ($tmp[0] =~ m/^error:.*/) { 
                   5513:         %names=(); 
                   5514:     } else {
                   5515:         %names = @tmp;
                   5516:     }
1.388     www      5517: #
                   5518: # Make sure to not trash student environment if instructor does not bother
                   5519: # to supply name and email information
                   5520: #
                   5521:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5522:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5523:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5524:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5525:     if ($email) {
                   5526:        $email=~s/[^\w\@\.\-\,]//gs;
                   5527:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5528: 			   $names{'critnotification'} = $email;
                   5529: 			   $names{'permanentemail'} = $email; }
                   5530:     }
1.899     raeburn  5531:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5532:     my $reply = &put('environment', \%names, $udom,$uname);
                   5533:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5534:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5535:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5536:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5537:              $umode.', '.$first.', '.$middle.', '.
                   5538: 	     $last.', '.$gene.' by '.
1.620     albertel 5539:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5540:     return 'ok';
1.80      www      5541: }
                   5542: 
1.81      www      5543: # -------------------------------------------------------------- Modify student
1.80      www      5544: 
1.81      www      5545: sub modifystudent {
                   5546:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5547:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5548:     if (!$cid) {
1.620     albertel 5549: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5550: 	    return 'not_in_class';
                   5551: 	}
1.80      www      5552:     }
                   5553: # --------------------------------------------------------------- Make the user
1.81      www      5554:     my $reply=&modifyuser
1.209     matthew  5555: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5556:          $desiredhome,$email);
1.80      www      5557:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5558:     # This will cause &modify_student_enrollment to get the uid from the
                   5559:     # students environment
                   5560:     $uid = undef if (!$forceid);
1.455     albertel 5561:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5562: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5563:     return $reply;
                   5564: }
                   5565: 
                   5566: sub modify_student_enrollment {
1.947     raeburn  5567:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
1.455     albertel 5568:     my ($cdom,$cnum,$chome);
                   5569:     if (!$cid) {
1.620     albertel 5570: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5571: 	    return 'not_in_class';
                   5572: 	}
1.620     albertel 5573: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5574: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5575:     } else {
                   5576: 	($cdom,$cnum)=split(/_/,$cid);
                   5577:     }
1.620     albertel 5578:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5579:     if (!$chome) {
1.457     raeburn  5580: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5581:     }
1.455     albertel 5582:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5583:     # Make sure the user exists
1.81      www      5584:     my $uhome=&homeserver($uname,$udom);
                   5585:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5586: 	return 'error: no such user';
                   5587:     }
1.297     matthew  5588:     # Get student data if we were not given enough information
                   5589:     if (!defined($first)  || $first  eq '' || 
                   5590:         !defined($last)   || $last   eq '' || 
                   5591:         !defined($uid)    || $uid    eq '' || 
                   5592:         !defined($middle) || $middle eq '' || 
                   5593:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5594:         # They did not supply us with enough data to enroll the student, so
                   5595:         # we need to pick up more information.
1.297     matthew  5596:         my %tmp = &get('environment',
1.294     matthew  5597:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5598:                        ,$udom,$uname);
                   5599: 
1.800     albertel 5600:         #foreach my $key (keys(%tmp)) {
                   5601:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5602:         #}
1.294     matthew  5603:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5604:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5605:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5606:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5607:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5608:     }
1.556     albertel 5609:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5610:     my $reply=cput('classlist',
                   5611: 		   {"$uname:$udom" => 
1.515     raeburn  5612: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5613: 		   $cdom,$cnum);
1.81      www      5614:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5615: 	return 'error: '.$reply;
1.652     albertel 5616:     } else {
                   5617: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5618:     }
1.297     matthew  5619:     # Add student role to user
1.83      www      5620:     my $uurl='/'.$cid;
1.81      www      5621:     $uurl=~s/\_/\//g;
                   5622:     if ($usec) {
                   5623: 	$uurl.='/'.$usec;
                   5624:     }
1.947     raeburn  5625:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
1.21      www      5626: }
                   5627: 
1.556     albertel 5628: sub format_name {
                   5629:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5630:     my $name;
                   5631:     if ($first ne 'lastname') {
                   5632: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5633:     } else {
                   5634: 	if ($lastname=~/\S/) {
                   5635: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5636: 	    $name=~s/\s+,/,/;
                   5637: 	} else {
                   5638: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5639: 	}
                   5640:     }
                   5641:     $name=~s/^\s+//;
                   5642:     $name=~s/\s+$//;
                   5643:     $name=~s/\s+/ /g;
                   5644:     return $name;
                   5645: }
                   5646: 
1.84      www      5647: # ------------------------------------------------- Write to course preferences
                   5648: 
                   5649: sub writecoursepref {
                   5650:     my ($courseid,%prefs)=@_;
                   5651:     $courseid=~s/^\///;
                   5652:     $courseid=~s/\_/\//g;
                   5653:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5654:     my $chome=homeserver($cnum,$cdomain);
                   5655:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5656: 	return 'error: no such course';
                   5657:     }
                   5658:     my $cstring='';
1.800     albertel 5659:     foreach my $pref (keys(%prefs)) {
                   5660: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5661:     }
1.84      www      5662:     $cstring=~s/\&$//;
                   5663:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5664: }
                   5665: 
                   5666: # ---------------------------------------------------------- Make/modify course
                   5667: 
                   5668: sub createcourse {
1.741     raeburn  5669:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5670:         $course_owner,$crstype)=@_;
1.84      www      5671:     $url=&declutter($url);
                   5672:     my $cid='';
1.264     matthew  5673:     unless (&allowed('ccc',$udom)) {
1.84      www      5674:         return 'refused';
                   5675:     }
                   5676: # ------------------------------------------------------------------- Create ID
1.674     www      5677:    my $uname=int(1+rand(9)).
                   5678:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5679:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5680:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5681: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5682:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5683:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5684:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5685:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5686:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5687:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5688:            return 'error: unable to generate unique course-ID';
                   5689:        } 
                   5690:    }
1.264     matthew  5691: # ------------------------------------------------ Check supplied server name
1.620     albertel 5692:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5693:     if (! &is_library($course_server)) {
1.264     matthew  5694:         return 'error:bad server name '.$course_server;
                   5695:     }
1.84      www      5696: # ------------------------------------------------------------- Make the course
                   5697:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5698:                       $course_server);
1.84      www      5699:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5700:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5701:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5702: 	return 'error: no such course';
                   5703:     }
1.271     www      5704: # ----------------------------------------------------------------- Course made
1.516     raeburn  5705: # log existence
1.918     raeburn  5706:     my $newcourse = {
                   5707:                     $udom.'_'.$uname => {
1.921     raeburn  5708:                                      description => $description,
                   5709:                                      inst_code   => $inst_code,
                   5710:                                      owner       => $course_owner,
                   5711:                                      type        => $crstype,
1.918     raeburn  5712:                                                 },
                   5713:                     };
1.921     raeburn  5714:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5715: # set toplevel url
1.271     www      5716:     my $topurl=$url;
                   5717:     unless ($nonstandard) {
                   5718: # ------------------------------------------ For standard courses, make top url
                   5719:         my $mapurl=&clutter($url);
1.278     www      5720:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5721:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5722: <map>
                   5723: <resource id="1" type="start"></resource>
                   5724: <resource id="2" src="$mapurl"></resource>
                   5725: <resource id="3" type="finish"></resource>
                   5726: <link index="1" from="1" to="2"></link>
                   5727: <link index="2" from="2" to="3"></link>
                   5728: </map>
                   5729: ENDINITMAP
                   5730:         $topurl=&declutter(
1.638     albertel 5731:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5732:                           );
                   5733:     }
                   5734: # ----------------------------------------------------------- Write preferences
1.84      www      5735:     &writecoursepref($udom.'_'.$uname,
                   5736:                      ('description' => $description,
1.271     www      5737:                       'url'         => $topurl));
1.84      www      5738:     return '/'.$udom.'/'.$uname;
                   5739: }
                   5740: 
1.813     albertel 5741: sub is_course {
                   5742:     my ($cdom,$cnum) = @_;
                   5743:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  5744: 				undef,'.');
1.813     albertel 5745:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5746:         return 1;
                   5747:     }
                   5748:     return 0;
                   5749: }
                   5750: 
1.21      www      5751: # ---------------------------------------------------------- Assign Custom Role
                   5752: 
                   5753: sub assigncustomrole {
1.357     www      5754:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5755:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5756:                        $end,$start,$deleteflag);
1.21      www      5757: }
                   5758: 
                   5759: # ----------------------------------------------------------------- Revoke Role
                   5760: 
                   5761: sub revokerole {
1.357     www      5762:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5763:     my $now=time;
1.357     www      5764:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5765: }
                   5766: 
                   5767: # ---------------------------------------------------------- Revoke Custom Role
                   5768: 
                   5769: sub revokecustomrole {
1.357     www      5770:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5771:     my $now=time;
1.357     www      5772:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5773:            $deleteflag);
1.17      www      5774: }
                   5775: 
1.533     banghart 5776: # ------------------------------------------------------------ Disk usage
1.535     albertel 5777: sub diskusage {
1.533     banghart 5778:     my ($udom,$uname,$directoryRoot)=@_;
                   5779:     $directoryRoot =~ s/\/$//;
1.535     albertel 5780:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5781:     return $listing;
1.512     banghart 5782: }
                   5783: 
1.566     banghart 5784: sub is_locked {
                   5785:     my ($file_name, $domain, $user) = @_;
                   5786:     my @check;
                   5787:     my $is_locked;
                   5788:     push @check, $file_name;
1.613     albertel 5789:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5790: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5791:     my ($tmp)=keys(%locked);
                   5792:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5793:     
1.566     banghart 5794:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5795:         $is_locked = 'false';
                   5796:         foreach my $entry (@{$locked{$file_name}}) {
                   5797:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5798:                $is_locked = 'true';
                   5799:                last;
1.745     raeburn  5800:            }
                   5801:        }
1.566     banghart 5802:     } else {
                   5803:         $is_locked = 'false';
                   5804:     }
                   5805: }
                   5806: 
1.759     albertel 5807: sub declutter_portfile {
                   5808:     my ($file) = @_;
1.833     albertel 5809:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5810:     return $file;
                   5811: }
                   5812: 
1.559     banghart 5813: # ------------------------------------------------------------- Mark as Read Only
                   5814: 
                   5815: sub mark_as_readonly {
                   5816:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5817:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5818:     my ($tmp)=keys(%current_permissions);
                   5819:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5820:     foreach my $file (@{$files}) {
1.759     albertel 5821: 	$file = &declutter_portfile($file);
1.561     banghart 5822:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5823:     }
1.613     albertel 5824:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5825:     return;
                   5826: }
                   5827: 
1.572     banghart 5828: # ------------------------------------------------------------Save Selected Files
                   5829: 
                   5830: sub save_selected_files {
                   5831:     my ($user, $path, @files) = @_;
                   5832:     my $filename = $user."savedfiles";
1.573     banghart 5833:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5834:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5835:     foreach my $file (@files) {
1.620     albertel 5836:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5837:     }
                   5838:     foreach my $file (@other_files) {
1.574     banghart 5839:         print (OUT $file."\n");
1.572     banghart 5840:     }
1.574     banghart 5841:     close (OUT);
1.572     banghart 5842:     return 'ok';
                   5843: }
                   5844: 
1.574     banghart 5845: sub clear_selected_files {
                   5846:     my ($user) = @_;
                   5847:     my $filename = $user."savedfiles";
                   5848:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5849:     print (OUT undef);
                   5850:     close (OUT);
                   5851:     return ("ok");    
                   5852: }
                   5853: 
1.572     banghart 5854: sub files_in_path {
                   5855:     my ($user, $path) = @_;
                   5856:     my $filename = $user."savedfiles";
                   5857:     my %return_files;
1.574     banghart 5858:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5859:     while (my $line_in = <IN>) {
1.574     banghart 5860:         chomp ($line_in);
                   5861:         my @paths_and_file = split (m!/!, $line_in);
                   5862:         my $file_part = pop (@paths_and_file);
                   5863:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5864:         $path_part.='/';
                   5865:         my $path_and_file = $path_part.$file_part;
                   5866:         if ($path_part eq $path) {
                   5867:             $return_files{$file_part}= 'selected';
                   5868:         }
                   5869:     }
1.574     banghart 5870:     close (IN);
                   5871:     return (\%return_files);
1.572     banghart 5872: }
                   5873: 
                   5874: # called in portfolio select mode, to show files selected NOT in current directory
                   5875: sub files_not_in_path {
                   5876:     my ($user, $path) = @_;
                   5877:     my $filename = $user."savedfiles";
                   5878:     my @return_files;
                   5879:     my $path_part;
1.800     albertel 5880:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5881:     while (my $line = <IN>) {
1.572     banghart 5882:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5883:         my @paths_and_file = split(m|/|, $line);
                   5884:         my $file_part = pop(@paths_and_file);
                   5885:         chomp($file_part);
                   5886:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5887:         $path_part .= '/';
                   5888:         my $path_and_file = $path_part.$file_part;
                   5889:         if ($path_part ne $path) {
1.800     albertel 5890:             push(@return_files, ($path_and_file));
1.572     banghart 5891:         }
                   5892:     }
1.800     albertel 5893:     close(OUT);
1.574     banghart 5894:     return (@return_files);
1.572     banghart 5895: }
                   5896: 
1.745     raeburn  5897: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5898: 
1.745     raeburn  5899: sub get_portfile_permissions {
                   5900:     my ($domain,$user) = @_;
1.613     albertel 5901:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5902:     my ($tmp)=keys(%current_permissions);
                   5903:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5904:     return \%current_permissions;
                   5905: }
                   5906: 
                   5907: #---------------------------------------------Get portfolio file access controls
                   5908: 
1.749     raeburn  5909: sub get_access_controls {
1.745     raeburn  5910:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5911:     my %access;
                   5912:     my $real_file = $file;
                   5913:     $file =~ s/\.meta$//;
1.745     raeburn  5914:     if (defined($file)) {
1.749     raeburn  5915:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5916:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5917:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5918:             }
                   5919:         }
1.745     raeburn  5920:     } else {
1.749     raeburn  5921:         foreach my $key (keys(%{$current_permissions})) {
                   5922:             if ($key =~ /\0accesscontrol$/) {
                   5923:                 if (defined($group)) {
                   5924:                     if ($key !~ m-^\Q$group\E/-) {
                   5925:                         next;
                   5926:                     }
                   5927:                 }
                   5928:                 my ($fullpath) = split(/\0/,$key);
                   5929:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5930:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5931:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5932:                     }
                   5933:                 }
                   5934:             }
                   5935:         }
                   5936:     }
                   5937:     return %access;
                   5938: }
                   5939: 
                   5940: sub modify_access_controls {
                   5941:     my ($file_name,$changes,$domain,$user)=@_;
                   5942:     my ($outcome,$deloutcome);
                   5943:     my %store_permissions;
                   5944:     my %new_values;
                   5945:     my %new_control;
                   5946:     my %translation;
                   5947:     my @deletions = ();
                   5948:     my $now = time;
                   5949:     if (exists($$changes{'activate'})) {
                   5950:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5951:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5952:             my $numnew = scalar(@newitems);
                   5953:             for (my $i=0; $i<$numnew; $i++) {
                   5954:                 my $newkey = $newitems[$i];
                   5955:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5956:                 if ($newkey =~ /^\d+:/) { 
                   5957:                     $newkey =~ s/^(\d+)/$newid/;
                   5958:                     $translation{$1} = $newid;
                   5959:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5960:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5961:                     $translation{$1} = $newid;
                   5962:                 }
1.749     raeburn  5963:                 $new_values{$file_name."\0".$newkey} = 
                   5964:                                           $$changes{'activate'}{$newitems[$i]};
                   5965:                 $new_control{$newkey} = $now;
                   5966:             }
                   5967:         }
                   5968:     }
                   5969:     my %todelete;
                   5970:     my %changed_items;
                   5971:     foreach my $action ('delete','update') {
                   5972:         if (exists($$changes{$action})) {
                   5973:             if (ref($$changes{$action}) eq 'HASH') {
                   5974:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5975:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5976:                     if ($action eq 'delete') { 
                   5977:                         $todelete{$itemnum} = 1;
                   5978:                     } else {
                   5979:                         $changed_items{$itemnum} = $key;
                   5980:                     }
                   5981:                 }
1.745     raeburn  5982:             }
                   5983:         }
1.749     raeburn  5984:     }
                   5985:     # get lock on access controls for file.
                   5986:     my $lockhash = {
                   5987:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5988:                                                        ':'.$env{'user.domain'},
                   5989:                    }; 
                   5990:     my $tries = 0;
                   5991:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5992:    
                   5993:     while (($gotlock ne 'ok') && $tries <3) {
                   5994:         $tries ++;
                   5995:         sleep 1;
                   5996:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5997:     }
                   5998:     if ($gotlock eq 'ok') {
                   5999:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6000:         my ($tmp)=keys(%curr_permissions);
                   6001:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6002:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6003:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6004:             if (ref($curr_controls) eq 'HASH') {
                   6005:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6006:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6007:                     if (defined($todelete{$itemnum})) {
                   6008:                         push(@deletions,$file_name."\0".$control_item);
                   6009:                     } else {
                   6010:                         if (defined($changed_items{$itemnum})) {
                   6011:                             $new_control{$changed_items{$itemnum}} = $now;
                   6012:                             push(@deletions,$file_name."\0".$control_item);
                   6013:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6014:                         } else {
                   6015:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6016:                         }
                   6017:                     }
1.745     raeburn  6018:                 }
                   6019:             }
                   6020:         }
1.749     raeburn  6021:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6022:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6023:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6024:         #  remove lock
                   6025:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6026:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6027:         my ($file,$group);
                   6028:         if (&is_course($domain,$user)) {
                   6029:             ($group,$file) = split(/\//,$file_name,2);
                   6030:         } else {
                   6031:             $file = $file_name;
                   6032:         }
                   6033:         my $sqlresult =
                   6034:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6035:                                     $group);
1.749     raeburn  6036:     } else {
                   6037:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6038:     }
1.749     raeburn  6039:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6040: }
                   6041: 
1.827     raeburn  6042: sub make_public_indefinitely {
                   6043:     my ($requrl) = @_;
                   6044:     my $now = time;
                   6045:     my $action = 'activate';
                   6046:     my $aclnum = 0;
                   6047:     if (&is_portfolio_url($requrl)) {
                   6048:         my (undef,$udom,$unum,$file_name,$group) =
                   6049:             &parse_portfolio_url($requrl);
                   6050:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6051:         my %access_controls = &get_access_controls($current_perms,
                   6052:                                                    $group,$file_name);
                   6053:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6054:             my ($num,$scope,$end,$start) = 
                   6055:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6056:             if ($scope eq 'public') {
                   6057:                 if ($start <= $now && $end == 0) {
                   6058:                     $action = 'none';
                   6059:                 } else {
                   6060:                     $action = 'update';
                   6061:                     $aclnum = $num;
                   6062:                 }
                   6063:                 last;
                   6064:             }
                   6065:         }
                   6066:         if ($action eq 'none') {
                   6067:              return 'ok';
                   6068:         } else {
                   6069:             my %changes;
                   6070:             my $newend = 0;
                   6071:             my $newstart = $now;
                   6072:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6073:             $changes{$action}{$newkey} = {
                   6074:                 type => 'public',
                   6075:                 time => {
                   6076:                     start => $newstart,
                   6077:                     end   => $newend,
                   6078:                 },
                   6079:             };
                   6080:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6081:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6082:             return $outcome;
                   6083:         }
                   6084:     } else {
                   6085:         return 'invalid';
                   6086:     }
                   6087: }
                   6088: 
1.745     raeburn  6089: #------------------------------------------------------Get Marked as Read Only
                   6090: 
                   6091: sub get_marked_as_readonly {
                   6092:     my ($domain,$user,$what,$group) = @_;
                   6093:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6094:     my @readonly_files;
1.629     banghart 6095:     my $cmp1=$what;
                   6096:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6097:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6098:         if (defined($group)) {
                   6099:             if ($file_name !~ m-^\Q$group\E/-) {
                   6100:                 next;
                   6101:             }
                   6102:         }
1.561     banghart 6103:         if (ref($value) eq "ARRAY"){
                   6104:             foreach my $stored_what (@{$value}) {
1.629     banghart 6105:                 my $cmp2=$stored_what;
1.759     albertel 6106:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6107:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6108:                 }
1.629     banghart 6109:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6110:                     push(@readonly_files, $file_name);
1.745     raeburn  6111:                     last;
1.563     banghart 6112:                 } elsif (!defined($what)) {
                   6113:                     push(@readonly_files, $file_name);
1.745     raeburn  6114:                     last;
1.561     banghart 6115:                 }
                   6116:             }
1.745     raeburn  6117:         }
1.561     banghart 6118:     }
                   6119:     return @readonly_files;
                   6120: }
1.577     banghart 6121: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6122: 
1.577     banghart 6123: sub get_marked_as_readonly_hash {
1.745     raeburn  6124:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6125:     my %readonly_files;
1.745     raeburn  6126:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6127:         if (defined($group)) {
                   6128:             if ($file_name !~ m-^\Q$group\E/-) {
                   6129:                 next;
                   6130:             }
                   6131:         }
1.577     banghart 6132:         if (ref($value) eq "ARRAY"){
                   6133:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6134:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6135:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6136:                         if ($lock_descriptor eq 'graded') {
                   6137:                             $readonly_files{$file_name} = 'graded';
                   6138:                         } elsif ($lock_descriptor eq 'handback') {
                   6139:                             $readonly_files{$file_name} = 'handback';
                   6140:                         } else {
                   6141:                             if (!exists($readonly_files{$file_name})) {
                   6142:                                 $readonly_files{$file_name} = 'locked';
                   6143:                             }
                   6144:                         }
1.745     raeburn  6145:                     }
1.750     banghart 6146:                 } 
1.577     banghart 6147:             }
                   6148:         } 
                   6149:     }
                   6150:     return %readonly_files;
                   6151: }
1.559     banghart 6152: # ------------------------------------------------------------ Unmark as Read Only
                   6153: 
                   6154: sub unmark_as_readonly {
1.629     banghart 6155:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6156:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6157:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6158:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6159:     my $symb_crs = $what;
                   6160:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6161:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6162:     my ($tmp)=keys(%current_permissions);
                   6163:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6164:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6165:     foreach my $file (@readonly_files) {
1.759     albertel 6166: 	my $clean_file = &declutter_portfile($file);
                   6167: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6168: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6169:         my @new_locks;
                   6170:         my @del_keys;
                   6171:         if (ref($current_locks) eq "ARRAY"){
                   6172:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6173:                 my $compare=$locker;
1.749     raeburn  6174:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6175:                     $compare=join('',@{$locker});
1.746     raeburn  6176:                     if ($compare ne $symb_crs) {
                   6177:                         push(@new_locks, $locker);
                   6178:                     }
1.563     banghart 6179:                 }
                   6180:             }
1.650     albertel 6181:             if (scalar(@new_locks) > 0) {
1.563     banghart 6182:                 $current_permissions{$file} = \@new_locks;
                   6183:             } else {
                   6184:                 push(@del_keys, $file);
1.613     albertel 6185:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6186:                 delete($current_permissions{$file});
1.563     banghart 6187:             }
                   6188:         }
1.561     banghart 6189:     }
1.613     albertel 6190:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6191:     return;
                   6192: }
1.512     banghart 6193: 
1.17      www      6194: # ------------------------------------------------------------ Directory lister
                   6195: 
                   6196: sub dirlist {
1.253     stredwic 6197:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   6198: 
1.18      www      6199:     $uri=~s/^\///;
                   6200:     $uri=~s/\/$//;
1.253     stredwic 6201:     my ($udom, $uname);
                   6202:     (undef,$udom,$uname)=split(/\//,$uri);
                   6203:     if(defined($userdomain)) {
                   6204:         $udom = $userdomain;
                   6205:     }
                   6206:     if(defined($username)) {
                   6207:         $uname = $username;
                   6208:     }
                   6209: 
                   6210:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6211:     if(defined($alternateDirectoryRoot)) {
                   6212:         $dirRoot = $alternateDirectoryRoot;
                   6213:         $dirRoot =~ s/\/$//;
1.751     banghart 6214:     }
1.253     stredwic 6215: 
                   6216:     if($udom) {
                   6217:         if($uname) {
1.800     albertel 6218:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6219: 				 &homeserver($uname,$udom));
1.605     matthew  6220:             my @listing_results;
                   6221:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6222:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6223: 				  &homeserver($uname,$udom));
1.605     matthew  6224:                 @listing_results = split(/:/,$listing);
                   6225:             } else {
                   6226:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6227:             }
                   6228:             return @listing_results;
1.253     stredwic 6229:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6230:             my %allusers;
1.841     albertel 6231: 	    my %servers = &get_servers($udom,'library');
                   6232: 	    foreach my $tryserver (keys(%servers)) {
                   6233: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6234: 				     $udom, $tryserver);
                   6235: 		my @listing_results;
                   6236: 		if ($listing eq 'unknown_cmd') {
                   6237: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6238: 				      $udom, $tryserver);
                   6239: 		    @listing_results = split(/:/,$listing);
                   6240: 		} else {
                   6241: 		    @listing_results =
                   6242: 			map { &unescape($_); } split(/:/,$listing);
                   6243: 		}
                   6244: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6245: 		    $listing_results[0] ne 'empty'       &&
                   6246: 		    $listing_results[0] ne 'con_lost') {
                   6247: 		    foreach my $line (@listing_results) {
                   6248: 			my ($entry) = split(/&/,$line,2);
                   6249: 			$allusers{$entry} = 1;
                   6250: 		    }
                   6251: 		}
1.253     stredwic 6252:             }
                   6253:             my $alluserstr='';
1.800     albertel 6254:             foreach my $user (sort(keys(%allusers))) {
                   6255:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6256:             }
                   6257:             $alluserstr=~s/:$//;
                   6258:             return split(/:/,$alluserstr);
                   6259:         } else {
1.800     albertel 6260:             return ('missing user name');
1.253     stredwic 6261:         }
                   6262:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6263:         my @all_domains = sort(&all_domains());
                   6264:          foreach my $domain (@all_domains) {
                   6265:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6266:          }
                   6267:          return @all_domains;
                   6268:      } else {
1.800     albertel 6269:         return ('missing domain');
1.275     stredwic 6270:     }
                   6271: }
                   6272: 
                   6273: # --------------------------------------------- GetFileTimestamp
                   6274: # This function utilizes dirlist and returns the date stamp for
                   6275: # when it was last modified.  It will also return an error of -1
                   6276: # if an error occurs
                   6277: 
1.410     matthew  6278: ##
                   6279: ## FIXME: This subroutine assumes its caller knows something about the
                   6280: ## directory structure of the home server for the student ($root).
                   6281: ## Not a good assumption to make.  Since this is for looking up files
                   6282: ## in user directories, the full path should be constructed by lond, not
                   6283: ## whatever machine we request data from.
                   6284: ##
1.275     stredwic 6285: sub GetFileTimestamp {
                   6286:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6287:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6288:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6289:     my $subdir=$studentName.'__';
                   6290:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6291:     my $proname="$studentDomain/$subdir/$studentName";
                   6292:     $proname .= '/'.$filename;
1.375     matthew  6293:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6294:                                               $studentName, $root);
1.275     stredwic 6295:     my @stats = split('&', $fileStat);
                   6296:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6297:         # @stats contains first the filename, then the stat output
                   6298:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6299:     } else {
                   6300:         return -1;
1.253     stredwic 6301:     }
1.26      www      6302: }
                   6303: 
1.712     albertel 6304: sub stat_file {
                   6305:     my ($uri) = @_;
1.787     albertel 6306:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6307: 
1.712     albertel 6308:     my ($udom,$uname,$file,$dir);
                   6309:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6310: 	($udom,$uname,$file) =
1.811     albertel 6311: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6312: 	$file = 'userfiles/'.$file;
1.740     www      6313: 	$dir = &propath($udom,$uname);
1.712     albertel 6314:     }
                   6315:     if ($uri =~ m-^/res/-) {
                   6316: 	($udom,$uname) = 
1.807     albertel 6317: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6318: 	$file = $uri;
                   6319:     }
                   6320: 
                   6321:     if (!$udom || !$uname || !$file) {
                   6322: 	# unable to handle the uri
                   6323: 	return ();
                   6324:     }
                   6325: 
                   6326:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6327:     my @stats = split('&', $result);
1.721     banghart 6328:     
1.712     albertel 6329:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6330: 	shift(@stats); #filename is first
                   6331: 	return @stats;
                   6332:     }
                   6333:     return ();
                   6334: }
                   6335: 
1.26      www      6336: # -------------------------------------------------------- Value of a Condition
                   6337: 
1.713     albertel 6338: # gets the value of a specific preevaluated condition
                   6339: #    stored in the string  $env{user.state.<cid>}
                   6340: # or looks up a condition reference in the bighash and if if hasn't
                   6341: # already been evaluated recurses into docondval to get the value of
                   6342: # the condition, then memoizing it to 
                   6343: #   $env{user.state.<cid>.<condition>}
1.40      www      6344: sub directcondval {
                   6345:     my $number=shift;
1.620     albertel 6346:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6347: 	&Apache::lonuserstate::evalstate();
                   6348:     }
1.713     albertel 6349:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6350: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6351:     } elsif ($number =~ /^_/) {
                   6352: 	my $sub_condition;
                   6353: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6354: 		&GDBM_READER(),0640)) {
                   6355: 	    $sub_condition=$bighash{'conditions'.$number};
                   6356: 	    untie(%bighash);
                   6357: 	}
                   6358: 	my $value = &docondval($sub_condition);
1.949     raeburn  6359: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6360: 	return $value;
                   6361:     }
1.620     albertel 6362:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6363:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6364:     } else {
                   6365:        return 2;
                   6366:     }
                   6367: }
                   6368: 
1.713     albertel 6369: # get the collection of conditions for this resource
1.26      www      6370: sub condval {
                   6371:     my $condidx=shift;
1.54      www      6372:     my $allpathcond='';
1.713     albertel 6373:     foreach my $cond (split(/\|/,$condidx)) {
                   6374: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6375: 	    $allpathcond.=
                   6376: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6377: 	}
1.191     harris41 6378:     }
1.54      www      6379:     $allpathcond=~s/\|$//;
1.713     albertel 6380:     return &docondval($allpathcond);
                   6381: }
                   6382: 
                   6383: #evaluates an expression of conditions
                   6384: sub docondval {
                   6385:     my ($allpathcond) = @_;
                   6386:     my $result=0;
                   6387:     if ($env{'request.course.id'}
                   6388: 	&& defined($allpathcond)) {
                   6389: 	my $operand='|';
                   6390: 	my @stack;
                   6391: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6392: 	    if ($chunk eq '(') {
                   6393: 		push @stack,($operand,$result);
                   6394: 	    } elsif ($chunk eq ')') {
                   6395: 		my $before=pop @stack;
                   6396: 		if (pop @stack eq '&') {
                   6397: 		    $result=$result>$before?$before:$result;
                   6398: 		} else {
                   6399: 		    $result=$result>$before?$result:$before;
                   6400: 		}
                   6401: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6402: 		$operand=$chunk;
                   6403: 	    } else {
                   6404: 		my $new=directcondval($chunk);
                   6405: 		if ($operand eq '&') {
                   6406: 		    $result=$result>$new?$new:$result;
                   6407: 		} else {
                   6408: 		    $result=$result>$new?$result:$new;
                   6409: 		}
                   6410: 	    }
                   6411: 	}
1.26      www      6412:     }
                   6413:     return $result;
1.421     albertel 6414: }
                   6415: 
                   6416: # ---------------------------------------------------- Devalidate courseresdata
                   6417: 
                   6418: sub devalidatecourseresdata {
                   6419:     my ($coursenum,$coursedomain)=@_;
                   6420:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6421:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6422: }
                   6423: 
1.763     www      6424: 
1.200     www      6425: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6426: #
                   6427: #  Parameters:
                   6428: #      $coursenum    - Number of the course.
                   6429: #      $coursedomain - Domain at which the course was created.
                   6430: #  Returns:
                   6431: #     A hash of the course parameters along (I think) with timestamps
                   6432: #     and version info.
1.877     foxr     6433: 
1.624     albertel 6434: sub get_courseresdata {
                   6435:     my ($coursenum,$coursedomain)=@_;
1.200     www      6436:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6437:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6438:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6439:     my %dumpreply;
1.417     albertel 6440:     unless (defined($cached)) {
1.624     albertel 6441: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6442: 	$result=\%dumpreply;
1.251     albertel 6443: 	my ($tmp) = keys(%dumpreply);
                   6444: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6445: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6446: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6447: 	    return $tmp;
1.416     albertel 6448: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6449: 	    $result=undef;
1.599     albertel 6450: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6451: 	}
                   6452:     }
1.624     albertel 6453:     return $result;
                   6454: }
                   6455: 
1.633     albertel 6456: sub devalidateuserresdata {
                   6457:     my ($uname,$udom)=@_;
                   6458:     my $hashid="$udom:$uname";
                   6459:     &devalidate_cache_new('userres',$hashid);
                   6460: }
                   6461: 
1.624     albertel 6462: sub get_userresdata {
                   6463:     my ($uname,$udom)=@_;
                   6464:     #most student don\'t have any data set, check if there is some data
                   6465:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6466: 
                   6467:     my $hashid="$udom:$uname";
                   6468:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6469:     if (!defined($cached)) {
                   6470: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6471: 	$result=\%resourcedata;
                   6472: 	&do_cache_new('userres',$hashid,$result,600);
                   6473:     }
                   6474:     my ($tmp)=keys(%$result);
                   6475:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6476: 	return $result;
                   6477:     }
                   6478:     #error 2 occurs when the .db doesn't exist
                   6479:     if ($tmp!~/error: 2 /) {
1.672     albertel 6480: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6481: 		 " Trying to get resource data for ".
                   6482: 		 $uname." at ".$udom.": ".
                   6483: 		 $tmp."</font>");
                   6484:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6485: 	#&EXT_cache_set($udom,$uname);
                   6486: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6487: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6488:     }
                   6489:     return $tmp;
                   6490: }
1.879     foxr     6491: #----------------------------------------------- resdata - return resource data
                   6492: #  Purpose:
                   6493: #    Return resource data for either users or for a course.
                   6494: #  Parameters:
                   6495: #     $name      - Course/user name.
                   6496: #     $domain    - Name of the domain the user/course is registered on.
                   6497: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6498: #     @which     - Array of names of resources desired.
                   6499: #  Returns:
                   6500: #     The value of the first reasource in @which that is found in the
                   6501: #     resource hash.
                   6502: #  Exceptional Conditions:
                   6503: #     If the $type passed in is not valid (not the string 'course' or 
                   6504: #     'user', an undefined  reference is returned.
                   6505: #     If none of the resources are found, an undef is returned
1.624     albertel 6506: sub resdata {
                   6507:     my ($name,$domain,$type,@which)=@_;
                   6508:     my $result;
                   6509:     if ($type eq 'course') {
                   6510: 	$result=&get_courseresdata($name,$domain);
                   6511:     } elsif ($type eq 'user') {
                   6512: 	$result=&get_userresdata($name,$domain);
                   6513:     }
                   6514:     if (!ref($result)) { return $result; }    
1.251     albertel 6515:     foreach my $item (@which) {
1.927     albertel 6516: 	if (defined($result->{$item->[0]})) {
                   6517: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6518: 	}
1.250     albertel 6519:     }
1.291     albertel 6520:     return undef;
1.200     www      6521: }
                   6522: 
1.379     matthew  6523: #
                   6524: # EXT resource caching routines
                   6525: #
                   6526: 
                   6527: sub clear_EXT_cache_status {
1.383     albertel 6528:     &delenv('cache.EXT.');
1.379     matthew  6529: }
                   6530: 
                   6531: sub EXT_cache_status {
                   6532:     my ($target_domain,$target_user) = @_;
1.383     albertel 6533:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6534:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6535:         # We know already the user has no data
                   6536:         return 1;
                   6537:     } else {
                   6538:         return 0;
                   6539:     }
                   6540: }
                   6541: 
                   6542: sub EXT_cache_set {
                   6543:     my ($target_domain,$target_user) = @_;
1.383     albertel 6544:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6545:     #&appenv({$cachename => time});
1.379     matthew  6546: }
                   6547: 
1.28      www      6548: # --------------------------------------------------------- Value of a Variable
1.58      www      6549: sub EXT {
1.715     albertel 6550: 
1.395     albertel 6551:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6552:     unless ($varname) { return ''; }
1.218     albertel 6553:     #get real user name/domain, courseid and symb
                   6554:     my $courseid;
1.359     albertel 6555:     my $publicuser;
1.427     www      6556:     if ($symbparm) {
                   6557: 	$symbparm=&get_symb_from_alias($symbparm);
                   6558:     }
1.218     albertel 6559:     if (!($uname && $udom)) {
1.790     albertel 6560:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6561:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6562:     } else {
1.620     albertel 6563: 	$courseid=$env{'request.course.id'};
1.218     albertel 6564:     }
1.48      www      6565:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6566:     my $rest;
1.320     albertel 6567:     if (defined($therest[0])) {
1.48      www      6568:        $rest=join('.',@therest);
                   6569:     } else {
                   6570:        $rest='';
                   6571:     }
1.320     albertel 6572: 
1.57      www      6573:     my $qualifierrest=$qualifier;
                   6574:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6575:     my $spacequalifierrest=$space;
                   6576:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6577:     if ($realm eq 'user') {
1.48      www      6578: # --------------------------------------------------------------- user.resource
                   6579: 	if ($space eq 'resource') {
1.651     albertel 6580: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6581: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6582: 		 &&
1.744     albertel 6583: 		 ($symbparm eq &symbread()) ) {	
                   6584: 		# if we are in the middle of processing the resource the
                   6585: 		# get the value we are planning on committing
                   6586:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6587:                     return $Apache::lonhomework::results{$qualifierrest};
                   6588:                 } else {
                   6589:                     return $Apache::lonhomework::history{$qualifierrest};
                   6590:                 }
1.335     albertel 6591: 	    } else {
1.359     albertel 6592: 		my %restored;
1.620     albertel 6593: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6594: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6595: 		} else {
                   6596: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6597: 		}
1.335     albertel 6598: 		return $restored{$qualifierrest};
                   6599: 	    }
1.48      www      6600: # ----------------------------------------------------------------- user.access
                   6601:         } elsif ($space eq 'access') {
1.218     albertel 6602: 	    # FIXME - not supporting calls for a specific user
1.48      www      6603:             return &allowed($qualifier,$rest);
                   6604: # ------------------------------------------ user.preferences, user.environment
                   6605:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6606: 	    if (($uname eq $env{'user.name'}) &&
                   6607: 		($udom eq $env{'user.domain'})) {
                   6608: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6609: 	    } else {
1.359     albertel 6610: 		my %returnhash;
                   6611: 		if (!$publicuser) {
                   6612: 		    %returnhash=&userenvironment($udom,$uname,
                   6613: 						 $qualifierrest);
                   6614: 		}
1.218     albertel 6615: 		return $returnhash{$qualifierrest};
                   6616: 	    }
1.48      www      6617: # ----------------------------------------------------------------- user.course
                   6618:         } elsif ($space eq 'course') {
1.218     albertel 6619: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6620:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6621: # ------------------------------------------------------------------- user.role
                   6622:         } elsif ($space eq 'role') {
1.218     albertel 6623: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6624:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6625:             if ($qualifier eq 'value') {
                   6626: 		return $role;
                   6627:             } elsif ($qualifier eq 'extent') {
                   6628:                 return $where;
                   6629:             }
                   6630: # ----------------------------------------------------------------- user.domain
                   6631:         } elsif ($space eq 'domain') {
1.218     albertel 6632:             return $udom;
1.48      www      6633: # ------------------------------------------------------------------- user.name
                   6634:         } elsif ($space eq 'name') {
1.218     albertel 6635:             return $uname;
1.48      www      6636: # ---------------------------------------------------- Any other user namespace
1.29      www      6637:         } else {
1.359     albertel 6638: 	    my %reply;
                   6639: 	    if (!$publicuser) {
                   6640: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6641: 	    }
                   6642: 	    return $reply{$qualifierrest};
1.48      www      6643:         }
1.236     www      6644:     } elsif ($realm eq 'query') {
                   6645: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6646:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6647: 						[$spacequalifierrest]);
1.620     albertel 6648: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6649:    } elsif ($realm eq 'request') {
1.48      www      6650: # ------------------------------------------------------------- request.browser
                   6651:         if ($space eq 'browser') {
1.430     www      6652: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6653: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6654: 		    return 1;
                   6655: 		} else {
                   6656: 		    return 0;
                   6657: 		}
                   6658: 	    } else {
1.620     albertel 6659: 		return $env{'browser.'.$qualifier};
1.430     www      6660: 	    }
1.57      www      6661: # ------------------------------------------------------------ request.filename
                   6662:         } else {
1.620     albertel 6663:             return $env{'request.'.$spacequalifierrest};
1.29      www      6664:         }
1.28      www      6665:     } elsif ($realm eq 'course') {
1.48      www      6666: # ---------------------------------------------------------- course.description
1.620     albertel 6667:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6668:     } elsif ($realm eq 'resource') {
1.165     www      6669: 
1.620     albertel 6670: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6671: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6672: 	}
1.693     albertel 6673: 
                   6674: 	if ($space eq 'title') {
                   6675: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6676: 	    return &gettitle($symbparm);
                   6677: 	}
                   6678: 	
                   6679: 	if ($space eq 'map') {
                   6680: 	    my ($map) = &decode_symb($symbparm);
                   6681: 	    return &symbread($map);
                   6682: 	}
1.905     albertel 6683: 	if ($space eq 'filename') {
                   6684: 	    if ($symbparm) {
                   6685: 		return &clutter((&decode_symb($symbparm))[2]);
                   6686: 	    }
                   6687: 	    return &hreflocation('',$env{'request.filename'});
                   6688: 	}
1.693     albertel 6689: 
                   6690: 	my ($section, $group, @groups);
1.593     albertel 6691: 	my ($courselevelm,$courselevel);
1.539     albertel 6692: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6693: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6694: 
1.218     albertel 6695: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6696: 
1.60      www      6697: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6698: 	    my $symbp=$symbparm;
1.735     albertel 6699: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6700: 
                   6701: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6702: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6703: 
1.620     albertel 6704: 	    if (($env{'user.name'} eq $uname) &&
                   6705: 		($env{'user.domain'} eq $udom)) {
                   6706: 		$section=$env{'request.course.sec'};
1.733     raeburn  6707:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6708:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6709: 	    } else {
1.539     albertel 6710: 		if (! defined($usection)) {
1.551     albertel 6711: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6712: 		} else {
                   6713: 		    $section = $usection;
                   6714: 		}
1.733     raeburn  6715:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6716: 	    }
                   6717: 
                   6718: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6719: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6720: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6721: 
1.593     albertel 6722: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6723: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6724: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6725: 
1.60      www      6726: # ----------------------------------------------------------- first, check user
1.624     albertel 6727: 
                   6728: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6729: 				       ([$courselevelr,'resource'],
                   6730: 					[$courselevelm,'map'     ],
                   6731: 					[$courselevel, 'course'  ]));
1.931     albertel 6732: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6733: 
1.594     albertel 6734: # ------------------------------------------------ second, check some of course
1.684     raeburn  6735:             my $coursereply;
1.691     raeburn  6736:             if (@groups > 0) {
                   6737:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6738:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6739:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6740:             }
1.96      www      6741: 
1.684     raeburn  6742: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6743: 				  $env{'course.'.$courseid.'.domain'},
                   6744: 				  'course',
                   6745: 				  ([$seclevelr,   'resource'],
                   6746: 				   [$seclevelm,   'map'     ],
                   6747: 				   [$seclevel,    'course'  ],
                   6748: 				   [$courselevelr,'resource']));
                   6749: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6750: 
1.60      www      6751: # ------------------------------------------------------ third, check map parms
1.218     albertel 6752: 	    my %parmhash=();
                   6753: 	    my $thisparm='';
                   6754: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6755: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6756: 		    &GDBM_READER(),0640)) {
1.218     albertel 6757: 		$thisparm=$parmhash{$symbparm};
                   6758: 		untie(%parmhash);
                   6759: 	    }
1.927     albertel 6760: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6761: 	}
1.594     albertel 6762: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6763: 
1.218     albertel 6764: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6765: 	my $filename;
                   6766: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6767: 	if ($symbparm) {
1.409     www      6768: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6769: 	} else {
1.620     albertel 6770: 	    $filename=$env{'request.filename'};
1.282     albertel 6771: 	}
                   6772: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6773: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6774: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6775: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6776: 
1.927     albertel 6777: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6778: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6779: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6780: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6781: 				     $env{'course.'.$courseid.'.domain'},
                   6782: 				     'course',
1.927     albertel 6783: 				     ([$courselevelm,'map'   ],
                   6784: 				      [$courselevel, 'course']));
                   6785: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6786: 	}
1.145     www      6787: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6788: 	unless ($space eq '0') {
1.336     albertel 6789: 	    my @parts=split(/_/,$space);
                   6790: 	    my $id=pop(@parts);
                   6791: 	    my $part=join('_',@parts);
                   6792: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6793: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6794: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6795: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6796: 	}
1.395     albertel 6797: 	if ($recurse) { return undef; }
                   6798: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6799: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6800: # ---------------------------------------------------- Any other user namespace
                   6801:     } elsif ($realm eq 'environment') {
                   6802: # ----------------------------------------------------------------- environment
1.620     albertel 6803: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6804: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6805: 	} else {
1.770     albertel 6806: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6807: 		return '';
                   6808: 	    }
1.219     albertel 6809: 	    my %returnhash=&userenvironment($udom,$uname,
                   6810: 					    $spacequalifierrest);
                   6811: 	    return $returnhash{$spacequalifierrest};
                   6812: 	}
1.28      www      6813:     } elsif ($realm eq 'system') {
1.48      www      6814: # ----------------------------------------------------------------- system.time
                   6815: 	if ($space eq 'time') {
                   6816: 	    return time;
                   6817:         }
1.696     albertel 6818:     } elsif ($realm eq 'server') {
                   6819: # ----------------------------------------------------------------- system.time
                   6820: 	if ($space eq 'name') {
                   6821: 	    return $ENV{'SERVER_NAME'};
                   6822:         }
1.28      www      6823:     }
1.48      www      6824:     return '';
1.61      www      6825: }
                   6826: 
1.927     albertel 6827: sub get_reply {
                   6828:     my ($reply_value) = @_;
1.940     raeburn  6829:     if (ref($reply_value) eq 'ARRAY') {
                   6830:         if (wantarray) {
                   6831: 	    return @$reply_value;
                   6832:         }
                   6833:         return $reply_value->[0];
                   6834:     } else {
                   6835:         return $reply_value;
1.927     albertel 6836:     }
                   6837: }
                   6838: 
1.691     raeburn  6839: sub check_group_parms {
                   6840:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6841:     my @groupitems = ();
                   6842:     my $resultitem;
1.927     albertel 6843:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6844:     foreach my $group (@{$groups}) {
                   6845:         foreach my $level (@levels) {
1.927     albertel 6846:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6847:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6848:         }
                   6849:     }
                   6850:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6851:                             $env{'course.'.$courseid.'.domain'},
                   6852:                                      'course',@groupitems);
                   6853:     return $coursereply;
                   6854: }
                   6855: 
                   6856: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6857:     my ($courseid,@groups) = @_;
                   6858:     @groups = sort(@groups);
1.691     raeburn  6859:     return @groups;
                   6860: }
                   6861: 
1.395     albertel 6862: sub packages_tab_default {
                   6863:     my ($uri,$varname)=@_;
                   6864:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6865: 
                   6866:     my (@extension,@specifics,$do_default);
                   6867:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6868: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6869: 	if ($pack_type eq 'default') {
                   6870: 	    $do_default=1;
                   6871: 	} elsif ($pack_type eq 'extension') {
                   6872: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6873: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6874: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6875: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6876: 	}
                   6877:     }
                   6878:     # first look for a package that matches the requested part id
                   6879:     foreach my $package (@specifics) {
                   6880: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6881: 	next if ($pack_part ne $part);
                   6882: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6883: 	    return $packagetab{"$pack_type&$name&default"};
                   6884: 	}
                   6885:     }
                   6886:     # look for any possible matching non extension_ package
                   6887:     foreach my $package (@specifics) {
                   6888: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6889: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6890: 	    return $packagetab{"$pack_type&$name&default"};
                   6891: 	}
1.585     albertel 6892: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6893: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6894: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6895: 	}
                   6896:     }
1.738     albertel 6897:     # look for any posible extension_ match
                   6898:     foreach my $package (@extension) {
                   6899: 	my ($package,$pack_type)=@{$package};
                   6900: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6901: 	    return $packagetab{"$pack_type&$name&default"};
                   6902: 	}
                   6903: 	if (defined($packagetab{$package."&$name&default"})) {
                   6904: 	    return $packagetab{$package."&$name&default"};
                   6905: 	}
                   6906:     }
                   6907:     # look for a global default setting
                   6908:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6909: 	return $packagetab{"default&$name&default"};
                   6910:     }
1.395     albertel 6911:     return undef;
                   6912: }
                   6913: 
1.334     albertel 6914: sub add_prefix_and_part {
                   6915:     my ($prefix,$part)=@_;
                   6916:     my $keyroot;
                   6917:     if (defined($prefix) && $prefix !~ /^__/) {
                   6918: 	# prefix that has a part already
                   6919: 	$keyroot=$prefix;
                   6920:     } elsif (defined($prefix)) {
                   6921: 	# prefix that is missing a part
                   6922: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6923:     } else {
                   6924: 	# no prefix at all
                   6925: 	if (defined($part)) { $keyroot='_'.$part; }
                   6926:     }
                   6927:     return $keyroot;
                   6928: }
                   6929: 
1.71      www      6930: # ---------------------------------------------------------------- Get metadata
                   6931: 
1.599     albertel 6932: my %metaentry;
1.71      www      6933: sub metadata {
1.176     www      6934:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6935:     $uri=&declutter($uri);
1.288     albertel 6936:     # if it is a non metadata possible uri return quickly
1.529     albertel 6937:     if (($uri eq '') || 
                   6938: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6939: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 6940:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   6941: 	return undef;
                   6942:     }
                   6943:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   6944: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 6945: 	return undef;
1.288     albertel 6946:     }
1.73      www      6947:     my $filename=$uri;
                   6948:     $uri=~s/\.meta$//;
1.172     www      6949: #
                   6950: # Is the metadata already cached?
1.177     www      6951: # Look at timestamp of caching
1.172     www      6952: # Everything is cached by the main uri, libraries are never directly cached
                   6953: #
1.428     albertel 6954:     if (!defined($liburi)) {
1.599     albertel 6955: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6956: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6957:     }
                   6958:     {
1.172     www      6959: #
                   6960: # Is this a recursive call for a library?
                   6961: #
1.599     albertel 6962: #	if (! exists($metacache{$uri})) {
                   6963: #	    $metacache{$uri}={};
                   6964: #	}
1.924     albertel 6965: 	my $cachetime = 60*60;
1.171     www      6966:         if ($liburi) {
                   6967: 	    $liburi=&declutter($liburi);
                   6968:             $filename=$liburi;
1.401     bowersj2 6969:         } else {
1.599     albertel 6970: 	    &devalidate_cache_new('meta',$uri);
                   6971: 	    undef(%metaentry);
1.401     bowersj2 6972: 	}
1.140     www      6973:         my %metathesekeys=();
1.73      www      6974:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6975: 	my $metastring;
1.924     albertel 6976: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 6977: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 6978: 	    $metastring = 
1.929     albertel 6979: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 6980: 					  ('grade_target' => 'meta'));
                   6981: 	    $cachetime = 1; # only want this cached in the child not long term
                   6982: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 6983: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6984: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6985: 	    $metastring=&getfile($file);
1.489     albertel 6986: 	}
1.208     albertel 6987:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6988:         my $token;
1.140     www      6989:         undef %metathesekeys;
1.71      www      6990:         while ($token=$parser->get_token) {
1.339     albertel 6991: 	    if ($token->[0] eq 'S') {
                   6992: 		if (defined($token->[2]->{'package'})) {
1.172     www      6993: #
                   6994: # This is a package - get package info
                   6995: #
1.339     albertel 6996: 		    my $package=$token->[2]->{'package'};
                   6997: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6998: 		    if (defined($token->[2]->{'id'})) { 
                   6999: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7000: 		    }
1.599     albertel 7001: 		    if ($metaentry{':packages'}) {
                   7002: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7003: 		    } else {
1.599     albertel 7004: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7005: 		    }
1.736     albertel 7006: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7007: 			my $part=$keyroot;
                   7008: 			$part=~s/^\_//;
1.736     albertel 7009: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7010: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7011: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7012: 			    # ignore package.tab specified default values
                   7013:                             # here &package_tab_default() will fetch those
                   7014: 			    if ($subp eq 'default') { next; }
1.736     albertel 7015: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7016: 			    my $unikey;
                   7017: 			    if ($pack =~ /_0$/) {
                   7018: 				$unikey='parameter_0_'.$name;
                   7019: 				$part=0;
                   7020: 			    } else {
                   7021: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7022: 			    }
1.339     albertel 7023: 			    if ($subp eq 'display') {
                   7024: 				$value.=' [Part: '.$part.']';
                   7025: 			    }
1.599     albertel 7026: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7027: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7028: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7029: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7030: 			    }
1.599     albertel 7031: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7032: 				$metaentry{':'.$unikey}=
                   7033: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7034: 			    }
1.339     albertel 7035: 			}
                   7036: 		    }
                   7037: 		} else {
1.172     www      7038: #
                   7039: # This is not a package - some other kind of start tag
1.339     albertel 7040: #
                   7041: 		    my $entry=$token->[1];
                   7042: 		    my $unikey;
                   7043: 		    if ($entry eq 'import') {
                   7044: 			$unikey='';
                   7045: 		    } else {
                   7046: 			$unikey=$entry;
                   7047: 		    }
                   7048: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7049: 
                   7050: 		    if (defined($token->[2]->{'id'})) { 
                   7051: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7052: 		    }
1.175     www      7053: 
1.339     albertel 7054: 		    if ($entry eq 'import') {
1.175     www      7055: #
                   7056: # Importing a library here
1.339     albertel 7057: #
                   7058: 			if ($depthcount<20) {
                   7059: 			    my $location=$parser->get_text('/import');
                   7060: 			    my $dir=$filename;
                   7061: 			    $dir=~s|[^/]*$||;
                   7062: 			    $location=&filelocation($dir,$location);
1.736     albertel 7063: 			    my $metadata = 
                   7064: 				&metadata($uri,'keys', $location,$unikey,
                   7065: 					  $depthcount+1);
                   7066: 			    foreach my $meta (split(',',$metadata)) {
                   7067: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7068: 				$metathesekeys{$meta}=1;
1.339     albertel 7069: 			    }
                   7070: 			}
                   7071: 		    } else { 
                   7072: 			
                   7073: 			if (defined($token->[2]->{'name'})) { 
                   7074: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7075: 			}
                   7076: 			$metathesekeys{$unikey}=1;
1.736     albertel 7077: 			foreach my $param (@{$token->[3]}) {
                   7078: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7079: 				$token->[2]->{$param};
1.339     albertel 7080: 			}
                   7081: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7082: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7083: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7084: 		 # only ws inside the tag, and not in default, so use default
                   7085: 		 # as value
1.599     albertel 7086: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7087: 			} elsif ( $internaltext =~ /\S/ ) {
                   7088: 		  # something interesting inside the tag
                   7089: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7090: 			} else {
1.908     albertel 7091: 		  # no interesting values, don't set a default
1.339     albertel 7092: 			}
1.172     www      7093: # end of not-a-package not-a-library import
1.339     albertel 7094: 		    }
1.172     www      7095: # end of not-a-package start tag
1.339     albertel 7096: 		}
1.172     www      7097: # the next is the end of "start tag"
1.339     albertel 7098: 	    }
                   7099: 	}
1.483     albertel 7100: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7101: 	$extension = lc($extension);
                   7102: 	if ($extension eq 'htm') { $extension='html'; }
                   7103: 
1.737     albertel 7104: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7105: 	    #no specific packages #how's our extension
                   7106: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7107: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7108: 					 \%metathesekeys);
                   7109: 	}
1.883     albertel 7110: 
                   7111: 	if (!exists($metaentry{':packages'})
                   7112: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7113: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7114: 		#no specific packages well let's get default then
                   7115: 		if ($key!~/^default&/) { next; }
1.488     albertel 7116: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7117: 					     \%metathesekeys);
                   7118: 	    }
                   7119: 	}
1.338     www      7120: # are there custom rights to evaluate
1.599     albertel 7121: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7122: 
1.338     www      7123:     #
                   7124:     # Importing a rights file here
1.339     albertel 7125:     #
                   7126: 	    unless ($depthcount) {
1.599     albertel 7127: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7128: 		my $dir=$filename;
                   7129: 		$dir=~s|[^/]*$||;
                   7130: 		$location=&filelocation($dir,$location);
1.736     albertel 7131: 		my $rights_metadata =
                   7132: 		    &metadata($uri,'keys',$location,'_rights',
                   7133: 			      $depthcount+1);
                   7134: 		foreach my $rights (split(',',$rights_metadata)) {
                   7135: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7136: 		    $metathesekeys{$rights}=1;
1.339     albertel 7137: 		}
                   7138: 	    }
                   7139: 	}
1.737     albertel 7140: 	# uniqifiy package listing
                   7141: 	my %seen;
                   7142: 	my @uniq_packages =
                   7143: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7144: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7145: 
                   7146: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7147: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7148: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7149: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7150: # this is the end of "was not already recently cached
1.71      www      7151:     }
1.599     albertel 7152:     return $metaentry{':'.$what};
1.261     albertel 7153: }
                   7154: 
1.488     albertel 7155: sub metadata_create_package_def {
1.483     albertel 7156:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7157:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7158:     if ($subp eq 'default') { next; }
                   7159:     
1.599     albertel 7160:     if (defined($metaentry{':packages'})) {
                   7161: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7162:     } else {
1.599     albertel 7163: 	$metaentry{':packages'}=$package;
1.483     albertel 7164:     }
                   7165:     my $value=$packagetab{$key};
                   7166:     my $unikey;
                   7167:     $unikey='parameter_0_'.$name;
1.599     albertel 7168:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7169:     $$metathesekeys{$unikey}=1;
1.599     albertel 7170:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7171: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7172:     }
1.599     albertel 7173:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7174: 	$metaentry{':'.$unikey}=
                   7175: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7176:     }
                   7177: }
                   7178: 
1.261     albertel 7179: sub metadata_generate_part0 {
                   7180:     my ($metadata,$metacache,$uri) = @_;
                   7181:     my %allnames;
1.737     albertel 7182:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7183: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7184: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7185: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7186: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7187: 	    $allnames{$name}=$part;
                   7188: 	  }
                   7189: 	}
                   7190:     }
                   7191:     foreach my $name (keys(%allnames)) {
                   7192:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7193:       my $key=":parameter_0_$name";
1.261     albertel 7194:       $$metacache{"$key.part"}='0';
                   7195:       $$metacache{"$key.name"}=$name;
1.428     albertel 7196:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7197: 					   $allnames{$name}.'_'.$name.
                   7198: 					   '.type'};
1.428     albertel 7199:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7200: 			     '.display'};
1.644     www      7201:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7202:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7203:       $$metacache{"$key.display"}=$olddis;
                   7204:     }
1.71      www      7205: }
                   7206: 
1.764     albertel 7207: # ------------------------------------------------------ Devalidate title cache
                   7208: 
                   7209: sub devalidate_title_cache {
                   7210:     my ($url)=@_;
                   7211:     if (!$env{'request.course.id'}) { return; }
                   7212:     my $symb=&symbread($url);
                   7213:     if (!$symb) { return; }
                   7214:     my $key=$env{'request.course.id'}."\0".$symb;
                   7215:     &devalidate_cache_new('title',$key);
                   7216: }
                   7217: 
1.301     www      7218: # ------------------------------------------------- Get the title of a resource
                   7219: 
                   7220: sub gettitle {
                   7221:     my $urlsymb=shift;
                   7222:     my $symb=&symbread($urlsymb);
1.534     albertel 7223:     if ($symb) {
1.620     albertel 7224: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7225: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7226: 	if (defined($cached)) { 
                   7227: 	    return $result;
                   7228: 	}
1.534     albertel 7229: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7230: 	my $title='';
1.907     albertel 7231: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7232: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7233: 	} else {
                   7234: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7235: 		    &GDBM_READER(),0640)) {
                   7236: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7237: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7238: 		untie(%bighash);
                   7239: 	    }
1.534     albertel 7240: 	}
                   7241: 	$title=~s/\&colon\;/\:/gs;
                   7242: 	if ($title) {
1.599     albertel 7243: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7244: 	}
                   7245: 	$urlsymb=$url;
                   7246:     }
                   7247:     my $title=&metadata($urlsymb,'title');
                   7248:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7249:     return $title;
1.301     www      7250: }
1.613     albertel 7251: 
1.614     albertel 7252: sub get_slot {
                   7253:     my ($which,$cnum,$cdom)=@_;
                   7254:     if (!$cnum || !$cdom) {
1.790     albertel 7255: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7256: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7257: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7258:     }
1.703     albertel 7259:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7260:     my %slotinfo;
                   7261:     if (exists($remembered{$key})) {
                   7262: 	$slotinfo{$which} = $remembered{$key};
                   7263:     } else {
                   7264: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7265: 	&Apache::lonhomework::showhash(%slotinfo);
                   7266: 	my ($tmp)=keys(%slotinfo);
                   7267: 	if ($tmp=~/^error:/) { return (); }
                   7268: 	$remembered{$key} = $slotinfo{$which};
                   7269:     }
1.616     albertel 7270:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7271: 	return %{$slotinfo{$which}};
                   7272:     }
                   7273:     return $slotinfo{$which};
1.614     albertel 7274: }
1.31      www      7275: # ------------------------------------------------- Update symbolic store links
                   7276: 
                   7277: sub symblist {
                   7278:     my ($mapname,%newhash)=@_;
1.438     www      7279:     $mapname=&deversion(&declutter($mapname));
1.31      www      7280:     my %hash;
1.620     albertel 7281:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7282:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7283:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7284: 	    foreach my $url (keys %newhash) {
                   7285: 		next if ($url eq 'last_known'
                   7286: 			 && $env{'form.no_update_last_known'});
                   7287: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7288: 						    $newhash{$url}->[1],
                   7289: 						    $newhash{$url}->[0]);
1.191     harris41 7290:             }
1.31      www      7291:             if (untie(%hash)) {
                   7292: 		return 'ok';
                   7293:             }
                   7294:         }
                   7295:     }
                   7296:     return 'error';
1.212     www      7297: }
                   7298: 
                   7299: # --------------------------------------------------------------- Verify a symb
                   7300: 
                   7301: sub symbverify {
1.510     www      7302:     my ($symb,$thisurl)=@_;
                   7303:     my $thisfn=$thisurl;
1.439     www      7304:     $thisfn=&declutter($thisfn);
1.215     www      7305: # direct jump to resource in page or to a sequence - will construct own symbs
                   7306:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7307: # check URL part
1.409     www      7308:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7309: 
1.431     www      7310:     unless ($url eq $thisfn) { return 0; }
1.213     www      7311: 
1.216     www      7312:     $symb=&symbclean($symb);
1.510     www      7313:     $thisurl=&deversion($thisurl);
1.439     www      7314:     $thisfn=&deversion($thisfn);
1.213     www      7315: 
                   7316:     my %bighash;
                   7317:     my $okay=0;
1.431     www      7318: 
1.620     albertel 7319:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7320:                             &GDBM_READER(),0640)) {
1.510     www      7321:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7322:         unless ($ids) { 
1.510     www      7323:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7324:         }
                   7325:         if ($ids) {
                   7326: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7327: 	    foreach my $id (split(/\,/,$ids)) {
                   7328: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7329:                if (
                   7330:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7331:    eq $symb) { 
1.620     albertel 7332: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7333: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7334: 		       $okay=1; 
                   7335: 		   }
                   7336: 	       }
1.216     www      7337: 	   }
                   7338:         }
1.213     www      7339: 	untie(%bighash);
                   7340:     }
                   7341:     return $okay;
1.31      www      7342: }
                   7343: 
1.210     www      7344: # --------------------------------------------------------------- Clean-up symb
                   7345: 
                   7346: sub symbclean {
                   7347:     my $symb=shift;
1.568     albertel 7348:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7349: # remove version from map
                   7350:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7351: 
1.210     www      7352: # remove version from URL
                   7353:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7354: 
1.507     www      7355: # remove wrapper
                   7356: 
1.510     www      7357:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7358:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7359:     return $symb;
1.409     www      7360: }
                   7361: 
                   7362: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7363: 
                   7364: sub encode_symb {
                   7365:     my ($map,$resid,$url)=@_;
                   7366:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7367: }
1.409     www      7368: 
                   7369: sub decode_symb {
1.568     albertel 7370:     my $symb=shift;
                   7371:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7372:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7373:     return (&fixversion($map),$resid,&fixversion($url));
                   7374: }
                   7375: 
                   7376: sub fixversion {
                   7377:     my $fn=shift;
1.609     banghart 7378:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7379:     my %bighash;
                   7380:     my $uri=&clutter($fn);
1.620     albertel 7381:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7382: # is this cached?
1.599     albertel 7383:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7384:     if (defined($cached)) { return $result; }
                   7385: # unfortunately not cached, or expired
1.620     albertel 7386:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7387: 	    &GDBM_READER(),0640)) {
                   7388:  	if ($bighash{'version_'.$uri}) {
                   7389:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7390:  	    unless (($version eq 'mostrecent') || 
                   7391: 		    ($version==&getversion($uri))) {
1.440     www      7392:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7393:  	    }
                   7394:  	}
                   7395:  	untie %bighash;
1.413     www      7396:     }
1.599     albertel 7397:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7398: }
                   7399: 
                   7400: sub deversion {
                   7401:     my $url=shift;
                   7402:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7403:     return $url;
1.210     www      7404: }
                   7405: 
1.31      www      7406: # ------------------------------------------------------ Return symb list entry
                   7407: 
                   7408: sub symbread {
1.249     www      7409:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7410:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7411:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7412: # no filename provided? try from environment
1.44      www      7413:     unless ($thisfn) {
1.620     albertel 7414:         if ($env{'request.symb'}) {
                   7415: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7416: 	}
1.620     albertel 7417: 	$thisfn=$env{'request.filename'};
1.44      www      7418:     }
1.569     albertel 7419:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7420: # is that filename actually a symb? Verify, clean, and return
                   7421:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7422: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7423: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7424: 	}
1.242     www      7425:     }
1.44      www      7426:     $thisfn=declutter($thisfn);
1.31      www      7427:     my %hash;
1.37      www      7428:     my %bighash;
                   7429:     my $syval='';
1.620     albertel 7430:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7431:         my $targetfn = $thisfn;
1.609     banghart 7432:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7433:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7434:         }
1.687     albertel 7435: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7436: 	    $targetfn=$1;
                   7437: 	}
1.620     albertel 7438:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7439:                       &GDBM_READER(),0640)) {
1.481     raeburn  7440: 	    $syval=$hash{$targetfn};
1.37      www      7441:             untie(%hash);
                   7442:         }
                   7443: # ---------------------------------------------------------- There was an entry
                   7444:         if ($syval) {
1.601     albertel 7445: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7446: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7447: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7448: 		    #return $env{$cache_str}='';
1.601     albertel 7449: 		#}    
                   7450: 		#$syval.=$1;
                   7451: 	    #}
1.37      www      7452:         } else {
                   7453: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7454:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7455:                             &GDBM_READER(),0640)) {
1.37      www      7456: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7457:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7458:               unless ($ids) { 
                   7459:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7460:               }
                   7461:               unless ($ids) {
                   7462: # alias?
                   7463: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7464:               }
1.37      www      7465:               if ($ids) {
                   7466: # ------------------------------------------------------------------- Has ID(s)
                   7467:                  my @possibilities=split(/\,/,$ids);
1.39      www      7468:                  if ($#possibilities==0) {
                   7469: # ----------------------------------------------- There is only one possibility
1.37      www      7470: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7471: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7472: 						    $resid,$thisfn);
1.249     www      7473:                  } elsif (!$donotrecurse) {
1.39      www      7474: # ------------------------------------------ There is more than one possibility
                   7475:                      my $realpossible=0;
1.800     albertel 7476:                      foreach my $id (@possibilities) {
                   7477: 			 my $file=$bighash{'src_'.$id};
1.39      www      7478:                          if (&allowed('bre',$file)) {
1.800     albertel 7479:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7480:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7481: 				$realpossible++;
1.626     albertel 7482:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7483: 						    $resid,$thisfn);
1.39      www      7484:                             }
                   7485: 			 }
1.191     harris41 7486:                      }
1.39      www      7487: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7488:                  } else {
                   7489:                      $syval='';
1.37      www      7490:                  }
                   7491: 	      }
                   7492:               untie(%bighash)
1.481     raeburn  7493:            }
1.31      www      7494:         }
1.62      www      7495:         if ($syval) {
1.620     albertel 7496: 	    return $env{$cache_str}=$syval;
1.62      www      7497:         }
1.31      www      7498:     }
1.949     raeburn  7499:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7500:     return $env{$cache_str}='';
1.31      www      7501: }
                   7502: 
                   7503: # ---------------------------------------------------------- Return random seed
                   7504: 
1.32      www      7505: sub numval {
                   7506:     my $txt=shift;
                   7507:     $txt=~tr/A-J/0-9/;
                   7508:     $txt=~tr/a-j/0-9/;
                   7509:     $txt=~tr/K-T/0-9/;
                   7510:     $txt=~tr/k-t/0-9/;
                   7511:     $txt=~tr/U-Z/0-5/;
                   7512:     $txt=~tr/u-z/0-5/;
                   7513:     $txt=~s/\D//g;
1.564     albertel 7514:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7515:     return int($txt);
1.368     albertel 7516: }
                   7517: 
1.484     albertel 7518: sub numval2 {
                   7519:     my $txt=shift;
                   7520:     $txt=~tr/A-J/0-9/;
                   7521:     $txt=~tr/a-j/0-9/;
                   7522:     $txt=~tr/K-T/0-9/;
                   7523:     $txt=~tr/k-t/0-9/;
                   7524:     $txt=~tr/U-Z/0-5/;
                   7525:     $txt=~tr/u-z/0-5/;
                   7526:     $txt=~s/\D//g;
                   7527:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7528:     my $total;
                   7529:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7530:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7531:     return int($total);
                   7532: }
                   7533: 
1.575     albertel 7534: sub numval3 {
                   7535:     use integer;
                   7536:     my $txt=shift;
                   7537:     $txt=~tr/A-J/0-9/;
                   7538:     $txt=~tr/a-j/0-9/;
                   7539:     $txt=~tr/K-T/0-9/;
                   7540:     $txt=~tr/k-t/0-9/;
                   7541:     $txt=~tr/U-Z/0-5/;
                   7542:     $txt=~tr/u-z/0-5/;
                   7543:     $txt=~s/\D//g;
                   7544:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7545:     my $total;
                   7546:     foreach my $val (@txts) { $total+=$val; }
                   7547:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7548:     return $total;
                   7549: }
                   7550: 
1.675     albertel 7551: sub digest {
                   7552:     my ($data)=@_;
                   7553:     my $digest=&Digest::MD5::md5($data);
                   7554:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7555:     my ($e,$f);
                   7556:     {
                   7557:         use integer;
                   7558:         $e=($a+$b);
                   7559:         $f=($c+$d);
                   7560:         if ($_64bit) {
                   7561:             $e=(($e<<32)>>32);
                   7562:             $f=(($f<<32)>>32);
                   7563:         }
                   7564:     }
                   7565:     if (wantarray) {
                   7566: 	return ($e,$f);
                   7567:     } else {
                   7568: 	my $g;
                   7569: 	{
                   7570: 	    use integer;
                   7571: 	    $g=($e+$f);
                   7572: 	    if ($_64bit) {
                   7573: 		$g=(($g<<32)>>32);
                   7574: 	    }
                   7575: 	}
                   7576: 	return $g;
                   7577:     }
                   7578: }
                   7579: 
1.368     albertel 7580: sub latest_rnd_algorithm_id {
1.675     albertel 7581:     return '64bit5';
1.366     albertel 7582: }
1.32      www      7583: 
1.503     albertel 7584: sub get_rand_alg {
                   7585:     my ($courseid)=@_;
1.790     albertel 7586:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7587:     if ($courseid) {
1.620     albertel 7588: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7589:     }
                   7590:     return &latest_rnd_algorithm_id();
                   7591: }
                   7592: 
1.562     albertel 7593: sub validCODE {
                   7594:     my ($CODE)=@_;
                   7595:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7596:     return 0;
                   7597: }
                   7598: 
1.491     albertel 7599: sub getCODE {
1.620     albertel 7600:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7601:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7602: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7603: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7604: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7605:     }
                   7606:     return undef;
                   7607: }
                   7608: 
1.31      www      7609: sub rndseed {
1.155     albertel 7610:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7611:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7612:     if (!defined($symb)) {
1.366     albertel 7613: 	unless ($symb=$wsymb) { return time; }
                   7614:     }
                   7615:     if (!$courseid) { $courseid=$wcourseid; }
                   7616:     if (!$domain) { $domain=$wdomain; }
                   7617:     if (!$username) { $username=$wusername }
1.503     albertel 7618:     my $which=&get_rand_alg();
1.803     albertel 7619: 
1.491     albertel 7620:     if (defined(&getCODE())) {
1.675     albertel 7621: 	if ($which eq '64bit5') {
                   7622: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7623: 	} elsif ($which eq '64bit4') {
1.575     albertel 7624: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7625: 	} else {
                   7626: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7627: 	}
1.675     albertel 7628:     } elsif ($which eq '64bit5') {
                   7629: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7630:     } elsif ($which eq '64bit4') {
                   7631: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7632:     } elsif ($which eq '64bit3') {
                   7633: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7634:     } elsif ($which eq '64bit2') {
                   7635: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7636:     } elsif ($which eq '64bit') {
                   7637: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7638:     }
                   7639:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7640: }
                   7641: 
                   7642: sub rndseed_32bit {
                   7643:     my ($symb,$courseid,$domain,$username)=@_;
                   7644:     {
                   7645: 	use integer;
                   7646: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7647: 	my $symbseed=numval($symb) << 22;
                   7648: 	my $namechck=unpack("%32C*",$username) << 17;
                   7649: 	my $nameseed=numval($username) << 12;
                   7650: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7651: 	my $courseseed=unpack("%32C*",$courseid);
                   7652: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7653: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7654: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7655: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7656: 	return $num;
                   7657:     }
                   7658: }
                   7659: 
                   7660: sub rndseed_64bit {
                   7661:     my ($symb,$courseid,$domain,$username)=@_;
                   7662:     {
                   7663: 	use integer;
                   7664: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7665: 	my $symbseed=numval($symb) << 10;
                   7666: 	my $namechck=unpack("%32S*",$username);
                   7667: 	
                   7668: 	my $nameseed=numval($username) << 21;
                   7669: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7670: 	my $courseseed=unpack("%32S*",$courseid);
                   7671: 	
                   7672: 	my $num1=$symbchck+$symbseed+$namechck;
                   7673: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7674: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7675: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7676: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7677: 	return "$num1,$num2";
1.155     albertel 7678:     }
1.366     albertel 7679: }
                   7680: 
1.443     albertel 7681: sub rndseed_64bit2 {
                   7682:     my ($symb,$courseid,$domain,$username)=@_;
                   7683:     {
                   7684: 	use integer;
                   7685: 	# strings need to be an even # of cahracters long, it it is odd the
                   7686:         # last characters gets thrown away
                   7687: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7688: 	my $symbseed=numval($symb) << 10;
                   7689: 	my $namechck=unpack("%32S*",$username.' ');
                   7690: 	
                   7691: 	my $nameseed=numval($username) << 21;
1.501     albertel 7692: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7693: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7694: 	
                   7695: 	my $num1=$symbchck+$symbseed+$namechck;
                   7696: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7697: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7698: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7699: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7700: 	return "$num1,$num2";
                   7701:     }
                   7702: }
                   7703: 
                   7704: sub rndseed_64bit3 {
                   7705:     my ($symb,$courseid,$domain,$username)=@_;
                   7706:     {
                   7707: 	use integer;
                   7708: 	# strings need to be an even # of cahracters long, it it is odd the
                   7709:         # last characters gets thrown away
                   7710: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7711: 	my $symbseed=numval2($symb) << 10;
                   7712: 	my $namechck=unpack("%32S*",$username.' ');
                   7713: 	
                   7714: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7715: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7716: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7717: 	
                   7718: 	my $num1=$symbchck+$symbseed+$namechck;
                   7719: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7720: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7721: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7722: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7723: 	
1.503     albertel 7724: 	return "$num1:$num2";
1.443     albertel 7725:     }
                   7726: }
                   7727: 
1.575     albertel 7728: sub rndseed_64bit4 {
                   7729:     my ($symb,$courseid,$domain,$username)=@_;
                   7730:     {
                   7731: 	use integer;
                   7732: 	# strings need to be an even # of cahracters long, it it is odd the
                   7733:         # last characters gets thrown away
                   7734: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7735: 	my $symbseed=numval3($symb) << 10;
                   7736: 	my $namechck=unpack("%32S*",$username.' ');
                   7737: 	
                   7738: 	my $nameseed=numval3($username) << 21;
                   7739: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7740: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7741: 	
                   7742: 	my $num1=$symbchck+$symbseed+$namechck;
                   7743: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7744: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7745: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7746: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7747: 	
                   7748: 	return "$num1:$num2";
                   7749:     }
                   7750: }
                   7751: 
1.675     albertel 7752: sub rndseed_64bit5 {
                   7753:     my ($symb,$courseid,$domain,$username)=@_;
                   7754:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7755:     return "$num1:$num2";
                   7756: }
                   7757: 
1.366     albertel 7758: sub rndseed_CODE_64bit {
                   7759:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7760:     {
1.366     albertel 7761: 	use integer;
1.443     albertel 7762: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7763: 	my $symbseed=numval2($symb);
1.491     albertel 7764: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7765: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7766: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7767: 	my $num1=$symbseed+$CODEchck;
                   7768: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7769: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7770: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7771: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7772: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7773: 	return "$num1:$num2";
1.366     albertel 7774:     }
                   7775: }
                   7776: 
1.575     albertel 7777: sub rndseed_CODE_64bit4 {
                   7778:     my ($symb,$courseid,$domain,$username)=@_;
                   7779:     {
                   7780: 	use integer;
                   7781: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7782: 	my $symbseed=numval3($symb);
                   7783: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7784: 	my $CODEseed=numval3(&getCODE());
                   7785: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7786: 	my $num1=$symbseed+$CODEchck;
                   7787: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7788: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7789: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7790: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7791: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7792: 	return "$num1:$num2";
                   7793:     }
                   7794: }
                   7795: 
1.675     albertel 7796: sub rndseed_CODE_64bit5 {
                   7797:     my ($symb,$courseid,$domain,$username)=@_;
                   7798:     my $code = &getCODE();
                   7799:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7800:     return "$num1:$num2";
                   7801: }
                   7802: 
1.366     albertel 7803: sub setup_random_from_rndseed {
                   7804:     my ($rndseed)=@_;
1.503     albertel 7805:     if ($rndseed =~/([,:])/) {
                   7806: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7807: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7808:     } else {
                   7809: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7810:     }
1.36      albertel 7811: }
                   7812: 
1.474     albertel 7813: sub latest_receipt_algorithm_id {
1.835     albertel 7814:     return 'receipt3';
1.474     albertel 7815: }
                   7816: 
1.480     www      7817: sub recunique {
                   7818:     my $fucourseid=shift;
                   7819:     my $unique;
1.835     albertel 7820:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7821: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7822: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7823:     } else {
                   7824: 	$unique=$perlvar{'lonReceipt'};
                   7825:     }
                   7826:     return unpack("%32C*",$unique);
                   7827: }
                   7828: 
                   7829: sub recprefix {
                   7830:     my $fucourseid=shift;
                   7831:     my $prefix;
1.835     albertel 7832:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7833: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7834: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7835:     } else {
                   7836: 	$prefix=$perlvar{'lonHostID'};
                   7837:     }
                   7838:     return unpack("%32C*",$prefix);
                   7839: }
                   7840: 
1.76      www      7841: sub ireceipt {
1.474     albertel 7842:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7843: 
                   7844:     my $return =&recprefix($fucourseid).'-';
                   7845: 
                   7846:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7847: 	$env{'request.state'} eq 'construct') {
                   7848: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7849: 	return $return;
                   7850:     }
                   7851: 
1.76      www      7852:     my $cuname=unpack("%32C*",$funame);
                   7853:     my $cudom=unpack("%32C*",$fudom);
                   7854:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7855:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7856:     my $cunique=&recunique($fucourseid);
1.474     albertel 7857:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7858:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7859: 
1.790     albertel 7860: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7861: 			       
                   7862: 	$return.= ($cunique%$cuname+
                   7863: 		   $cunique%$cudom+
                   7864: 		   $cusymb%$cuname+
                   7865: 		   $cusymb%$cudom+
                   7866: 		   $cucourseid%$cuname+
                   7867: 		   $cucourseid%$cudom+
                   7868: 		   $cpart%$cuname+
                   7869: 		   $cpart%$cudom);
                   7870:     } else {
                   7871: 	$return.= ($cunique%$cuname+
                   7872: 		   $cunique%$cudom+
                   7873: 		   $cusymb%$cuname+
                   7874: 		   $cusymb%$cudom+
                   7875: 		   $cucourseid%$cuname+
                   7876: 		   $cucourseid%$cudom);
                   7877:     }
                   7878:     return $return;
1.76      www      7879: }
                   7880: 
                   7881: sub receipt {
1.474     albertel 7882:     my ($part)=@_;
1.790     albertel 7883:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7884:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7885: }
1.260     ng       7886: 
1.790     albertel 7887: sub whichuser {
                   7888:     my ($passedsymb)=@_;
                   7889:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7890:     if (defined($env{'form.grade_symb'})) {
                   7891: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7892: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7893: 	if (!$allowed &&
                   7894: 	    exists($env{'request.course.sec'}) &&
                   7895: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7896: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7897: 			      '/'.$env{'request.course.sec'});
                   7898: 	}
                   7899: 	if ($allowed) {
                   7900: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7901: 	    $courseid=$tmp_courseid;
                   7902: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7903: 	    ($name)=&get_env_multiple('form.grade_username');
                   7904: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7905: 	}
                   7906:     }
                   7907:     if (!$passedsymb) {
                   7908: 	$symb=&symbread();
                   7909:     } else {
                   7910: 	$symb=$passedsymb;
                   7911:     }
                   7912:     $courseid=$env{'request.course.id'};
                   7913:     $domain=$env{'user.domain'};
                   7914:     $name=$env{'user.name'};
                   7915:     if ($name eq 'public' && $domain eq 'public') {
                   7916: 	if (!defined($env{'form.username'})) {
                   7917: 	    $env{'form.username'}.=time.rand(10000000);
                   7918: 	}
                   7919: 	$name.=$env{'form.username'};
                   7920:     }
                   7921:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7922: 
                   7923: }
                   7924: 
1.36      albertel 7925: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7926: # returns either the contents of the file or 
                   7927: # -1 if the file doesn't exist
1.481     raeburn  7928: #
                   7929: # if the target is a file that was uploaded via DOCS, 
                   7930: # a check will be made to see if a current copy exists on the local server,
                   7931: # if it does this will be served, otherwise a copy will be retrieved from
                   7932: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7933: # the local server.   
1.472     albertel 7934: 
1.36      albertel 7935: sub getfile {
1.538     albertel 7936:     my ($file) = @_;
1.609     banghart 7937:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7938:     &repcopy($file);
                   7939:     return &readfile($file);
                   7940: }
                   7941: 
                   7942: sub repcopy_userfile {
                   7943:     my ($file)=@_;
1.609     banghart 7944:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7945:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7946:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7947: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7948:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7949:     if (-e "$file") {
1.828     www      7950: # we already have a local copy, check it out
1.538     albertel 7951: 	my @fileinfo = stat($file);
1.828     www      7952: 	my $rtncode;
                   7953: 	my $info;
1.538     albertel 7954: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7955: 	if ($lwpresp ne 'ok') {
1.828     www      7956: # there is no such file anymore, even though we had a local copy
1.482     albertel 7957: 	    if ($rtncode eq '404') {
1.538     albertel 7958: 		unlink($file);
1.482     albertel 7959: 	    }
                   7960: 	    return -1;
                   7961: 	}
                   7962: 	if ($info < $fileinfo[9]) {
1.828     www      7963: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7964: 	    return 'ok';
1.828     www      7965: 	} else {
                   7966: # the file is outdated, get rid of it
                   7967: 	    unlink($file);
1.482     albertel 7968: 	}
1.828     www      7969:     }
                   7970: # one way or the other, at this point, we don't have the file
                   7971: # construct the correct path for the file
                   7972:     my @parts = ($cdom,$cnum); 
                   7973:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7974: 	push @parts, split(/\//,$1);
                   7975:     }
                   7976:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7977:     foreach my $part (@parts) {
                   7978: 	$path .= '/'.$part;
                   7979: 	if (!-e $path) {
                   7980: 	    mkdir($path,0770);
1.482     albertel 7981: 	}
                   7982:     }
1.828     www      7983: # now the path exists for sure
                   7984: # get a user agent
                   7985:     my $ua=new LWP::UserAgent;
                   7986:     my $transferfile=$file.'.in.transfer';
                   7987: # FIXME: this should flock
                   7988:     if (-e $transferfile) { return 'ok'; }
                   7989:     my $request;
                   7990:     $uri=~s/^\///;
1.838     albertel 7991:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7992:     my $response=$ua->request($request,$transferfile);
                   7993: # did it work?
                   7994:     if ($response->is_error()) {
                   7995: 	unlink($transferfile);
                   7996: 	&logthis("Userfile repcopy failed for $uri");
                   7997: 	return -1;
                   7998:     }
                   7999: # worked, rename the transfer file
                   8000:     rename($transferfile,$file);
1.607     raeburn  8001:     return 'ok';
1.481     raeburn  8002: }
                   8003: 
1.517     albertel 8004: sub tokenwrapper {
                   8005:     my $uri=shift;
1.552     albertel 8006:     $uri=~s|^http\://([^/]+)||;
                   8007:     $uri=~s|^/||;
1.620     albertel 8008:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8009:     my $token=$1;
1.552     albertel 8010:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8011:     if ($udom && $uname && $file) {
                   8012: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8013:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838     albertel 8014:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 8015:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8016:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8017:     } else {
                   8018:         return '/adm/notfound.html';
                   8019:     }
                   8020: }
                   8021: 
1.828     www      8022: # call with reqtype HEAD: get last modification time
                   8023: # call with reqtype GET: get the file contents
                   8024: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8025: #
1.481     raeburn  8026: sub getuploaded {
                   8027:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8028:     $uri=~s/^\///;
1.838     albertel 8029:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8030:     my $ua=new LWP::UserAgent;
                   8031:     my $request=new HTTP::Request($reqtype,$uri);
                   8032:     my $response=$ua->request($request);
                   8033:     $$rtncode = $response->code;
1.482     albertel 8034:     if (! $response->is_success()) {
                   8035: 	return 'failed';
                   8036:     }      
                   8037:     if ($reqtype eq 'HEAD') {
1.486     www      8038: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8039:     } elsif ($reqtype eq 'GET') {
                   8040: 	$$info = $response->content;
1.472     albertel 8041:     }
1.482     albertel 8042:     return 'ok';
1.36      albertel 8043: }
                   8044: 
1.481     raeburn  8045: sub readfile {
                   8046:     my $file = shift;
                   8047:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8048:     my $fh;
                   8049:     open($fh,"<$file");
                   8050:     my $a='';
1.800     albertel 8051:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8052:     return $a;
                   8053: }
                   8054: 
1.36      albertel 8055: sub filelocation {
1.590     banghart 8056:     my ($dir,$file) = @_;
                   8057:     my $location;
                   8058:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8059: 
                   8060:     if ($file =~ m-^/adm/-) {
                   8061: 	$file=~s-^/adm/wrapper/-/-;
                   8062: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8063:     }
1.882     albertel 8064: 
1.590     banghart 8065:     if ($file=~m:^/~:) { # is a contruction space reference
                   8066:         $location = $file;
                   8067:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8068:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8069: 	# is a correct contruction space reference
                   8070:         $location = $file;
1.609     banghart 8071:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8072:         my ($udom,$uname,$filename)=
1.811     albertel 8073:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8074:         my $home=&homeserver($uname,$udom);
                   8075:         my $is_me=0;
                   8076:         my @ids=&current_machine_ids();
                   8077:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8078:         if ($is_me) {
1.740     www      8079:   	    $location=&propath($udom,$uname).
1.590     banghart 8080:   	      '/userfiles/'.$filename;
                   8081:         } else {
                   8082:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8083:   	      $udom.'/'.$uname.'/'.$filename;
                   8084:         }
1.882     albertel 8085:     } elsif ($file =~ m-^/adm/-) {
                   8086: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8087:     } else {
                   8088:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8089:         $file=~s:^/res/:/:;
                   8090:         if ( !( $file =~ m:^/:) ) {
                   8091:             $location = $dir. '/'.$file;
                   8092:         } else {
                   8093:             $location = '/home/httpd/html/res'.$file;
                   8094:         }
1.59      albertel 8095:     }
1.590     banghart 8096:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8097:     while ($location=~m{/\.\./}) {
                   8098: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8099: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8100: 	} else {
                   8101: 	    $location=~ s{/\.\./}{/}g;
                   8102: 	}
                   8103:     } #remove dir/..
1.590     banghart 8104:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8105:     return $location;
1.46      www      8106: }
1.36      albertel 8107: 
1.46      www      8108: sub hreflocation {
                   8109:     my ($dir,$file)=@_;
1.460     albertel 8110:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8111: 	$file=filelocation($dir,$file);
1.700     albertel 8112:     } elsif ($file=~m-^/adm/-) {
                   8113: 	$file=~s-^/adm/wrapper/-/-;
                   8114: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8115:     }
                   8116:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8117: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8118:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8119: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8120:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8121: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8122: 	    -/uploaded/$1/$2/-x;
1.46      www      8123:     }
1.913     albertel 8124:     if ($file=~ m{^/userfiles/}) {
                   8125: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8126:     }
1.462     albertel 8127:     return $file;
1.465     albertel 8128: }
                   8129: 
                   8130: sub current_machine_domains {
1.853     albertel 8131:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8132: }
                   8133: 
                   8134: sub machine_domains {
                   8135:     my ($hostname) = @_;
1.465     albertel 8136:     my @domains;
1.838     albertel 8137:     my %hostname = &all_hostnames();
1.465     albertel 8138:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8139: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8140: 	if ($hostname eq $name) {
1.844     albertel 8141: 	    push(@domains,&host_domain($id));
1.465     albertel 8142: 	}
                   8143:     }
                   8144:     return @domains;
                   8145: }
                   8146: 
                   8147: sub current_machine_ids {
1.853     albertel 8148:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8149: }
                   8150: 
                   8151: sub machine_ids {
                   8152:     my ($hostname) = @_;
                   8153:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8154:     my @ids;
1.888     albertel 8155:     my %name_to_host = &all_names();
1.889     albertel 8156:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8157: 	return @{ $name_to_host{$hostname} };
                   8158:     }
                   8159:     return;
1.31      www      8160: }
                   8161: 
1.824     raeburn  8162: sub additional_machine_domains {
                   8163:     my @domains;
                   8164:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8165:     while( my $line = <$fh>) {
                   8166:         $line =~ s/\s//g;
                   8167:         push(@domains,$line);
                   8168:     }
                   8169:     return @domains;
                   8170: }
                   8171: 
                   8172: sub default_login_domain {
                   8173:     my $domain = $perlvar{'lonDefDomain'};
                   8174:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8175:     foreach my $posdom (&current_machine_domains(),
                   8176:                         &additional_machine_domains()) {
                   8177:         if (lc($posdom) eq lc($testdomain)) {
                   8178:             $domain=$posdom;
                   8179:             last;
                   8180:         }
                   8181:     }
                   8182:     return $domain;
                   8183: }
                   8184: 
1.31      www      8185: # ------------------------------------------------------------- Declutters URLs
                   8186: 
                   8187: sub declutter {
                   8188:     my $thisfn=shift;
1.569     albertel 8189:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8190:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8191:     $thisfn=~s/^\///;
1.697     albertel 8192:     $thisfn=~s|^adm/wrapper/||;
                   8193:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8194:     $thisfn=~s/^res\///;
1.235     www      8195:     $thisfn=~s/\?.+$//;
1.268     www      8196:     return $thisfn;
                   8197: }
                   8198: 
                   8199: # ------------------------------------------------------------- Clutter up URLs
                   8200: 
                   8201: sub clutter {
                   8202:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8203:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8204: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8205:        $thisfn='/res'.$thisfn; 
                   8206:     }
1.694     albertel 8207:     if ($thisfn !~m|/adm|) {
1.695     albertel 8208: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8209: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8210: 	} else {
                   8211: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8212: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8213: 	    if ($embstyle eq 'ssi'
                   8214: 		|| ($embstyle eq 'hdn')
                   8215: 		|| ($embstyle eq 'rat')
                   8216: 		|| ($embstyle eq 'prv')
                   8217: 		|| ($embstyle eq 'ign')) {
                   8218: 		#do nothing with these
                   8219: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8220: 		|| ($embstyle eq 'emb')
                   8221: 		|| ($embstyle eq 'wrp')) {
                   8222: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8223: 	    } elsif ($embstyle eq 'unk'
                   8224: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8225: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8226: 	    } else {
1.718     www      8227: #		&logthis("Got a blank emb style");
1.695     albertel 8228: 	    }
1.694     albertel 8229: 	}
                   8230:     }
1.31      www      8231:     return $thisfn;
1.12      www      8232: }
                   8233: 
1.787     albertel 8234: sub clutter_with_no_wrapper {
                   8235:     my $uri = &clutter(shift);
                   8236:     if ($uri =~ m-^/adm/-) {
                   8237: 	$uri =~ s-^/adm/wrapper/-/-;
                   8238: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8239:     }
                   8240:     return $uri;
                   8241: }
                   8242: 
1.557     albertel 8243: sub freeze_escape {
                   8244:     my ($value)=@_;
                   8245:     if (ref($value)) {
                   8246: 	$value=&nfreeze($value);
                   8247: 	return '__FROZEN__'.&escape($value);
                   8248:     }
                   8249:     return &escape($value);
                   8250: }
                   8251: 
1.11      www      8252: 
1.557     albertel 8253: sub thaw_unescape {
                   8254:     my ($value)=@_;
                   8255:     if ($value =~ /^__FROZEN__/) {
                   8256: 	substr($value,0,10,undef);
                   8257: 	$value=&unescape($value);
                   8258: 	return &thaw($value);
                   8259:     }
                   8260:     return &unescape($value);
                   8261: }
                   8262: 
1.436     albertel 8263: sub correct_line_ends {
                   8264:     my ($result)=@_;
                   8265:     $$result =~s/\r\n/\n/mg;
                   8266:     $$result =~s/\r/\n/mg;
1.415     albertel 8267: }
1.1       albertel 8268: # ================================================================ Main Program
                   8269: 
1.184     www      8270: sub goodbye {
1.204     albertel 8271:    &logthis("Starting Shut down");
1.443     albertel 8272: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8273:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8274: #converted
1.599     albertel 8275: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8276:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8277: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8278: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8279: #1.1 only
1.870     albertel 8280: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8281: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8282: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8283: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8284:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8285:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8286:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8287:    &flushcourselogs();
                   8288:    &logthis("Shutting down");
                   8289: }
                   8290: 
1.852     albertel 8291: sub get_dns {
1.869     albertel 8292:     my ($url,$func,$ignore_cache) = @_;
                   8293:     if (!$ignore_cache) {
                   8294: 	my ($content,$cached)=
                   8295: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8296: 	if ($cached) {
                   8297: 	    &$func($content);
                   8298: 	    return;
                   8299: 	}
                   8300:     }
                   8301: 
                   8302:     my %alldns;
1.852     albertel 8303:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8304:     foreach my $dns (<$config>) {
                   8305: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8306: 	$alldns{$1} = 1;
                   8307:     }
                   8308:     while (%alldns) {
                   8309: 	my ($dns) = keys(%alldns);
                   8310: 	delete($alldns{$dns});
1.852     albertel 8311: 	my $ua=new LWP::UserAgent;
                   8312: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8313: 	my $response=$ua->request($request);
                   8314: 	next if ($response->is_error());
                   8315: 	my @content = split("\n",$response->content);
1.869     albertel 8316: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8317: 	&$func(\@content);
1.869     albertel 8318: 	return;
1.852     albertel 8319:     }
                   8320:     close($config);
1.871     albertel 8321:     my $which = (split('/',$url))[3];
                   8322:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8323:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8324:     my @content = <$config>;
                   8325:     &$func(\@content);
                   8326:     return;
1.852     albertel 8327: }
1.327     albertel 8328: # ------------------------------------------------------------ Read domain file
                   8329: {
1.852     albertel 8330:     my $loaded;
1.846     albertel 8331:     my %domain;
                   8332: 
1.852     albertel 8333:     sub parse_domain_tab {
                   8334: 	my ($lines) = @_;
                   8335: 	foreach my $line (@$lines) {
                   8336: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8337: 
1.846     albertel 8338: 	    chomp($line);
1.852     albertel 8339: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8340: 	    my %this_domain;
                   8341: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8342: 			       'lang_def', 'city', 'longi', 'lati',
                   8343: 			       'primary') {
                   8344: 		$this_domain{$field} = shift(@elements);
                   8345: 	    }
                   8346: 	    $domain{$name} = \%this_domain;
1.852     albertel 8347: 	}
                   8348:     }
1.864     albertel 8349: 
                   8350:     sub reset_domain_info {
                   8351: 	undef($loaded);
                   8352: 	undef(%domain);
                   8353:     }
                   8354: 
1.852     albertel 8355:     sub load_domain_tab {
1.869     albertel 8356: 	my ($ignore_cache) = @_;
                   8357: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8358: 	my $fh;
                   8359: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8360: 	    my @lines = <$fh>;
                   8361: 	    &parse_domain_tab(\@lines);
1.448     albertel 8362: 	}
1.852     albertel 8363: 	close($fh);
                   8364: 	$loaded = 1;
1.327     albertel 8365:     }
1.846     albertel 8366: 
                   8367:     sub domain {
1.852     albertel 8368: 	&load_domain_tab() if (!$loaded);
                   8369: 
1.846     albertel 8370: 	my ($name,$what) = @_;
                   8371: 	return if ( !exists($domain{$name}) );
                   8372: 
                   8373: 	if (!$what) {
                   8374: 	    return $domain{$name}{'description'};
                   8375: 	}
                   8376: 	return $domain{$name}{$what};
                   8377:     }
1.327     albertel 8378: }
                   8379: 
                   8380: 
1.1       albertel 8381: # ------------------------------------------------------------- Read hosts file
                   8382: {
1.838     albertel 8383:     my %hostname;
1.844     albertel 8384:     my %hostdom;
1.845     albertel 8385:     my %libserv;
1.852     albertel 8386:     my $loaded;
1.888     albertel 8387:     my %name_to_host;
1.852     albertel 8388: 
                   8389:     sub parse_hosts_tab {
                   8390: 	my ($file) = @_;
                   8391: 	foreach my $configline (@$file) {
                   8392: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8393: 	    next if ($configline =~ /^\^/);
                   8394: 	    chomp($configline);
                   8395: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8396: 	    $name=~s/\s//g;
                   8397: 	    if ($id && $domain && $role && $name) {
                   8398: 		$hostname{$id}=$name;
1.888     albertel 8399: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8400: 		$hostdom{$id}=$domain;
                   8401: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8402: 	    }
                   8403: 	}
                   8404:     }
1.864     albertel 8405:     
                   8406:     sub reset_hosts_info {
1.897     albertel 8407: 	&purge_remembered();
1.864     albertel 8408: 	&reset_domain_info();
                   8409: 	&reset_hosts_ip_info();
1.892     albertel 8410: 	undef(%name_to_host);
1.864     albertel 8411: 	undef(%hostname);
                   8412: 	undef(%hostdom);
                   8413: 	undef(%libserv);
                   8414: 	undef($loaded);
                   8415:     }
1.1       albertel 8416: 
1.852     albertel 8417:     sub load_hosts_tab {
1.869     albertel 8418: 	my ($ignore_cache) = @_;
                   8419: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8420: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8421: 	my @config = <$config>;
                   8422: 	&parse_hosts_tab(\@config);
                   8423: 	close($config);
                   8424: 	$loaded=1;
1.1       albertel 8425:     }
1.852     albertel 8426: 
1.838     albertel 8427:     sub hostname {
1.852     albertel 8428: 	&load_hosts_tab() if (!$loaded);
                   8429: 
1.838     albertel 8430: 	my ($lonid) = @_;
                   8431: 	return $hostname{$lonid};
                   8432:     }
1.845     albertel 8433: 
1.838     albertel 8434:     sub all_hostnames {
1.852     albertel 8435: 	&load_hosts_tab() if (!$loaded);
                   8436: 
1.838     albertel 8437: 	return %hostname;
                   8438:     }
1.845     albertel 8439: 
1.888     albertel 8440:     sub all_names {
                   8441: 	&load_hosts_tab() if (!$loaded);
                   8442: 
                   8443: 	return %name_to_host;
                   8444:     }
                   8445: 
1.845     albertel 8446:     sub is_library {
1.852     albertel 8447: 	&load_hosts_tab() if (!$loaded);
                   8448: 
1.845     albertel 8449: 	return exists($libserv{$_[0]});
                   8450:     }
                   8451: 
                   8452:     sub all_library {
1.852     albertel 8453: 	&load_hosts_tab() if (!$loaded);
                   8454: 
1.845     albertel 8455: 	return %libserv;
                   8456:     }
                   8457: 
1.841     albertel 8458:     sub get_servers {
1.852     albertel 8459: 	&load_hosts_tab() if (!$loaded);
                   8460: 
1.841     albertel 8461: 	my ($domain,$type) = @_;
                   8462: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8463: 	                                          : %hostname;
                   8464: 	my %result;
1.842     albertel 8465: 	if (ref($domain) eq 'ARRAY') {
                   8466: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8467: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8468: 		    $result{$host} = $hostname;
                   8469: 		}
                   8470: 	    }
                   8471: 	} else {
                   8472: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8473: 		if ($hostdom{$host} eq $domain) {
                   8474: 		    $result{$host} = $hostname;
                   8475: 		}
1.841     albertel 8476: 	    }
                   8477: 	}
                   8478: 	return %result;
                   8479:     }
1.845     albertel 8480: 
1.844     albertel 8481:     sub host_domain {
1.852     albertel 8482: 	&load_hosts_tab() if (!$loaded);
                   8483: 
1.844     albertel 8484: 	my ($lonid) = @_;
                   8485: 	return $hostdom{$lonid};
                   8486:     }
                   8487: 
1.841     albertel 8488:     sub all_domains {
1.852     albertel 8489: 	&load_hosts_tab() if (!$loaded);
                   8490: 
1.841     albertel 8491: 	my %seen;
                   8492: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8493: 	return @uniq;
                   8494:     }
1.1       albertel 8495: }
                   8496: 
1.847     albertel 8497: { 
                   8498:     my %iphost;
1.856     albertel 8499:     my %name_to_ip;
                   8500:     my %lonid_to_ip;
1.869     albertel 8501: 
1.847     albertel 8502:     sub get_hosts_from_ip {
                   8503: 	my ($ip) = @_;
                   8504: 	my %iphosts = &get_iphost();
                   8505: 	if (ref($iphosts{$ip})) {
                   8506: 	    return @{$iphosts{$ip}};
                   8507: 	}
                   8508: 	return;
1.839     albertel 8509:     }
1.864     albertel 8510:     
                   8511:     sub reset_hosts_ip_info {
                   8512: 	undef(%iphost);
                   8513: 	undef(%name_to_ip);
                   8514: 	undef(%lonid_to_ip);
                   8515:     }
1.856     albertel 8516: 
                   8517:     sub get_host_ip {
                   8518: 	my ($lonid) = @_;
                   8519: 	if (exists($lonid_to_ip{$lonid})) {
                   8520: 	    return $lonid_to_ip{$lonid};
                   8521: 	}
                   8522: 	my $name=&hostname($lonid);
                   8523:    	my $ip = gethostbyname($name);
                   8524: 	return if (!$ip || length($ip) ne 4);
                   8525: 	$ip=inet_ntoa($ip);
                   8526: 	$name_to_ip{$name}   = $ip;
                   8527: 	$lonid_to_ip{$lonid} = $ip;
                   8528: 	return $ip;
                   8529:     }
1.847     albertel 8530:     
                   8531:     sub get_iphost {
1.869     albertel 8532: 	my ($ignore_cache) = @_;
1.894     albertel 8533: 
1.869     albertel 8534: 	if (!$ignore_cache) {
                   8535: 	    if (%iphost) {
                   8536: 		return %iphost;
                   8537: 	    }
                   8538: 	    my ($ip_info,$cached)=
                   8539: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8540: 	    if ($cached) {
                   8541: 		%iphost      = %{$ip_info->[0]};
                   8542: 		%name_to_ip  = %{$ip_info->[1]};
                   8543: 		%lonid_to_ip = %{$ip_info->[2]};
                   8544: 		return %iphost;
                   8545: 	    }
                   8546: 	}
1.894     albertel 8547: 
                   8548: 	# get yesterday's info for fallback
                   8549: 	my %old_name_to_ip;
                   8550: 	my ($ip_info,$cached)=
                   8551: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8552: 	if ($cached) {
                   8553: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8554: 	}
                   8555: 
1.888     albertel 8556: 	my %name_to_host = &all_names();
                   8557: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8558: 	    my $ip;
                   8559: 	    if (!exists($name_to_ip{$name})) {
                   8560: 		$ip = gethostbyname($name);
                   8561: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8562: 		    if (defined($old_name_to_ip{$name})) {
                   8563: 			$ip = $old_name_to_ip{$name};
                   8564: 			&logthis("Can't find $name defaulting to old $ip");
                   8565: 		    } else {
                   8566: 			&logthis("Name $name no IP found");
                   8567: 			next;
                   8568: 		    }
                   8569: 		} else {
                   8570: 		    $ip=inet_ntoa($ip);
1.847     albertel 8571: 		}
                   8572: 		$name_to_ip{$name} = $ip;
                   8573: 	    } else {
                   8574: 		$ip = $name_to_ip{$name};
1.653     albertel 8575: 	    }
1.888     albertel 8576: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8577: 		$lonid_to_ip{$id} = $ip;
                   8578: 	    }
                   8579: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8580: 	}
1.869     albertel 8581: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8582: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8583: 				      48*60*60);
1.869     albertel 8584: 
1.847     albertel 8585: 	return %iphost;
1.598     albertel 8586:     }
                   8587: }
                   8588: 
1.862     albertel 8589: BEGIN {
                   8590: 
                   8591: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8592:     unless ($readit) {
                   8593: {
                   8594:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8595:     %perlvar = (%perlvar,%{$configvars});
                   8596: }
                   8597: 
                   8598: 
1.1       albertel 8599: # ------------------------------------------------------ Read spare server file
                   8600: {
1.448     albertel 8601:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8602: 
                   8603:     while (my $configline=<$config>) {
                   8604:        chomp($configline);
1.284     matthew  8605:        if ($configline) {
1.784     albertel 8606: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8607: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8608: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8609:        }
                   8610:     }
1.448     albertel 8611:     close($config);
1.1       albertel 8612: }
1.11      www      8613: # ------------------------------------------------------------ Read permissions
                   8614: {
1.448     albertel 8615:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8616: 
                   8617:     while (my $configline=<$config>) {
1.448     albertel 8618: 	chomp($configline);
                   8619: 	if ($configline) {
                   8620: 	    my ($role,$perm)=split(/ /,$configline);
                   8621: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8622: 	}
1.11      www      8623:     }
1.448     albertel 8624:     close($config);
1.11      www      8625: }
                   8626: 
                   8627: # -------------------------------------------- Read plain texts for permissions
                   8628: {
1.448     albertel 8629:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8630: 
                   8631:     while (my $configline=<$config>) {
1.448     albertel 8632: 	chomp($configline);
                   8633: 	if ($configline) {
1.742     raeburn  8634: 	    my ($short,@plain)=split(/:/,$configline);
                   8635:             %{$prp{$short}} = ();
                   8636: 	    if (@plain > 0) {
                   8637:                 $prp{$short}{'std'} = $plain[0];
                   8638:                 for (my $i=1; $i<@plain; $i++) {
                   8639:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8640:                 }
                   8641:             }
1.448     albertel 8642: 	}
1.135     www      8643:     }
1.448     albertel 8644:     close($config);
1.135     www      8645: }
                   8646: 
                   8647: # ---------------------------------------------------------- Read package table
                   8648: {
1.448     albertel 8649:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8650: 
                   8651:     while (my $configline=<$config>) {
1.483     albertel 8652: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8653: 	chomp($configline);
                   8654: 	my ($short,$plain)=split(/:/,$configline);
                   8655: 	my ($pack,$name)=split(/\&/,$short);
                   8656: 	if ($plain ne '') {
                   8657: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8658: 	    $packagetab{$short}=$plain; 
                   8659: 	}
1.11      www      8660:     }
1.448     albertel 8661:     close($config);
1.329     matthew  8662: }
                   8663: 
                   8664: # ------------- set up temporary directory
                   8665: {
                   8666:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8667: 
1.11      www      8668: }
                   8669: 
1.794     albertel 8670: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8671: 				'compress_threshold'=> 20_000,
                   8672:  			        });
1.185     www      8673: 
1.281     www      8674: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8675: $dumpcount=0;
1.22      www      8676: 
1.163     harris41 8677: &logtouch();
1.672     albertel 8678: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8679: $readit=1;
1.564     albertel 8680:     {
                   8681: 	use integer;
                   8682: 	my $test=(2**32)+1;
1.568     albertel 8683: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8684: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8685:     }
1.195     www      8686: }
1.1       albertel 8687: }
1.179     www      8688: 
1.1       albertel 8689: 1;
1.191     harris41 8690: __END__
                   8691: 
1.243     albertel 8692: =pod
                   8693: 
1.191     harris41 8694: =head1 NAME
                   8695: 
1.243     albertel 8696: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8697: 
                   8698: =head1 SYNOPSIS
                   8699: 
1.243     albertel 8700: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8701: 
                   8702:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8703: 
1.243     albertel 8704: Common parameters:
                   8705: 
                   8706: =over 4
                   8707: 
                   8708: =item *
                   8709: 
                   8710: $uname : an internal username (if $cname expecting a course Id specifically)
                   8711: 
                   8712: =item *
                   8713: 
                   8714: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8715: 
                   8716: =item *
                   8717: 
                   8718: $symb : a resource instance identifier
                   8719: 
                   8720: =item *
                   8721: 
                   8722: $namespace : the name of a .db file that contains the data needed or
                   8723: being set.
                   8724: 
                   8725: =back
                   8726: 
1.394     bowersj2 8727: =head1 OVERVIEW
1.191     harris41 8728: 
1.394     bowersj2 8729: lonnet provides subroutines which interact with the
                   8730: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8731: about classes, users, and resources.
1.243     albertel 8732: 
                   8733: For many of these objects you can also use this to store data about
                   8734: them or modify them in various ways.
1.191     harris41 8735: 
1.394     bowersj2 8736: =head2 Symbs
1.191     harris41 8737: 
1.394     bowersj2 8738: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8739: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8740: map, the resource number of the resource in the map, and the URL of
                   8741: the resource itself. The latter is somewhat redundant, but might help
                   8742: if maps change.
                   8743: 
                   8744: An example is
                   8745: 
                   8746:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8747: 
                   8748: The respective map entry is
                   8749: 
                   8750:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8751:   title="Problem 2">
                   8752:  </resource>
                   8753: 
                   8754: Symbs are used by the random number generator, as well as to store and
                   8755: restore data specific to a certain instance of for example a problem.
                   8756: 
                   8757: =head2 Storing And Retrieving Data
                   8758: 
                   8759: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8760: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8761: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8762: is is the non-critical message twin of cstore. These functions are for
                   8763: handlers to store a perl hash to a user's permanent data space in an
                   8764: easy manner, and to retrieve it again on another call. It is expected
                   8765: that a handler would use this once at the beginning to retrieve data,
                   8766: and then again once at the end to send only the new data back.
                   8767: 
                   8768: The data is stored in the user's data directory on the user's
                   8769: homeserver under the ID of the course.
                   8770: 
                   8771: The hash that is returned by restore will have all of the previous
                   8772: value for all of the elements of the hash.
                   8773: 
                   8774: Example:
                   8775: 
                   8776:  #creating a hash
                   8777:  my %hash;
                   8778:  $hash{'foo'}='bar';
                   8779: 
                   8780:  #storing it
                   8781:  &Apache::lonnet::cstore(\%hash);
                   8782: 
                   8783:  #changing a value
                   8784:  $hash{'foo'}='notbar';
                   8785: 
                   8786:  #adding a new value
                   8787:  $hash{'bar'}='foo';
                   8788:  &Apache::lonnet::cstore(\%hash);
                   8789: 
                   8790:  #retrieving the hash
                   8791:  my %history=&Apache::lonnet::restore();
                   8792: 
                   8793:  #print the hash
                   8794:  foreach my $key (sort(keys(%history))) {
                   8795:    print("\%history{$key} = $history{$key}");
                   8796:  }
                   8797: 
                   8798: Will print out:
1.191     harris41 8799: 
1.394     bowersj2 8800:  %history{1:foo} = bar
                   8801:  %history{1:keys} = foo:timestamp
                   8802:  %history{1:timestamp} = 990455579
                   8803:  %history{2:bar} = foo
                   8804:  %history{2:foo} = notbar
                   8805:  %history{2:keys} = foo:bar:timestamp
                   8806:  %history{2:timestamp} = 990455580
                   8807:  %history{bar} = foo
                   8808:  %history{foo} = notbar
                   8809:  %history{timestamp} = 990455580
                   8810:  %history{version} = 2
                   8811: 
                   8812: Note that the special hash entries C<keys>, C<version> and
                   8813: C<timestamp> were added to the hash. C<version> will be equal to the
                   8814: total number of versions of the data that have been stored. The
                   8815: C<timestamp> attribute will be the UNIX time the hash was
                   8816: stored. C<keys> is available in every historical section to list which
                   8817: keys were added or changed at a specific historical revision of a
                   8818: hash.
                   8819: 
                   8820: B<Warning>: do not store the hash that restore returns directly. This
                   8821: will cause a mess since it will restore the historical keys as if the
                   8822: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8823: 
1.394     bowersj2 8824: Calling convention:
1.191     harris41 8825: 
1.394     bowersj2 8826:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8827:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8828: 
1.394     bowersj2 8829: For more detailed information, see lonnet specific documentation.
1.191     harris41 8830: 
1.394     bowersj2 8831: =head1 RETURN MESSAGES
1.191     harris41 8832: 
1.394     bowersj2 8833: =over 4
1.191     harris41 8834: 
1.394     bowersj2 8835: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8836: 
1.394     bowersj2 8837: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8838: when the connection is brought back up
1.191     harris41 8839: 
1.394     bowersj2 8840: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8841: for later delivery
1.191     harris41 8842: 
1.394     bowersj2 8843: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8844: 
1.394     bowersj2 8845: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8846: that was requested
1.191     harris41 8847: 
1.243     albertel 8848: =back
1.191     harris41 8849: 
1.243     albertel 8850: =head1 PUBLIC SUBROUTINES
1.191     harris41 8851: 
1.243     albertel 8852: =head2 Session Environment Functions
1.191     harris41 8853: 
1.243     albertel 8854: =over 4
1.191     harris41 8855: 
1.394     bowersj2 8856: =item * 
                   8857: X<appenv()>
1.949     raeburn  8858: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 8859: the user envirnoment file, and will be restored for each access this
1.620     albertel 8860: user makes during this session, also modifies the %env for the current
1.949     raeburn  8861: process. Optional rolesarrayref - if defined contains a reference to an array
                   8862: of roles which are exempt from the restriction on modifying user.role entries 
                   8863: in the user's environment.db and in %env.    
1.191     harris41 8864: 
                   8865: =item *
1.394     bowersj2 8866: X<delenv()>
                   8867: B<delenv($regexp)>: removes all items from the session
                   8868: environment file that matches the regular expression in $regexp. The
1.620     albertel 8869: values are also delted from the current processes %env.
1.191     harris41 8870: 
1.795     albertel 8871: =item * get_env_multiple($name) 
                   8872: 
                   8873: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8874: values may be defined and end up as an array ref.
                   8875: 
                   8876: returns an array of values
                   8877: 
1.243     albertel 8878: =back
                   8879: 
                   8880: =head2 User Information
1.191     harris41 8881: 
1.243     albertel 8882: =over 4
1.191     harris41 8883: 
                   8884: =item *
1.394     bowersj2 8885: X<queryauthenticate()>
                   8886: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8887: authentication scheme
                   8888: 
                   8889: =item *
1.394     bowersj2 8890: X<authenticate()>
                   8891: B<authenticate($uname,$upass,$udom)>: try to
                   8892: authenticate user from domain's lib servers (first use the current
                   8893: one). C<$upass> should be the users password.
1.191     harris41 8894: 
                   8895: =item *
1.394     bowersj2 8896: X<homeserver()>
                   8897: B<homeserver($uname,$udom)>: find the server which has
                   8898: the user's directory and files (there must be only one), this caches
                   8899: the answer, and also caches if there is a borken connection.
1.191     harris41 8900: 
                   8901: =item *
1.394     bowersj2 8902: X<idget()>
                   8903: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8904: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8905: username, and only 1 username per ID in a specific domain) (returns
                   8906: hash: id=>name,id=>name)
1.191     harris41 8907: 
                   8908: =item *
1.394     bowersj2 8909: X<idrget()>
                   8910: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8911: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8912: 
                   8913: =item *
1.394     bowersj2 8914: X<idput()>
                   8915: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8916: 
                   8917: =item *
1.394     bowersj2 8918: X<rolesinit()>
                   8919: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8920: 
                   8921: =item *
1.551     albertel 8922: X<getsection()>
                   8923: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8924: course $cname, return section name/number or '' for "not in course"
                   8925: and '-1' for "no section"
                   8926: 
                   8927: =item *
1.394     bowersj2 8928: X<userenvironment()>
                   8929: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8930: passed in @what from the requested user's environment, returns a hash
                   8931: 
1.858     raeburn  8932: =item * 
                   8933: X<userlog_query()>
1.859     albertel 8934: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8935: activity.log file. %filters defines filters applied when parsing the
                   8936: log file. These can be start or end timestamps, or the type of action
                   8937: - log to look for Login or Logout events, check for Checkin or
                   8938: Checkout, role for role selection. The response is in the form
                   8939: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8940: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8941: 
1.243     albertel 8942: =back
                   8943: 
                   8944: =head2 User Roles
                   8945: 
                   8946: =over 4
                   8947: 
                   8948: =item *
                   8949: 
1.810     raeburn  8950: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8951:  F: full access
                   8952:  U,I,K: authentication modes (cxx only)
                   8953:  '': forbidden
                   8954:  1: user needs to choose course
                   8955:  2: browse allowed
1.766     albertel 8956:  A: passphrase authentication needed
1.243     albertel 8957: 
                   8958: =item *
                   8959: 
                   8960: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8961: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8962: and course level
                   8963: 
                   8964: =item *
                   8965: 
                   8966: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8967: explanation of a user role term
                   8968: 
1.832     raeburn  8969: =item *
                   8970: 
1.935     raeburn  8971: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  8972: All arguments are optional. Returns a hash of a roles, either for
                   8973: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8974: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  8975: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   8976: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   8977: For each key, value is set to colon-separated start and end times for
                   8978: the role.  If no username and domain are specified, will default to
1.934     raeburn  8979: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  8980: of role statuses (active, future or previous), roles 
                   8981: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8982: to restrict the list of roles reported. If no array ref is 
                   8983: provided for types, will default to return only active roles.
1.834     albertel 8984: 
1.243     albertel 8985: =back
                   8986: 
                   8987: =head2 User Modification
                   8988: 
                   8989: =over 4
                   8990: 
                   8991: =item *
                   8992: 
                   8993: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8994: user for the level given by URL.  Optional start and end dates (leave empty
                   8995: string or zero for "no date")
1.191     harris41 8996: 
                   8997: =item *
                   8998: 
1.243     albertel 8999: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9000: change a users, password, possible return values are: ok,
                   9001: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9002: refused
1.191     harris41 9003: 
                   9004: =item *
                   9005: 
1.243     albertel 9006: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9007: 
                   9008: =item *
                   9009: 
1.243     albertel 9010: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   9011: modify user
1.191     harris41 9012: 
                   9013: =item *
                   9014: 
1.286     matthew  9015: modifystudent
                   9016: 
                   9017: modify a students enrollment and identification information.
                   9018: The course id is resolved based on the current users environment.  
                   9019: This means the envoking user must be a course coordinator or otherwise
                   9020: associated with a course.
                   9021: 
1.297     matthew  9022: This call is essentially a wrapper for lonnet::modifyuser and
                   9023: lonnet::modify_student_enrollment
1.286     matthew  9024: 
                   9025: Inputs: 
                   9026: 
                   9027: =over 4
                   9028: 
                   9029: =item B<$udom> Students loncapa domain
                   9030: 
                   9031: =item B<$uname> Students loncapa login name
                   9032: 
                   9033: =item B<$uid> Students id/student number
                   9034: 
                   9035: =item B<$umode> Students authentication mode
                   9036: 
                   9037: =item B<$upass> Students password
                   9038: 
                   9039: =item B<$first> Students first name
                   9040: 
                   9041: =item B<$middle> Students middle name
                   9042: 
                   9043: =item B<$last> Students last name
                   9044: 
                   9045: =item B<$gene> Students generation
                   9046: 
                   9047: =item B<$usec> Students section in course
                   9048: 
                   9049: =item B<$end> Unix time of the roles expiration
                   9050: 
                   9051: =item B<$start> Unix time of the roles start date
                   9052: 
                   9053: =item B<$forceid> If defined, allow $uid to be changed
                   9054: 
                   9055: =item B<$desiredhome> server to use as home server for student
                   9056: 
                   9057: =back
1.297     matthew  9058: 
                   9059: =item *
                   9060: 
                   9061: modify_student_enrollment
                   9062: 
                   9063: Change a students enrollment status in a class.  The environment variable
                   9064: 'role.request.course' must be defined for this function to proceed.
                   9065: 
                   9066: Inputs:
                   9067: 
                   9068: =over 4
                   9069: 
                   9070: =item $udom, students domain
                   9071: 
                   9072: =item $uname, students name
                   9073: 
                   9074: =item $uid, students user id
                   9075: 
                   9076: =item $first, students first name
                   9077: 
                   9078: =item $middle
                   9079: 
                   9080: =item $last
                   9081: 
                   9082: =item $gene
                   9083: 
                   9084: =item $usec
                   9085: 
                   9086: =item $end
                   9087: 
                   9088: =item $start
                   9089: 
                   9090: =back
                   9091: 
1.191     harris41 9092: 
                   9093: =item *
                   9094: 
1.243     albertel 9095: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9096: custom role; give a custom role to a user for the level given by URL.  Specify
                   9097: name and domain of role author, and role name
1.191     harris41 9098: 
                   9099: =item *
                   9100: 
1.243     albertel 9101: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9102: 
                   9103: =item *
                   9104: 
1.243     albertel 9105: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9106: 
                   9107: =back
                   9108: 
                   9109: =head2 Course Infomation
                   9110: 
                   9111: =over 4
1.191     harris41 9112: 
                   9113: =item *
                   9114: 
1.631     albertel 9115: coursedescription($courseid) : returns a hash of information about the
                   9116: specified course id, including all environment settings for the
                   9117: course, the description of the course will be in the hash under the
                   9118: key 'description'
1.191     harris41 9119: 
                   9120: =item *
                   9121: 
1.624     albertel 9122: resdata($name,$domain,$type,@which) : request for current parameter
                   9123: setting for a specific $type, where $type is either 'course' or 'user',
                   9124: @what should be a list of parameters to ask about. This routine caches
                   9125: answers for 5 minutes.
1.243     albertel 9126: 
1.877     foxr     9127: =item *
                   9128: 
                   9129: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9130: data base, returning a hash that is keyed by the resource name and has
                   9131: values that are the resource value.  I believe that the timestamps and
                   9132: versions are also returned.
                   9133: 
                   9134: 
1.243     albertel 9135: =back
                   9136: 
                   9137: =head2 Course Modification
                   9138: 
                   9139: =over 4
1.191     harris41 9140: 
                   9141: =item *
                   9142: 
1.243     albertel 9143: writecoursepref($courseid,%prefs) : write preferences (environment
                   9144: database) for a course
1.191     harris41 9145: 
                   9146: =item *
                   9147: 
1.243     albertel 9148: createcourse($udom,$description,$url) : make/modify course
                   9149: 
                   9150: =back
                   9151: 
                   9152: =head2 Resource Subroutines
                   9153: 
                   9154: =over 4
1.191     harris41 9155: 
                   9156: =item *
                   9157: 
1.243     albertel 9158: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9159: 
                   9160: =item *
                   9161: 
1.243     albertel 9162: repcopy($filename) : subscribes to the requested file, and attempts to
                   9163: replicate from the owning library server, Might return
1.607     raeburn  9164: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9165: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9166: resource. Expects the local filesystem pathname
                   9167: (/home/httpd/html/res/....)
                   9168: 
                   9169: =back
                   9170: 
                   9171: =head2 Resource Information
                   9172: 
                   9173: =over 4
1.191     harris41 9174: 
                   9175: =item *
                   9176: 
1.243     albertel 9177: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9178: a vairety of different possible values, $varname should be a request
                   9179: string, and the other parameters can be used to specify who and what
                   9180: one is asking about.
                   9181: 
                   9182: Possible values for $varname are environment.lastname (or other item
                   9183: from the envirnment hash), user.name (or someother aspect about the
                   9184: user), resource.0.maxtries (or some other part and parameter of a
                   9185: resource)
1.204     albertel 9186: 
                   9187: =item *
                   9188: 
1.243     albertel 9189: directcondval($number) : get current value of a condition; reads from a state
                   9190: string
1.204     albertel 9191: 
                   9192: =item *
                   9193: 
1.243     albertel 9194: condval($condidx) : value of condition index based on state
1.204     albertel 9195: 
                   9196: =item *
                   9197: 
1.243     albertel 9198: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9199: resource's metadata, $what should be either a specific key, or either
                   9200: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9201: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9202: 
                   9203: this function automatically caches all requests
1.191     harris41 9204: 
                   9205: =item *
                   9206: 
1.243     albertel 9207: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9208: network of library servers; returns file handle of where SQL and regex results
                   9209: will be stored for query
1.191     harris41 9210: 
                   9211: =item *
                   9212: 
1.243     albertel 9213: symbread($filename) : return symbolic list entry (filename argument optional);
                   9214: returns the data handle
1.191     harris41 9215: 
                   9216: =item *
                   9217: 
1.243     albertel 9218: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9219: a possible symb for the URL in $thisfn, and if is an encryypted
                   9220: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9221: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9222: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9223: 
1.191     harris41 9224: 
                   9225: =item *
                   9226: 
1.243     albertel 9227: symbclean($symb) : removes versions numbers from a symb, returns the
                   9228: cleaned symb
1.191     harris41 9229: 
                   9230: =item *
                   9231: 
1.243     albertel 9232: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9233: course map, user must be in a course for it to work.
1.191     harris41 9234: 
                   9235: =item *
                   9236: 
1.243     albertel 9237: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9238: 
                   9239: =item *
                   9240: 
1.243     albertel 9241: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9242: a random seed, all arguments are optional, if they aren't sent it uses the
                   9243: environment to derive them. Note: if symb isn't sent and it can't get one
                   9244: from &symbread it will use the current time as its return value
1.191     harris41 9245: 
                   9246: =item *
                   9247: 
1.243     albertel 9248: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9249: unfakeable, receipt
1.191     harris41 9250: 
                   9251: =item *
                   9252: 
1.620     albertel 9253: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9254: 
                   9255: =item *
                   9256: 
1.243     albertel 9257: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9258: 
                   9259: =item *
                   9260: 
1.243     albertel 9261: 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 9262: 
                   9263: =item *
                   9264: 
1.243     albertel 9265: 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 9266: 
                   9267: =item *
                   9268: 
1.243     albertel 9269: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9270: 
                   9271: =item *
                   9272: 
1.243     albertel 9273: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9274: forcing spreadsheet to reevaluate the resource scores next time.
                   9275: 
                   9276: =back
                   9277: 
                   9278: =head2 Storing/Retreiving Data
                   9279: 
                   9280: =over 4
1.191     harris41 9281: 
                   9282: =item *
                   9283: 
1.243     albertel 9284: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9285: for this url; hashref needs to be given and should be a \%hashname; the
                   9286: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9287: be derived from the env
1.191     harris41 9288: 
                   9289: =item *
                   9290: 
1.243     albertel 9291: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9292: uses critical subroutine
1.191     harris41 9293: 
                   9294: =item *
                   9295: 
1.243     albertel 9296: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9297: all args are optional
1.191     harris41 9298: 
                   9299: =item *
                   9300: 
1.717     albertel 9301: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9302: dumps the complete (or key matching regexp) namespace into a hash
                   9303: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9304: normally &store()ed into
                   9305: 
                   9306: $range should be either an integer '100' (give me the first 100
                   9307:                                            matching records)
                   9308:               or be  two integers sperated by a - with no spaces
                   9309:                  '30-50' (give me the 30th through the 50th matching
                   9310:                           records)
                   9311: 
                   9312: 
                   9313: =item *
                   9314: 
                   9315: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9316: replaces a &store() version of data with a replacement set of data
                   9317: for a particular resource in a namespace passed in the $storehash hash 
                   9318: reference
                   9319: 
                   9320: =item *
                   9321: 
1.243     albertel 9322: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9323: works very similar to store/cstore, but all data is stored in a
                   9324: temporary location and can be reset using tmpreset, $storehash should
                   9325: be a hash reference, returns nothing on success
1.191     harris41 9326: 
                   9327: =item *
                   9328: 
1.243     albertel 9329: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9330: similar to restore, but all data is stored in a temporary location and
                   9331: can be reset using tmpreset. Returns a hash of values on success,
                   9332: error string otherwise.
1.191     harris41 9333: 
                   9334: =item *
                   9335: 
1.243     albertel 9336: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9337: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9338: 
                   9339: =item *
                   9340: 
1.243     albertel 9341: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9342: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9343: 
                   9344: =item *
                   9345: 
1.243     albertel 9346: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9347: namesp ($udom and $uname are optional)
1.191     harris41 9348: 
                   9349: =item *
                   9350: 
1.702     albertel 9351: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9352: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9353: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9354: 
1.702     albertel 9355: $range should be either an integer '100' (give me the first 100
                   9356:                                            matching records)
                   9357:               or be  two integers sperated by a - with no spaces
                   9358:                  '30-50' (give me the 30th through the 50th matching
                   9359:                           records)
1.449     matthew  9360: =item *
                   9361: 
                   9362: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9363: $store can be a scalar, an array reference, or if the amount to be 
                   9364: incremented is > 1, a hash reference.
                   9365: 
                   9366: ($udom and $uname are optional)
1.191     harris41 9367: 
                   9368: =item *
                   9369: 
1.243     albertel 9370: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9371: ($udom and $uname are optional)
1.191     harris41 9372: 
                   9373: =item *
                   9374: 
1.243     albertel 9375: cput($namespace,$storehash,$udom,$uname) : critical put
                   9376: ($udom and $uname are optional)
1.191     harris41 9377: 
                   9378: =item *
                   9379: 
1.748     albertel 9380: newput($namespace,$storehash,$udom,$uname) :
                   9381: 
                   9382: Attempts to store the items in the $storehash, but only if they don't
                   9383: currently exist, if this succeeds you can be certain that you have 
                   9384: successfully created a new key value pair in the $namespace db.
                   9385: 
                   9386: 
                   9387: Args:
                   9388:  $namespace: name of database to store values to
                   9389:  $storehash: hashref to store to the db
                   9390:  $udom: (optional) domain of user containing the db
                   9391:  $uname: (optional) name of user caontaining the db
                   9392: 
                   9393: Returns:
                   9394:  'ok' -> succeeded in storing all keys of $storehash
                   9395:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9396:                         least <key> already existed in the db (other
                   9397:                         requested keys may also already exist)
                   9398:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9399:  'con_lost' -> unable to contact request server
                   9400:  'refused' -> action was not allowed by remote machine
                   9401: 
                   9402: 
                   9403: =item *
                   9404: 
1.243     albertel 9405: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9406: reference filled in from namesp (encrypts the return communication)
                   9407: ($udom and $uname are optional)
1.191     harris41 9408: 
                   9409: =item *
                   9410: 
1.243     albertel 9411: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9412: critical subroutine
                   9413: 
1.806     raeburn  9414: =item *
                   9415: 
1.860     raeburn  9416: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9417: array reference filled in from namespace found in domain level on either
                   9418: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9419: 
                   9420: =item *
                   9421: 
1.860     raeburn  9422: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9423: domain level either on specified domain server ($uhome) or primary domain 
                   9424: server ($udom and $uhome are optional)
1.806     raeburn  9425: 
1.943     raeburn  9426: =item * 
                   9427: 
                   9428: get_domain_defaults($target_domain) : returns hash with defaults for
                   9429: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9430: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9431: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9432: Values are retrieved from cache (if current), or from domain's configuration.db
                   9433: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9434: or lonTabs/domain.tab. 
                   9435: 
                   9436: %domdefaults = &get_auth_defaults($target_domain);
                   9437: 
1.243     albertel 9438: =back
                   9439: 
                   9440: =head2 Network Status Functions
                   9441: 
                   9442: =over 4
1.191     harris41 9443: 
                   9444: =item *
                   9445: 
                   9446: dirlist($uri) : return directory list based on URI
                   9447: 
                   9448: =item *
                   9449: 
1.243     albertel 9450: spareserver() : find server with least workload from spare.tab
                   9451: 
                   9452: =back
                   9453: 
                   9454: =head2 Apache Request
                   9455: 
                   9456: =over 4
1.191     harris41 9457: 
                   9458: =item *
                   9459: 
1.243     albertel 9460: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9461: localhost, posts hash
                   9462: 
                   9463: =back
                   9464: 
                   9465: =head2 Data to String to Data
                   9466: 
                   9467: =over 4
1.191     harris41 9468: 
                   9469: =item *
                   9470: 
1.243     albertel 9471: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9472: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9473: 
                   9474: =item *
                   9475: 
1.243     albertel 9476: hashref2str($hashref) : convert a hashref into a string complete with
                   9477: escaping and '=' and '&' separators, supports elements that are
                   9478: arrayrefs and hashrefs
1.191     harris41 9479: 
                   9480: =item *
                   9481: 
1.243     albertel 9482: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9483: with escaping and '&' separators, supports elements that are arrayrefs
                   9484: and hashrefs
1.191     harris41 9485: 
                   9486: =item *
                   9487: 
1.243     albertel 9488: str2hash($string) : convert string to hash using unescaping and
                   9489: splitting on '=' and '&', supports elements that are arrayrefs and
                   9490: hashrefs
1.191     harris41 9491: 
                   9492: =item *
                   9493: 
1.243     albertel 9494: str2array($string) : convert string to hash using unescaping and
                   9495: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9496: 
                   9497: =back
                   9498: 
                   9499: =head2 Logging Routines
                   9500: 
                   9501: =over 4
                   9502: 
                   9503: These routines allow one to make log messages in the lonnet.log and
                   9504: lonnet.perm logfiles.
1.191     harris41 9505: 
                   9506: =item *
                   9507: 
1.243     albertel 9508: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9509: 
                   9510: =item *
                   9511: 
1.243     albertel 9512: logthis() : append message to the normal lonnet.log file, it gets
                   9513: preiodically rolled over and deleted.
1.191     harris41 9514: 
                   9515: =item *
                   9516: 
1.243     albertel 9517: logperm() : append a permanent message to lonnet.perm.log, this log
                   9518: file never gets deleted by any automated portion of the system, only
                   9519: messages of critical importance should go in here.
                   9520: 
                   9521: =back
                   9522: 
                   9523: =head2 General File Helper Routines
                   9524: 
                   9525: =over 4
1.191     harris41 9526: 
                   9527: =item *
                   9528: 
1.481     raeburn  9529: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9530: (a) files in /uploaded
                   9531:   (i) If a local copy of the file exists - 
                   9532:       compares modification date of local copy with last-modified date for 
                   9533:       definitive version stored on home server for course. If local copy is 
                   9534:       stale, requests a new version from the home server and stores it. 
                   9535:       If the original has been removed from the home server, then local copy 
                   9536:       is unlinked.
                   9537:   (ii) If local copy does not exist -
                   9538:       requests the file from the home server and stores it. 
                   9539:   
                   9540:   If $caller is 'uploadrep':  
                   9541:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9542:     for request for files originally uploaded via DOCS. 
                   9543:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9544:   
                   9545:   Otherwise:
                   9546:      This indicates a call from the content generation phase of the request.
                   9547:      -  returns the entire contents of the file or -1.
                   9548:      
                   9549: (b) files in /res
                   9550:    - returns the entire contents of a file or -1; 
                   9551:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9552: 
1.712     albertel 9553: 
                   9554: =item *
                   9555: 
                   9556: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9557:                   reference
                   9558: 
                   9559: returns either a stat() list of data about the file or an empty list
                   9560: if the file doesn't exist or couldn't find out about it (connection
                   9561: problems or user unknown)
                   9562: 
1.191     harris41 9563: =item *
                   9564: 
1.243     albertel 9565: filelocation($dir,$file) : returns file system location of a file
                   9566: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9567: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9568: and a file of ../bob will become /a/bob)
1.191     harris41 9569: 
                   9570: =item *
                   9571: 
                   9572: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9573: filelocation except for hrefs
                   9574: 
                   9575: =item *
                   9576: 
                   9577: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9578: 
1.243     albertel 9579: =back
                   9580: 
1.608     albertel 9581: =head2 Usererfile file routines (/uploaded*)
                   9582: 
                   9583: =over 4
                   9584: 
                   9585: =item *
                   9586: 
                   9587: userfileupload(): main rotine for putting a file in a user or course's
                   9588:                   filespace, arguments are,
                   9589: 
1.620     albertel 9590:  formname - required - this is the name of the element in $env where the
1.608     albertel 9591:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9592:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9593:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9594:  coursedoc - if true, store the file in the course of the active role
                   9595:              of the current user
                   9596:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9597:          if undefined, it will be placed in "unknown"
                   9598: 
                   9599:  (This routine calls clean_filename() to remove any dangerous
                   9600:  characters from the filename, and then calls finuserfileupload() to
                   9601:  complete the transaction)
                   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: clean_filename(): routine for cleaing a filename up for storage in
                   9609:                  userfile space, argument is:
                   9610: 
                   9611:  filename - proposed filename
                   9612: 
                   9613: returns: the new clean filename
                   9614: 
                   9615: =item *
                   9616: 
                   9617: finishuserfileupload(): routine that creaes and sends the file to
                   9618: userspace, probably shouldn't be called directly
                   9619: 
                   9620:   docuname: username or courseid of destination for the file
                   9621:   docudom: domain of user/course of destination for the file
                   9622:   formname: same as for userfileupload()
                   9623:   fname: filename (inculding subdirectories) for the file
                   9624: 
                   9625:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9626:  and /adm/notfound.html if unsuccessful
                   9627: 
                   9628: =item *
                   9629: 
                   9630: renameuserfile(): renames an existing userfile to a new name
                   9631: 
                   9632:   Args:
                   9633:    docuname: username or courseid of destination for the file
                   9634:    docudom: domain of user/course of destination for the file
                   9635:    old: current file name (including any subdirs under userfiles)
                   9636:    new: desired file name (including any subdirs under userfiles)
                   9637: 
                   9638: =item *
                   9639: 
                   9640: mkdiruserfile(): creates a directory is a userfiles dir
                   9641: 
                   9642:   Args:
                   9643:    docuname: username or courseid of destination for the file
                   9644:    docudom: domain of user/course of destination for the file
                   9645:    dir: dir to create (including any subdirs under userfiles)
                   9646: 
                   9647: =item *
                   9648: 
                   9649: removeuserfile(): removes a file that exists in userfiles
                   9650: 
                   9651:   Args:
                   9652:    docuname: username or courseid of destination for the file
                   9653:    docudom: domain of user/course of destination for the file
                   9654:    fname: filname to delete (including any subdirs under userfiles)
                   9655: 
                   9656: =item *
                   9657: 
                   9658: removeuploadedurl(): convience function for removeuserfile()
                   9659: 
                   9660:   Args:
                   9661:    url:  a full /uploaded/... url to delete
                   9662: 
1.747     albertel 9663: =item * 
                   9664: 
                   9665: get_portfile_permissions():
                   9666:   Args:
                   9667:     domain: domain of user or course contain the portfolio files
                   9668:     user: name of user or num of course contain the portfolio files
                   9669:   Returns:
                   9670:     hashref of a dump of the proper file_permissions.db
                   9671:    
                   9672: 
                   9673: =item * 
                   9674: 
                   9675: get_access_controls():
                   9676: 
                   9677: Args:
                   9678:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9679:   group: (optional) the group you want the files associated with
                   9680:   file: (optional) the file you want access info on
                   9681: 
                   9682: Returns:
1.749     raeburn  9683:     a hash (keys are file names) of hashes containing
                   9684:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9685:         values are XML containing access control settings (see below) 
1.747     albertel 9686: 
                   9687: Internal notes:
                   9688: 
1.749     raeburn  9689:  access controls are stored in file_permissions.db as key=value pairs.
                   9690:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9691:         where scope -> public,guest,course,group,domains or users.
                   9692:               end -> UNIX time for end of access (0 -> no end date)
                   9693:               start -> UNIX time for start of access
                   9694: 
                   9695:     value -> XML description of access control
                   9696:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9697:             <start></start>
                   9698:             <end></end>
                   9699: 
                   9700:             <password></password>  for scope type = guest
                   9701: 
                   9702:             <domain></domain>     for scope type = course or group
                   9703:             <number></number>
                   9704:             <roles id="">
                   9705:              <role></role>
                   9706:              <access></access>
                   9707:              <section></section>
                   9708:              <group></group>
                   9709:             </roles>
                   9710: 
                   9711:             <dom></dom>         for scope type = domains
                   9712: 
                   9713:             <users>             for scope type = users
                   9714:              <user>
                   9715:               <uname></uname>
                   9716:               <udom></udom>
                   9717:              </user>
                   9718:             </users>
                   9719:            </scope> 
                   9720:               
                   9721:  Access data is also aggregated for each file in an additional key=value pair:
                   9722:  key -> path to file/file_name\0accesscontrol 
                   9723:  value -> reference to hash
                   9724:           hash contains key = value pairs
                   9725:           where key = uniqueID:scope_end_start
                   9726:                 value = UNIX time record was last updated
                   9727: 
                   9728:           Used to improve speed of look-ups of access controls for each file.  
                   9729:  
                   9730:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9731: 
                   9732: modify_access_controls():
                   9733: 
                   9734: Modifies access controls for a portfolio file
                   9735: Args
                   9736: 1. file name
                   9737: 2. reference to hash of required changes,
                   9738: 3. domain
                   9739: 4. username
                   9740:   where domain,username are the domain of the portfolio owner 
                   9741:   (either a user or a course) 
                   9742: 
                   9743: Returns:
                   9744: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9745: 2. result of deletions ('ok' or 'error', with error message).
                   9746: 3. reference to hash of any new or updated access controls.
                   9747: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9748:    key = integer (inbound ID)
                   9749:    value = uniqueID  
1.747     albertel 9750: 
1.608     albertel 9751: =back
                   9752: 
1.243     albertel 9753: =head2 HTTP Helper Routines
                   9754: 
                   9755: =over 4
                   9756: 
1.191     harris41 9757: =item *
                   9758: 
                   9759: escape() : unpack non-word characters into CGI-compatible hex codes
                   9760: 
                   9761: =item *
                   9762: 
                   9763: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9764: 
1.243     albertel 9765: =back
                   9766: 
                   9767: =head1 PRIVATE SUBROUTINES
                   9768: 
                   9769: =head2 Underlying communication routines (Shouldn't call)
                   9770: 
                   9771: =over 4
                   9772: 
                   9773: =item *
                   9774: 
                   9775: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9776: 
                   9777: =item *
                   9778: 
                   9779: reply() : uses subreply to send a message to remote machine, logs all failures
                   9780: 
                   9781: =item *
                   9782: 
                   9783: critical() : passes a critical message to another server; if cannot
                   9784: get through then place message in connection buffer directory and
                   9785: returns con_delayed, if incapable of saving message, returns
                   9786: con_failed
                   9787: 
                   9788: =item *
                   9789: 
                   9790: reconlonc() : tries to reconnect lonc client processes.
                   9791: 
                   9792: =back
                   9793: 
                   9794: =head2 Resource Access Logging
                   9795: 
                   9796: =over 4
                   9797: 
                   9798: =item *
                   9799: 
                   9800: flushcourselogs() : flush (save) buffer logs and access logs
                   9801: 
                   9802: =item *
                   9803: 
                   9804: courselog($what) : save message for course in hash
                   9805: 
                   9806: =item *
                   9807: 
                   9808: courseacclog($what) : save message for course using &courselog().  Perform
                   9809: special processing for specific resource types (problems, exams, quizzes, etc).
                   9810: 
1.191     harris41 9811: =item *
                   9812: 
                   9813: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9814: as a PerlChildExitHandler
1.243     albertel 9815: 
                   9816: =back
                   9817: 
                   9818: =head2 Other
                   9819: 
                   9820: =over 4
                   9821: 
                   9822: =item *
                   9823: 
                   9824: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9825: 
                   9826: =back
                   9827: 
                   9828: =cut
1.877     foxr     9829: 

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