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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.881   ! raeburn     4: # $Id: lonnet.pm,v 1.880 2007/05/22 21:56:32 banghart 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.854     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\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.836     www       217:     &logthis("Trying to reconnect lonc");
1.1       albertel  218:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  219:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  220: 	my $loncpid=<$fh>;
                    221:         chomp($loncpid);
                    222:         if (kill 0 => $loncpid) {
                    223: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    224:             kill USR1 => $loncpid;
                    225:             sleep 1;
1.836     www       226:          } else {
1.12      www       227: 	    &logthis(
1.672     albertel  228:                "<font color=\"blue\">WARNING:".
1.12      www       229:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  230:         }
                    231:     } else {
1.836     www       232: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  233:     }
                    234: }
                    235: 
                    236: # ------------------------------------------------------ Critical communication
1.12      www       237: 
1.1       albertel  238: sub critical {
                    239:     my ($cmd,$server)=@_;
1.838     albertel  240:     unless (&hostname($server)) {
1.672     albertel  241:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       242:                " Critical message to unknown server ($server)</font>");
                    243:         return 'no_such_host';
                    244:     }
1.1       albertel  245:     my $answer=reply($cmd,$server);
                    246:     if ($answer eq 'con_lost') {
                    247: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  248: 	my $answer=reply($cmd,$server);
1.1       albertel  249:         if ($answer eq 'con_lost') {
                    250:             my $now=time;
                    251:             my $middlename=$cmd;
1.5       www       252:             $middlename=substr($middlename,0,16);
1.1       albertel  253:             $middlename=~s/\W//g;
                    254:             my $dfilename=
1.305     www       255:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    256:             $dumpcount++;
1.1       albertel  257:             {
1.448     albertel  258: 		my $dfh;
                    259: 		if (open($dfh,">$dfilename")) {
                    260: 		    print $dfh "$cmd\n"; 
                    261: 		    close($dfh);
                    262: 		}
1.1       albertel  263:             }
                    264:             sleep 2;
                    265:             my $wcmd='';
                    266:             {
1.448     albertel  267: 		my $dfh;
                    268: 		if (open($dfh,"<$dfilename")) {
                    269: 		    $wcmd=<$dfh>; 
                    270: 		    close($dfh);
                    271: 		}
1.1       albertel  272:             }
                    273:             chomp($wcmd);
1.7       www       274:             if ($wcmd eq $cmd) {
1.672     albertel  275: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       276:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  277:                 &logperm("D:$server:$cmd");
                    278: 	        return 'con_delayed';
                    279:             } else {
1.672     albertel  280:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       281:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  282:                 &logperm("F:$server:$cmd");
                    283:                 return 'con_failed';
                    284:             }
                    285:         }
                    286:     }
                    287:     return $answer;
1.405     albertel  288: }
                    289: 
1.755     albertel  290: # ------------------------------------------- check if return value is an error
                    291: 
                    292: sub error {
                    293:     my ($result) = @_;
1.756     albertel  294:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  295: 	if ($2 == 2) { return undef; }
                    296: 	return $1;
                    297:     }
                    298:     return undef;
                    299: }
                    300: 
1.783     albertel  301: sub convert_and_load_session_env {
                    302:     my ($lonidsdir,$handle)=@_;
                    303:     my @profile;
                    304:     {
                    305: 	open(my $idf,"$lonidsdir/$handle.id");
                    306: 	flock($idf,LOCK_SH);
                    307: 	@profile=<$idf>;
                    308: 	close($idf);
                    309:     }
                    310:     my %temp_env;
                    311:     foreach my $line (@profile) {
1.786     albertel  312: 	if ($line !~ m/=/) {
                    313: 	    return 0;
                    314: 	}
1.783     albertel  315: 	chomp($line);
                    316: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    317: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    318:     }
                    319:     unlink("$lonidsdir/$handle.id");
                    320:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    321: 	    0640)) {
                    322: 	%disk_env = %temp_env;
                    323: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    324: 	untie(%disk_env);
                    325:     }
1.786     albertel  326:     return 1;
1.783     albertel  327: }
                    328: 
1.374     www       329: # ------------------------------------------- Transfer profile into environment
1.780     albertel  330: my $env_loaded;
                    331: sub transfer_profile_to_env {
1.788     albertel  332:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    333:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       334: 
1.720     albertel  335:     if (!defined($lonidsdir)) {
                    336: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    337:     }
                    338:     if (!defined($handle)) {
                    339:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    340:     }
                    341: 
1.786     albertel  342:     my $convert;
                    343:     {
                    344:     	open(my $idf,"$lonidsdir/$handle.id");
                    345: 	flock($idf,LOCK_SH);
                    346: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    347: 		&GDBM_READER(),0640)) {
                    348: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    349: 	    untie(%disk_env);
                    350: 	} else {
                    351: 	    $convert = 1;
                    352: 	}
                    353:     }
                    354:     if ($convert) {
                    355: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    356: 	    &logthis("Failed to load session, or convert session.");
                    357: 	}
1.374     www       358:     }
1.783     albertel  359: 
1.786     albertel  360:     my %remove;
1.783     albertel  361:     while ( my $envname = each(%env) ) {
1.433     matthew   362:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    363:             if ($time < time-300) {
1.783     albertel  364:                 $remove{$key}++;
1.433     matthew   365:             }
                    366:         }
                    367:     }
1.783     albertel  368: 
1.619     albertel  369:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  370:     $env_loaded=1;
1.783     albertel  371:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   372:         &delenv($expired_key);
1.374     www       373:     }
1.1       albertel  374: }
                    375: 
1.830     albertel  376: sub timed_flock {
                    377:     my ($file,$lock_type) = @_;
                    378:     my $failed=0;
                    379:     eval {
                    380: 	local $SIG{__DIE__}='DEFAULT';
                    381: 	local $SIG{ALRM}=sub {
                    382: 	    $failed=1;
                    383: 	    die("failed lock");
                    384: 	};
                    385: 	alarm(13);
                    386: 	flock($file,$lock_type);
                    387: 	alarm(0);
                    388:     };
                    389:     if ($failed) {
                    390: 	return undef;
                    391:     } else {
                    392: 	return 1;
                    393:     }
                    394: }
                    395: 
1.5       www       396: # ---------------------------------------------------------- Append Environment
                    397: 
                    398: sub appenv {
1.6       www       399:     my %newenv=@_;
1.692     albertel  400:     foreach my $key (keys(%newenv)) {
                    401: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  402:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  403:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       404:                 .'</font>');
1.692     albertel  405: 	    delete($newenv{$key});
1.35      www       406:         } else {
1.692     albertel  407:             $env{$key}=$newenv{$key};
1.35      www       408:         }
1.191     harris41  409:     }
1.830     albertel  410:     open(my $env_file,$env{'user.environment'});
                    411:     if (&timed_flock($env_file,LOCK_EX)
                    412: 	&&
                    413: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    414: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  415: 	while (my ($key,$value) = each(%newenv)) {
                    416: 	    $disk_env{$key} = $value;
1.448     albertel  417: 	}
1.783     albertel  418: 	untie(%disk_env);
1.56      www       419:     }
                    420:     return 'ok';
                    421: }
                    422: # ----------------------------------------------------- Delete from Environment
                    423: 
                    424: sub delenv {
                    425:     my $delthis=shift;
                    426:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  427:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       428:                 "Attempt to delete from environment ".$delthis);
                    429:         return 'error';
                    430:     }
1.830     albertel  431:     open(my $env_file,$env{'user.environment'});
                    432:     if (&timed_flock($env_file,LOCK_EX)
                    433: 	&&
                    434: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    435: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  436: 	foreach my $key (keys(%disk_env)) {
                    437: 	    if ($key=~/^$delthis/) { 
1.619     albertel  438:                 delete($env{$key});
1.783     albertel  439:                 delete($disk_env{$key});
1.473     matthew   440:             }
1.448     albertel  441: 	}
1.783     albertel  442: 	untie(%disk_env);
1.5       www       443:     }
                    444:     return 'ok';
1.369     albertel  445: }
                    446: 
1.790     albertel  447: sub get_env_multiple {
                    448:     my ($name) = @_;
                    449:     my @values;
                    450:     if (defined($env{$name})) {
                    451:         # exists is it an array
                    452:         if (ref($env{$name})) {
                    453:             @values=@{ $env{$name} };
                    454:         } else {
                    455:             $values[0]=$env{$name};
                    456:         }
                    457:     }
                    458:     return(@values);
                    459: }
                    460: 
1.369     albertel  461: # ------------------------------------------ Find out current server userload
                    462: # there is a copy in lond
                    463: sub userload {
                    464:     my $numusers=0;
                    465:     {
                    466: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    467: 	my $filename;
                    468: 	my $curtime=time;
                    469: 	while ($filename=readdir(LONIDS)) {
                    470: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  471: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  472: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  473: 	}
                    474: 	closedir(LONIDS);
                    475:     }
                    476:     my $userloadpercent=0;
                    477:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    478:     if ($maxuserload) {
1.371     albertel  479: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  480:     }
1.372     albertel  481:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  482:     return $userloadpercent;
1.283     www       483: }
                    484: 
                    485: # ------------------------------------------ Fight off request when overloaded
                    486: 
                    487: sub overloaderror {
                    488:     my ($r,$checkserver)=@_;
                    489:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    490:     my $loadavg;
                    491:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  492:        open(my $loadfile,'/proc/loadavg');
1.283     www       493:        $loadavg=<$loadfile>;
                    494:        $loadavg =~ s/\s.*//g;
1.285     matthew   495:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  496:        close($loadfile);
1.283     www       497:     } else {
                    498:        $loadavg=&reply('load',$checkserver);
                    499:     }
1.285     matthew   500:     my $overload=$loadavg-100;
1.283     www       501:     if ($overload>0) {
1.285     matthew   502: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       503:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       504:         return 413;
1.283     www       505:     }    
                    506:     return '';
1.5       www       507: }
1.1       albertel  508: 
                    509: # ------------------------------ Find server with least workload from spare.tab
1.11      www       510: 
1.1       albertel  511: sub spareserver {
1.670     albertel  512:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  513:     my $spare_server;
1.370     albertel  514:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  515:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    516:                                                      :  $userloadpercent;
                    517:     
                    518:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    519: 	($spare_server, $lowest_load) =
                    520: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    521:     }
                    522: 
                    523:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    524: 
                    525:     if (!$found_server) {
                    526: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    527: 	    ($spare_server, $lowest_load) =
                    528: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    529: 	}
                    530:     }
                    531: 
                    532:     if (!$want_server_name) {
1.838     albertel  533: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  534:     }
                    535:     return $spare_server;
                    536: }
                    537: 
                    538: sub compare_server_load {
                    539:     my ($try_server, $spare_server, $lowest_load) = @_;
                    540: 
                    541:     my $loadans     = &reply('load',    $try_server);
                    542:     my $userloadans = &reply('userload',$try_server);
                    543: 
                    544:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    545: 	next; #didn't get a number from the server
                    546:     }
                    547: 
                    548:     my $load;
                    549:     if ($loadans =~ /\d/) {
                    550: 	if ($userloadans =~ /\d/) {
                    551: 	    #both are numbers, pick the bigger one
                    552: 	    $load = ($loadans > $userloadans) ? $loadans 
                    553: 		                              : $userloadans;
1.411     albertel  554: 	} else {
1.784     albertel  555: 	    $load = $loadans;
1.411     albertel  556: 	}
1.784     albertel  557:     } else {
                    558: 	$load = $userloadans;
                    559:     }
                    560: 
                    561:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    562: 	$spare_server = $try_server;
                    563: 	$lowest_load  = $load;
1.370     albertel  564:     }
1.784     albertel  565:     return ($spare_server,$lowest_load);
1.202     matthew   566: }
                    567: # --------------------------------------------- Try to change a user's password
                    568: 
                    569: sub changepass {
1.799     raeburn   570:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   571:     $currentpass = &escape($currentpass);
                    572:     $newpass     = &escape($newpass);
1.799     raeburn   573:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   574: 		       $server);
                    575:     if (! $answer) {
                    576: 	&logthis("No reply on password change request to $server ".
                    577: 		 "by $uname in domain $udom.");
                    578:     } elsif ($answer =~ "^ok") {
                    579:         &logthis("$uname in $udom successfully changed their password ".
                    580: 		 "on $server.");
                    581:     } elsif ($answer =~ "^pwchange_failure") {
                    582: 	&logthis("$uname in $udom was unable to change their password ".
                    583: 		 "on $server.  The action was blocked by either lcpasswd ".
                    584: 		 "or pwchange");
                    585:     } elsif ($answer =~ "^non_authorized") {
                    586:         &logthis("$uname in $udom did not get their password correct when ".
                    587: 		 "attempting to change it on $server.");
                    588:     } elsif ($answer =~ "^auth_mode_error") {
                    589:         &logthis("$uname in $udom attempted to change their password despite ".
                    590: 		 "not being locally or internally authenticated on $server.");
                    591:     } elsif ($answer =~ "^unknown_user") {
                    592:         &logthis("$uname in $udom attempted to change their password ".
                    593: 		 "on $server but were unable to because $server is not ".
                    594: 		 "their home server.");
                    595:     } elsif ($answer =~ "^refused") {
                    596: 	&logthis("$server refused to change $uname in $udom password because ".
                    597: 		 "it was sent an unencrypted request to change the password.");
                    598:     }
                    599:     return $answer;
1.1       albertel  600: }
                    601: 
1.169     harris41  602: # ----------------------- Try to determine user's current authentication scheme
                    603: 
                    604: sub queryauthenticate {
                    605:     my ($uname,$udom)=@_;
1.456     albertel  606:     my $uhome=&homeserver($uname,$udom);
                    607:     if (!$uhome) {
                    608: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    609: 	return 'no_host';
                    610:     }
                    611:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    612:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    613: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  614:     }
1.456     albertel  615:     return $answer;
1.169     harris41  616: }
                    617: 
1.1       albertel  618: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       619: 
1.1       albertel  620: sub authenticate {
                    621:     my ($uname,$upass,$udom)=@_;
1.807     albertel  622:     $upass=&escape($upass);
                    623:     $uname= &LONCAPA::clean_username($uname);
1.836     www       624:     my $uhome=&homeserver($uname,$udom,1);
                    625:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    626: # Maybe the machine was offline and only re-appeared again recently?
                    627:         &reconlonc();
                    628: # One more
                    629: 	my $uhome=&homeserver($uname,$udom,1);
                    630: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    631: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    632: 	}
1.471     albertel  633: 	return 'no_host';
1.1       albertel  634:     }
1.471     albertel  635:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    636:     if ($answer eq 'authorized') {
                    637: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    638: 	return $uhome; 
                    639:     }
                    640:     if ($answer eq 'non_authorized') {
                    641: 	&logthis("User $uname at $udom rejected by $uhome");
                    642: 	return 'no_host'; 
1.9       www       643:     }
1.471     albertel  644:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  645:     return 'no_host';
                    646: }
                    647: 
                    648: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       649: 
1.599     albertel  650: my %homecache;
1.1       albertel  651: sub homeserver {
1.230     stredwic  652:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  653:     my $index="$uname:$udom";
1.426     albertel  654: 
1.599     albertel  655:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  656: 
                    657:     my %servers = &get_servers($udom,'library');
                    658:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  659:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  660: 		 exists($badServerCache{$tryserver}));
1.841     albertel  661: 
                    662: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    663: 	if ($answer eq 'found') {
                    664: 	    delete($badServerCache{$tryserver}); 
                    665: 	    return $homecache{$index}=$tryserver;
                    666: 	} elsif ($answer eq 'no_host') {
                    667: 	    $badServerCache{$tryserver}=1;
                    668: 	}
1.1       albertel  669:     }    
                    670:     return 'no_host';
1.70      www       671: }
                    672: 
                    673: # ------------------------------------- Find the usernames behind a list of IDs
                    674: 
                    675: sub idget {
                    676:     my ($udom,@ids)=@_;
                    677:     my %returnhash=();
                    678:     
1.841     albertel  679:     my %servers = &get_servers($udom,'library');
                    680:     foreach my $tryserver (keys(%servers)) {
                    681: 	my $idlist=join('&',@ids);
                    682: 	$idlist=~tr/A-Z/a-z/; 
                    683: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    684: 	my @answer=();
                    685: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    686: 	    @answer=split(/\&/,$reply);
                    687: 	}                    ;
                    688: 	my $i;
                    689: 	for ($i=0;$i<=$#ids;$i++) {
                    690: 	    if ($answer[$i]) {
                    691: 		$returnhash{$ids[$i]}=$answer[$i];
                    692: 	    } 
                    693: 	}
                    694:     } 
1.70      www       695:     return %returnhash;
                    696: }
                    697: 
                    698: # ------------------------------------- Find the IDs behind a list of usernames
                    699: 
                    700: sub idrget {
                    701:     my ($udom,@unames)=@_;
                    702:     my %returnhash=();
1.800     albertel  703:     foreach my $uname (@unames) {
                    704:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  705:     }
1.70      www       706:     return %returnhash;
                    707: }
                    708: 
                    709: # ------------------------------- Store away a list of names and associated IDs
                    710: 
                    711: sub idput {
                    712:     my ($udom,%ids)=@_;
                    713:     my %servers=();
1.800     albertel  714:     foreach my $uname (keys(%ids)) {
                    715: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    716:         my $uhom=&homeserver($uname,$udom);
1.70      www       717:         if ($uhom ne 'no_host') {
1.800     albertel  718:             my $id=&escape($ids{$uname});
1.70      www       719:             $id=~tr/A-Z/a-z/;
1.800     albertel  720:             my $esc_unam=&escape($uname);
1.70      www       721: 	    if ($servers{$uhom}) {
1.800     albertel  722: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       723:             } else {
1.800     albertel  724:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       725:             }
                    726:         }
1.191     harris41  727:     }
1.800     albertel  728:     foreach my $server (keys(%servers)) {
                    729:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  730:     }
1.344     www       731: }
                    732: 
1.806     raeburn   733: # ------------------------------------------- get items from domain db files   
                    734: 
                    735: sub get_dom {
1.860     raeburn   736:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   737:     my $items='';
                    738:     foreach my $item (@$storearr) {
                    739:         $items.=&escape($item).'&';
                    740:     }
                    741:     $items=~s/\&$//;
1.860     raeburn   742:     if (!$udom) {
                    743:         $udom=$env{'user.domain'};
                    744:         if (defined(&domain($udom,'primary'))) {
                    745:             $uhome=&domain($udom,'primary');
                    746:         } else {
1.874     albertel  747:             undef($uhome);
1.860     raeburn   748:         }
                    749:     } else {
                    750:         if (!$uhome) {
                    751:             if (defined(&domain($udom,'primary'))) {
                    752:                 $uhome=&domain($udom,'primary');
                    753:             }
                    754:         }
                    755:     }
                    756:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   757:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   758:         my %returnhash;
1.875     albertel  759:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   760:             return %returnhash;
                    761:         }
1.806     raeburn   762:         my @pairs=split(/\&/,$rep);
                    763:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    764:             return @pairs;
                    765:         }
                    766:         my $i=0;
                    767:         foreach my $item (@$storearr) {
                    768:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    769:             $i++;
                    770:         }
                    771:         return %returnhash;
                    772:     } else {
1.880     banghart  773:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   774:     }
                    775: }
                    776: 
                    777: # -------------------------------------------- put items in domain db files 
                    778: 
                    779: sub put_dom {
1.860     raeburn   780:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    781:     if (!$udom) {
                    782:         $udom=$env{'user.domain'};
                    783:         if (defined(&domain($udom,'primary'))) {
                    784:             $uhome=&domain($udom,'primary');
                    785:         } else {
1.874     albertel  786:             undef($uhome);
1.860     raeburn   787:         }
                    788:     } else {
                    789:         if (!$uhome) {
                    790:             if (defined(&domain($udom,'primary'))) {
                    791:                 $uhome=&domain($udom,'primary');
                    792:             }
                    793:         }
                    794:     } 
                    795:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   796:         my $items='';
                    797:         foreach my $item (keys(%$storehash)) {
                    798:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    799:         }
                    800:         $items=~s/\&$//;
                    801:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    802:     } else {
1.860     raeburn   803:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   804:     }
                    805: }
                    806: 
1.837     raeburn   807: sub retrieve_inst_usertypes {
                    808:     my ($udom) = @_;
                    809:     my (%returnhash,@order);
1.846     albertel  810:     if (defined(&domain($udom,'primary'))) {
                    811:         my $uhome=&domain($udom,'primary');
1.837     raeburn   812:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    813:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    814:         my @pairs=split(/\&/,$hashitems);
                    815:         foreach my $item (@pairs) {
                    816:             my ($key,$value)=split(/=/,$item,2);
                    817:             $key = &unescape($key);
                    818:             next if ($key =~ /^error: 2 /);
                    819:             $returnhash{$key}=&thaw_unescape($value);
                    820:         }
                    821:         my @esc_order = split(/\&/,$orderitems);
                    822:         foreach my $item (@esc_order) {
                    823:             push(@order,&unescape($item));
                    824:         }
                    825:     } else {
                    826:         &logthis("get_dom failed - no primary domain server for $udom");
                    827:     }
                    828:     return (\%returnhash,\@order);
                    829: }
                    830: 
1.868     raeburn   831: sub is_domainimage {
                    832:     my ($url) = @_;
                    833:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    834:         if (&domain($1) ne '') {
                    835:             return '1';
                    836:         }
                    837:     }
                    838:     return;
                    839: }
                    840: 
1.344     www       841: # --------------------------------------------------- Assign a key to a student
                    842: 
                    843: sub assign_access_key {
1.364     www       844: #
                    845: # a valid key looks like uname:udom#comments
                    846: # comments are being appended
                    847: #
1.498     www       848:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    849:     $kdom=
1.620     albertel  850:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       851:     $knum=
1.620     albertel  852:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       853:     $cdom=
1.620     albertel  854:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       855:     $cnum=
1.620     albertel  856:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    857:     $udom=$env{'user.name'} unless (defined($udom));
                    858:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       859:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       860:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  861:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       862:                                                   # assigned to this person
                    863:                                                   # - this should not happen,
1.345     www       864:                                                   # unless something went wrong
                    865:                                                   # the first time around
                    866: # ready to assign
1.364     www       867:         $logentry=$1.'; '.$logentry;
1.496     www       868:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       869:                                                  $kdom,$knum) eq 'ok') {
1.345     www       870: # key now belongs to user
1.346     www       871: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       872:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    873:                 &appenv('environment.'.$envkey => $ckey);
                    874:                 return 'ok';
                    875:             } else {
                    876:                 return 
                    877:   'error: Count not permanently assign key, will need to be re-entered later.';
                    878: 	    }
                    879:         } else {
                    880:             return 'error: Could not assign key, try again later.';
                    881:         }
1.364     www       882:     } elsif (!$existing{$ckey}) {
1.345     www       883: # the key does not exist
                    884: 	return 'error: The key does not exist';
                    885:     } else {
                    886: # the key is somebody else's
                    887: 	return 'error: The key is already in use';
                    888:     }
1.344     www       889: }
                    890: 
1.364     www       891: # ------------------------------------------ put an additional comment on a key
                    892: 
                    893: sub comment_access_key {
                    894: #
                    895: # a valid key looks like uname:udom#comments
                    896: # comments are being appended
                    897: #
                    898:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    899:     $cdom=
1.620     albertel  900:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       901:     $cnum=
1.620     albertel  902:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       903:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    904:     if ($existing{$ckey}) {
                    905:         $existing{$ckey}.='; '.$logentry;
                    906: # ready to assign
1.367     www       907:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       908:                                                  $cdom,$cnum) eq 'ok') {
                    909: 	    return 'ok';
                    910:         } else {
                    911: 	    return 'error: Count not store comment.';
                    912:         }
                    913:     } else {
                    914: # the key does not exist
                    915: 	return 'error: The key does not exist';
                    916:     }
                    917: }
                    918: 
1.344     www       919: # ------------------------------------------------------ Generate a set of keys
                    920: 
                    921: sub generate_access_keys {
1.364     www       922:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       923:     $cdom=
1.620     albertel  924:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       925:     $cnum=
1.620     albertel  926:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       927:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       928:     unless (($cdom) && ($cnum)) { return 0; }
                    929:     if ($number>10000) { return 0; }
                    930:     sleep(2); # make sure don't get same seed twice
                    931:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    932:     my $total=0;
                    933:     for (my $i=1;$i<=$number;$i++) {
                    934:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    935:                   sprintf("%lx",int(100000*rand)).'-'.
                    936:                   sprintf("%lx",int(100000*rand));
                    937:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    938:        $newkey=~s/0/h/g; # and also 0 and O
                    939:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    940:        if ($existing{$newkey}) {
                    941:            $i--;
                    942:        } else {
1.364     www       943: 	  if (&put('accesskeys',
                    944:               { $newkey => '# generated '.localtime().
1.620     albertel  945:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       946:                            '; '.$logentry },
                    947: 		   $cdom,$cnum) eq 'ok') {
1.344     www       948:               $total++;
                    949: 	  }
                    950:        }
                    951:     }
1.620     albertel  952:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       953:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    954:     return $total;
                    955: }
                    956: 
                    957: # ------------------------------------------------------- Validate an accesskey
                    958: 
                    959: sub validate_access_key {
                    960:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    961:     $cdom=
1.620     albertel  962:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       963:     $cnum=
1.620     albertel  964:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    965:     $udom=$env{'user.domain'} unless (defined($udom));
                    966:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       967:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  968:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       969: }
                    970: 
                    971: # ------------------------------------- Find the section of student in a course
1.652     albertel  972: sub devalidate_getsection_cache {
                    973:     my ($udom,$unam,$courseid)=@_;
                    974:     my $hashid="$udom:$unam:$courseid";
                    975:     &devalidate_cache_new('getsection',$hashid);
                    976: }
1.298     matthew   977: 
1.815     albertel  978: sub courseid_to_courseurl {
                    979:     my ($courseid) = @_;
                    980:     #already url style courseid
                    981:     return $courseid if ($courseid =~ m{^/});
                    982: 
                    983:     if (exists($env{'course.'.$courseid.'.num'})) {
                    984: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    985: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    986: 	return "/$cdom/$cnum";
                    987:     }
                    988: 
                    989:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    990:     if (exists($courseinfo{'num'})) {
                    991: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    992:     }
                    993: 
                    994:     return undef;
                    995: }
                    996: 
1.298     matthew   997: sub getsection {
                    998:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  999:     my $cachetime=1800;
1.551     albertel 1000: 
                   1001:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1002:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1003:     if (defined($cached)) { return $result; }
                   1004: 
1.298     matthew  1005:     my %Pending; 
                   1006:     my %Expired;
                   1007:     #
                   1008:     # Each role can either have not started yet (pending), be active, 
                   1009:     #    or have expired.
                   1010:     #
                   1011:     # If there is an active role, we are done.
                   1012:     #
                   1013:     # If there is more than one role which has not started yet, 
                   1014:     #     choose the one which will start sooner
                   1015:     # If there is one role which has not started yet, return it.
                   1016:     #
                   1017:     # If there is more than one expired role, choose the one which ended last.
                   1018:     # If there is a role which has expired, return it.
                   1019:     #
1.815     albertel 1020:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1021:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1022:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1023:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1024:         my $section=$1;
                   1025:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1026:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1027:         my $now=time;
1.548     albertel 1028:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1029:             $Expired{$end}=$section;
                   1030:             next;
                   1031:         }
1.548     albertel 1032:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1033:             $Pending{$start}=$section;
                   1034:             next;
                   1035:         }
1.599     albertel 1036:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1037:     }
                   1038:     #
                   1039:     # Presumedly there will be few matching roles from the above
                   1040:     # loop and the sorting time will be negligible.
                   1041:     if (scalar(keys(%Pending))) {
                   1042:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1043:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1044:     } 
                   1045:     if (scalar(keys(%Expired))) {
                   1046:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1047:         my $time = pop(@sorted);
1.599     albertel 1048:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1049:     }
1.599     albertel 1050:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1051: }
1.70      www      1052: 
1.599     albertel 1053: sub save_cache {
                   1054:     &purge_remembered();
1.722     albertel 1055:     #&Apache::loncommon::validate_page();
1.620     albertel 1056:     undef(%env);
1.780     albertel 1057:     undef($env_loaded);
1.599     albertel 1058: }
1.452     albertel 1059: 
1.599     albertel 1060: my $to_remember=-1;
                   1061: my %remembered;
                   1062: my %accessed;
                   1063: my $kicks=0;
                   1064: my $hits=0;
1.849     albertel 1065: sub make_key {
                   1066:     my ($name,$id) = @_;
1.872     albertel 1067:     if (length($id) > 65 
                   1068: 	&& length(&escape($id)) > 200) {
                   1069: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1070:     }
1.849     albertel 1071:     return &escape($name.':'.$id);
                   1072: }
                   1073: 
1.599     albertel 1074: sub devalidate_cache_new {
                   1075:     my ($name,$id,$debug) = @_;
                   1076:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1077:     $id=&make_key($name,$id);
1.599     albertel 1078:     $memcache->delete($id);
                   1079:     delete($remembered{$id});
                   1080:     delete($accessed{$id});
                   1081: }
                   1082: 
                   1083: sub is_cached_new {
                   1084:     my ($name,$id,$debug) = @_;
1.849     albertel 1085:     $id=&make_key($name,$id);
1.599     albertel 1086:     if (exists($remembered{$id})) {
                   1087: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1088: 	$accessed{$id}=[&gettimeofday()];
                   1089: 	$hits++;
                   1090: 	return ($remembered{$id},1);
                   1091:     }
                   1092:     my $value = $memcache->get($id);
                   1093:     if (!(defined($value))) {
                   1094: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1095: 	return (undef,undef);
1.416     albertel 1096:     }
1.599     albertel 1097:     if ($value eq '__undef__') {
                   1098: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1099: 	$value=undef;
                   1100:     }
                   1101:     &make_room($id,$value,$debug);
                   1102:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1103:     return ($value,1);
                   1104: }
                   1105: 
                   1106: sub do_cache_new {
                   1107:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1108:     $id=&make_key($name,$id);
1.599     albertel 1109:     my $setvalue=$value;
                   1110:     if (!defined($setvalue)) {
                   1111: 	$setvalue='__undef__';
                   1112:     }
1.623     albertel 1113:     if (!defined($time) ) {
                   1114: 	$time=600;
                   1115:     }
1.599     albertel 1116:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.872     albertel 1117:     if (!($memcache->set($id,$setvalue,$time))) {
                   1118: 	&logthis("caching of id -> $id  failed");
                   1119:     }
1.600     albertel 1120:     # need to make a copy of $value
                   1121:     #&make_room($id,$value,$debug);
1.599     albertel 1122:     return $value;
                   1123: }
                   1124: 
                   1125: sub make_room {
                   1126:     my ($id,$value,$debug)=@_;
                   1127:     $remembered{$id}=$value;
                   1128:     if ($to_remember<0) { return; }
                   1129:     $accessed{$id}=[&gettimeofday()];
                   1130:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1131:     my $to_kick;
                   1132:     my $max_time=0;
                   1133:     foreach my $other (keys(%accessed)) {
                   1134: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1135: 	    $to_kick=$other;
                   1136: 	    $max_time=&tv_interval($accessed{$other});
                   1137: 	}
                   1138:     }
                   1139:     delete($remembered{$to_kick});
                   1140:     delete($accessed{$to_kick});
                   1141:     $kicks++;
                   1142:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1143:     return;
                   1144: }
                   1145: 
1.599     albertel 1146: sub purge_remembered {
1.604     albertel 1147:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1148:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1149:     undef(%remembered);
                   1150:     undef(%accessed);
1.428     albertel 1151: }
1.70      www      1152: # ------------------------------------- Read an entry from a user's environment
                   1153: 
                   1154: sub userenvironment {
                   1155:     my ($udom,$unam,@what)=@_;
                   1156:     my %returnhash=();
                   1157:     my @answer=split(/\&/,
                   1158:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1159:                       &homeserver($unam,$udom)));
                   1160:     my $i;
                   1161:     for ($i=0;$i<=$#what;$i++) {
                   1162: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1163:     }
                   1164:     return %returnhash;
1.1       albertel 1165: }
                   1166: 
1.617     albertel 1167: # ---------------------------------------------------------- Get a studentphoto
                   1168: sub studentphoto {
                   1169:     my ($udom,$unam,$ext) = @_;
                   1170:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1171:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1172:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1173:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1174:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1175:             } else {
                   1176:                 my ($result,$perm_reqd)=
1.707     albertel 1177: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1178:                 if ($result eq 'ok') {
                   1179:                     if (!($perm_reqd eq 'yes')) {
                   1180:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1181:                     }
                   1182:                 }
                   1183:             }
                   1184:         }
                   1185:     } else {
                   1186:         my ($result,$perm_reqd) = 
1.707     albertel 1187: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1188:         if ($result eq 'ok') {
                   1189:             if (!($perm_reqd eq 'yes')) {
                   1190:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1191:             }
                   1192:         }
                   1193:     }
                   1194:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1195: }
                   1196: 
                   1197: sub retrievestudentphoto {
                   1198:     my ($udom,$unam,$ext,$type) = @_;
                   1199:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1200:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1201:     if ($ret eq 'ok') {
                   1202:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1203:         if ($type eq 'thumbnail') {
                   1204:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1205:         }
                   1206:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1207:         return $tokenurl;
                   1208:     } else {
                   1209:         if ($type eq 'thumbnail') {
                   1210:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1211:         } else { 
                   1212:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1213:         }
1.617     albertel 1214:     }
                   1215: }
                   1216: 
1.263     www      1217: # -------------------------------------------------------------------- New chat
                   1218: 
                   1219: sub chatsend {
1.724     raeburn  1220:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1221:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1222:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1223:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1224:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1225: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1226: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1227: }
                   1228: 
                   1229: # ------------------------------------------ Find current version of a resource
                   1230: 
                   1231: sub getversion {
                   1232:     my $fname=&clutter(shift);
                   1233:     unless ($fname=~/^\/res\//) { return -1; }
                   1234:     return &currentversion(&filelocation('',$fname));
                   1235: }
                   1236: 
                   1237: sub currentversion {
                   1238:     my $fname=shift;
1.599     albertel 1239:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1240:     if (defined($cached)) { return $result; }
1.292     www      1241:     my $author=$fname;
                   1242:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1243:     my ($udom,$uname)=split(/\//,$author);
                   1244:     my $home=homeserver($uname,$udom);
                   1245:     if ($home eq 'no_host') { 
                   1246:         return -1; 
                   1247:     }
                   1248:     my $answer=reply("currentversion:$fname",$home);
                   1249:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1250: 	return -1;
                   1251:     }
1.599     albertel 1252:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1253: }
                   1254: 
1.1       albertel 1255: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1256: 
1.1       albertel 1257: sub subscribe {
                   1258:     my $fname=shift;
1.761     raeburn  1259:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1260:     $fname=~s/[\n\r]//g;
1.1       albertel 1261:     my $author=$fname;
                   1262:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1263:     my ($udom,$uname)=split(/\//,$author);
                   1264:     my $home=homeserver($uname,$udom);
1.335     albertel 1265:     if ($home eq 'no_host') {
                   1266:         return 'not_found';
1.1       albertel 1267:     }
                   1268:     my $answer=reply("sub:$fname",$home);
1.64      www      1269:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1270: 	$answer.=' by '.$home;
                   1271:     }
1.1       albertel 1272:     return $answer;
                   1273: }
                   1274:     
1.8       www      1275: # -------------------------------------------------------------- Replicate file
                   1276: 
                   1277: sub repcopy {
                   1278:     my $filename=shift;
1.23      www      1279:     $filename=~s/\/+/\//g;
1.607     raeburn  1280:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1281:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1282:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1283: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1284: 	return &repcopy_userfile($filename);
                   1285:     }
1.532     albertel 1286:     $filename=~s/[\n\r]//g;
1.8       www      1287:     my $transname="$filename.in.transfer";
1.828     www      1288: # FIXME: this should flock
1.607     raeburn  1289:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1290:     my $remoteurl=subscribe($filename);
1.64      www      1291:     if ($remoteurl =~ /^con_lost by/) {
                   1292: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1293:            return 'unavailable';
1.8       www      1294:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1295: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1296: 	   return 'not_found';
1.64      www      1297:     } elsif ($remoteurl =~ /^rejected by/) {
                   1298: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1299:            return 'forbidden';
1.20      www      1300:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1301:            return 'ok';
1.8       www      1302:     } else {
1.290     www      1303:         my $author=$filename;
                   1304:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1305:         my ($udom,$uname)=split(/\//,$author);
                   1306:         my $home=homeserver($uname,$udom);
                   1307:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1308:            my @parts=split(/\//,$filename);
                   1309:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1310:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1311:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1312: 	       return 'bad_request';
1.8       www      1313:            }
                   1314:            my $count;
                   1315:            for ($count=5;$count<$#parts;$count++) {
                   1316:                $path.="/$parts[$count]";
                   1317:                if ((-e $path)!=1) {
                   1318: 		   mkdir($path,0777);
                   1319:                }
                   1320:            }
                   1321:            my $ua=new LWP::UserAgent;
                   1322:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1323:            my $response=$ua->request($request,$transname);
                   1324:            if ($response->is_error()) {
                   1325: 	       unlink($transname);
                   1326:                my $message=$response->status_line;
1.672     albertel 1327:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1328:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1329:                return 'unavailable';
1.8       www      1330:            } else {
1.16      www      1331: 	       if ($remoteurl!~/\.meta$/) {
                   1332:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1333:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1334:                   if ($mresponse->is_error()) {
                   1335: 		      unlink($filename.'.meta');
                   1336:                       &logthis(
1.672     albertel 1337:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1338:                   }
                   1339: 	       }
1.8       www      1340:                rename($transname,$filename);
1.607     raeburn  1341:                return 'ok';
1.8       www      1342:            }
1.290     www      1343:        }
1.8       www      1344:     }
1.330     www      1345: }
                   1346: 
                   1347: # ------------------------------------------------ Get server side include body
                   1348: sub ssi_body {
1.381     albertel 1349:     my ($filelink,%form)=@_;
1.606     matthew  1350:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1351:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1352:     }
1.330     www      1353:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1354:                                      &ssi($filelink,%form));
1.778     albertel 1355:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1356:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1357:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1358:     return $output;
1.8       www      1359: }
                   1360: 
1.15      www      1361: # --------------------------------------------------------- Server Side Include
                   1362: 
1.782     albertel 1363: sub absolute_url {
                   1364:     my ($host_name) = @_;
                   1365:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1366:     if ($host_name eq '') {
                   1367: 	$host_name = $ENV{'SERVER_NAME'};
                   1368:     }
                   1369:     return $protocol.$host_name;
                   1370: }
                   1371: 
1.15      www      1372: sub ssi {
                   1373: 
1.23      www      1374:     my ($fn,%form)=@_;
1.15      www      1375: 
                   1376:     my $ua=new LWP::UserAgent;
1.23      www      1377:     
                   1378:     my $request;
1.711     albertel 1379: 
                   1380:     $form{'no_update_last_known'}=1;
                   1381: 
1.23      www      1382:     if (%form) {
1.782     albertel 1383:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1384:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1385:     } else {
1.782     albertel 1386:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1387:     }
                   1388: 
1.15      www      1389:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1390:     my $response=$ua->request($request);
                   1391: 
1.324     www      1392:     return $response->content;
                   1393: }
                   1394: 
                   1395: sub externalssi {
                   1396:     my ($url)=@_;
                   1397:     my $ua=new LWP::UserAgent;
                   1398:     my $request=new HTTP::Request('GET',$url);
                   1399:     my $response=$ua->request($request);
1.15      www      1400:     return $response->content;
                   1401: }
1.254     www      1402: 
1.492     albertel 1403: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1404: 
                   1405: sub allowuploaded {
                   1406:     my ($srcurl,$url)=@_;
                   1407:     $url=&clutter(&declutter($url));
                   1408:     my $dir=$url;
                   1409:     $dir=~s/\/[^\/]+$//;
                   1410:     my %httpref=();
                   1411:     my $httpurl=&hreflocation('',$url);
                   1412:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1413:     &Apache::lonnet::appenv(%httpref);
1.254     www      1414: }
1.477     raeburn  1415: 
1.478     albertel 1416: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1417: # input: action, courseID, current domain, intended
1.637     raeburn  1418: #        path to file, source of file, instruction to parse file for objects,
                   1419: #        ref to hash for embedded objects,
                   1420: #        ref to hash for codebase of java objects.
                   1421: #
1.485     raeburn  1422: # output: url to file (if action was uploaddoc), 
                   1423: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1424: #
1.478     albertel 1425: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1426: # course.
1.477     raeburn  1427: #
1.478     albertel 1428: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1429: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1430: #          course's home server.
1.477     raeburn  1431: #
1.478     albertel 1432: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1433: #          be copied from $source (current location) to 
                   1434: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1435: #         and will then be copied to
                   1436: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1437: #         course's home server.
1.485     raeburn  1438: #
1.481     raeburn  1439: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1440: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1441: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1442: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1443: #         in course's home server.
1.637     raeburn  1444: #
1.477     raeburn  1445: 
                   1446: sub process_coursefile {
1.638     albertel 1447:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1448:     my $fetchresult;
1.638     albertel 1449:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1450:     if ($action eq 'propagate') {
1.638     albertel 1451:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1452: 			     $home);
1.481     raeburn  1453:     } else {
1.477     raeburn  1454:         my $fpath = '';
                   1455:         my $fname = $file;
1.478     albertel 1456:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1457:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1458:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1459:         if ($action eq 'copy') {
                   1460:             if ($source eq '') {
                   1461:                 $fetchresult = 'no source file';
                   1462:                 return $fetchresult;
                   1463:             } else {
                   1464:                 my $destination = $filepath.'/'.$fname;
                   1465:                 rename($source,$destination);
                   1466:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1467:                                  $home);
1.481     raeburn  1468:             }
                   1469:         } elsif ($action eq 'uploaddoc') {
                   1470:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1471:             print $fh $env{'form.'.$source};
1.481     raeburn  1472:             close($fh);
1.637     raeburn  1473:             if ($parser eq 'parse') {
                   1474:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1475:                 unless ($parse_result eq 'ok') {
                   1476:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1477:                 }
                   1478:             }
1.477     raeburn  1479:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1480:                                  $home);
1.481     raeburn  1481:             if ($fetchresult eq 'ok') {
                   1482:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1483:             } else {
                   1484:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1485:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1486:                 return '/adm/notfound.html';
                   1487:             }
1.477     raeburn  1488:         }
                   1489:     }
1.485     raeburn  1490:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1491:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1492:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1493:     }
                   1494:     return $fetchresult;
                   1495: }
                   1496: 
1.637     raeburn  1497: sub build_filepath {
                   1498:     my ($fpath) = @_;
                   1499:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1500:     unless ($fpath eq '') {
                   1501:         my @parts=split('/',$fpath);
                   1502:         foreach my $part (@parts) {
                   1503:             $filepath.= '/'.$part;
                   1504:             if ((-e $filepath)!=1) {
                   1505:                 mkdir($filepath,0777);
                   1506:             }
                   1507:         }
                   1508:     }
                   1509:     return $filepath;
                   1510: }
                   1511: 
                   1512: sub store_edited_file {
1.638     albertel 1513:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1514:     my $file = $primary_url;
                   1515:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1516:     my $fpath = '';
                   1517:     my $fname = $file;
                   1518:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1519:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1520:     my $filepath = &build_filepath($fpath);
                   1521:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1522:     print $fh $content;
                   1523:     close($fh);
1.638     albertel 1524:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1525:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1526: 			  $home);
1.637     raeburn  1527:     if ($$fetchresult eq 'ok') {
                   1528:         return '/uploaded/'.$fpath.'/'.$fname;
                   1529:     } else {
1.638     albertel 1530:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1531: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1532:         return '/adm/notfound.html';
                   1533:     }
                   1534: }
                   1535: 
1.531     albertel 1536: sub clean_filename {
1.831     albertel 1537:     my ($fname,$args)=@_;
1.315     www      1538: # Replace Windows backslashes by forward slashes
1.257     www      1539:     $fname=~s/\\/\//g;
1.831     albertel 1540:     if (!$args->{'keep_path'}) {
                   1541:         # Get rid of everything but the actual filename
                   1542: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1543:     }
1.315     www      1544: # Replace spaces by underscores
                   1545:     $fname=~s/\s+/\_/g;
                   1546: # Replace all other weird characters by nothing
1.831     albertel 1547:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1548: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1549: # numbers
                   1550:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1551:     return $fname;
                   1552: }
                   1553: 
1.608     albertel 1554: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1555: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1556: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1557: #        $coursedoc - if true up to the current course
                   1558: #                     if false
                   1559: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1560: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1561: #        $allfiles - reference to hash for embedded objects
                   1562: #        $codebase - reference to hash for codebase of java objects
                   1563: #        $desuname - username for permanent storage of uploaded file
                   1564: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1565: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1566: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1567: # 
1.686     albertel 1568: # output: url of file in userspace, or error: <message> 
                   1569: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1570: 
                   1571: 
1.531     albertel 1572: sub userfileupload {
1.860     raeburn  1573:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1574:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1575:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1576:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1577:     $fname=&clean_filename($fname);
1.315     www      1578: # See if there is anything left
1.257     www      1579:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1580:     chop($env{'form.'.$formname});
1.523     raeburn  1581:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1582:         my $now = time;
                   1583:         my $filepath = 'tmp/helprequests/'.$now;
                   1584:         my @parts=split(/\//,$filepath);
                   1585:         my $fullpath = $perlvar{'lonDaemons'};
                   1586:         for (my $i=0;$i<@parts;$i++) {
                   1587:             $fullpath .= '/'.$parts[$i];
                   1588:             if ((-e $fullpath)!=1) {
                   1589:                 mkdir($fullpath,0777);
                   1590:             }
                   1591:         }
                   1592:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1593:         print $fh $env{'form.'.$formname};
1.523     raeburn  1594:         close($fh);
1.741     raeburn  1595:         return $fullpath.'/'.$fname;
                   1596:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1597:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1598:                        '_'.$env{'user.domain'}.'/pending';
                   1599:         my @parts=split(/\//,$filepath);
                   1600:         my $fullpath = $perlvar{'lonDaemons'};
                   1601:         for (my $i=0;$i<@parts;$i++) {
                   1602:             $fullpath .= '/'.$parts[$i];
                   1603:             if ((-e $fullpath)!=1) {
                   1604:                 mkdir($fullpath,0777);
                   1605:             }
                   1606:         }
                   1607:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1608:         print $fh $env{'form.'.$formname};
                   1609:         close($fh);
                   1610:         return $fullpath.'/'.$fname;
1.523     raeburn  1611:     }
1.719     banghart 1612:     
1.258     www      1613: # Create the directory if not present
1.493     albertel 1614:     $fname="$subdir/$fname";
1.259     www      1615:     if ($coursedoc) {
1.638     albertel 1616: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1617: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1618:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1619:             return &finishuserfileupload($docuname,$docudom,
                   1620: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1621: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1622:         } else {
1.620     albertel 1623:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1624:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1625: 				       $fname,$formname,$parser,
                   1626: 				       $allfiles,$codebase);
1.481     raeburn  1627:         }
1.719     banghart 1628:     } elsif (defined($destuname)) {
                   1629:         my $docuname=$destuname;
                   1630:         my $docudom=$destudom;
1.860     raeburn  1631: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1632: 				     $parser,$allfiles,$codebase,
                   1633:                                      $thumbwidth,$thumbheight);
1.719     banghart 1634:         
1.259     www      1635:     } else {
1.638     albertel 1636:         my $docuname=$env{'user.name'};
                   1637:         my $docudom=$env{'user.domain'};
1.714     raeburn  1638:         if (exists($env{'form.group'})) {
                   1639:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1640:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1641:         }
1.860     raeburn  1642: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1643: 				     $parser,$allfiles,$codebase,
                   1644:                                      $thumbwidth,$thumbheight);
1.259     www      1645:     }
1.271     www      1646: }
                   1647: 
                   1648: sub finishuserfileupload {
1.860     raeburn  1649:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1650:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1651:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1652:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1653:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1654:     $file=$fname;
                   1655:     if ($fname=~m|/|) {
                   1656:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1657: 	$path.=$fnamepath.'/';
                   1658:     }
1.259     www      1659:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1660:     my $count;
                   1661:     for ($count=4;$count<=$#parts;$count++) {
                   1662:         $filepath.="/$parts[$count]";
                   1663:         if ((-e $filepath)!=1) {
                   1664: 	    mkdir($filepath,0777);
                   1665:         }
                   1666:     }
                   1667: # Save the file
                   1668:     {
1.701     albertel 1669: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1670: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1671: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1672: 	    return '/adm/notfound.html';
                   1673: 	}
                   1674: 	if (!print FH ($env{'form.'.$formname})) {
                   1675: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1676: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1677: 	    return '/adm/notfound.html';
                   1678: 	}
1.570     albertel 1679: 	close(FH);
1.258     www      1680:     }
1.637     raeburn  1681:     if ($parser eq 'parse') {
1.638     albertel 1682:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1683: 						   $codebase);
1.637     raeburn  1684:         unless ($parse_result eq 'ok') {
1.638     albertel 1685:             &logthis('Failed to parse '.$filepath.$file.
                   1686: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1687:         }
                   1688:     }
1.860     raeburn  1689:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1690:         my $input = $filepath.'/'.$file;
                   1691:         my $output = $filepath.'/'.'tn-'.$file;
                   1692:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1693:         system("convert -sample $thumbsize $input $output");
                   1694:         if (-e $filepath.'/'.'tn-'.$file) {
                   1695:             $fetchthumb  = 1; 
                   1696:         }
                   1697:     }
1.858     raeburn  1698:  
1.259     www      1699: # Notify homeserver to grep it
                   1700: #
1.638     albertel 1701:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1702:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1703:     if ($fetchresult eq 'ok') {
1.860     raeburn  1704:         if ($fetchthumb) {
                   1705:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1706:             if ($thumbresult ne 'ok') {
                   1707:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1708:                          $docuhome.': '.$thumbresult);
                   1709:             }
                   1710:         }
1.259     www      1711: #
1.258     www      1712: # Return the URL to it
1.494     albertel 1713:         return '/uploaded/'.$path.$file;
1.263     www      1714:     } else {
1.494     albertel 1715:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1716: 		 ': '.$fetchresult);
1.263     www      1717:         return '/adm/notfound.html';
1.858     raeburn  1718:     }
1.493     albertel 1719: }
                   1720: 
1.637     raeburn  1721: sub extract_embedded_items {
1.648     raeburn  1722:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1723:     my @state = ();
                   1724:     my %javafiles = (
                   1725:                       codebase => '',
                   1726:                       code => '',
                   1727:                       archive => ''
                   1728:                     );
                   1729:     my %mediafiles = (
                   1730:                       src => '',
                   1731:                       movie => '',
                   1732:                      );
1.648     raeburn  1733:     my $p;
                   1734:     if ($content) {
                   1735:         $p = HTML::LCParser->new($content);
                   1736:     } else {
                   1737:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1738:     }
1.641     albertel 1739:     while (my $t=$p->get_token()) {
1.640     albertel 1740: 	if ($t->[0] eq 'S') {
                   1741: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1742: 	    push (@state, $tagname);
1.648     raeburn  1743:             if (lc($tagname) eq 'allow') {
                   1744:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1745:             }
1.640     albertel 1746: 	    if (lc($tagname) eq 'img') {
                   1747: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1748: 	    }
1.645     raeburn  1749:             if (lc($tagname) eq 'script') {
                   1750:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1751:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1752:                 } else {
                   1753:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1754:                 }
                   1755:             }
                   1756:             if (lc($tagname) eq 'link') {
                   1757:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1758:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1759:                 }
                   1760:             }
1.640     albertel 1761: 	    if (lc($tagname) eq 'object' ||
                   1762: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1763: 		foreach my $item (keys(%javafiles)) {
                   1764: 		    $javafiles{$item} = '';
                   1765: 		}
                   1766: 	    }
                   1767: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1768: 		my $name = lc($attr->{'name'});
                   1769: 		foreach my $item (keys(%javafiles)) {
                   1770: 		    if ($name eq $item) {
                   1771: 			$javafiles{$item} = $attr->{'value'};
                   1772: 			last;
                   1773: 		    }
                   1774: 		}
                   1775: 		foreach my $item (keys(%mediafiles)) {
                   1776: 		    if ($name eq $item) {
                   1777: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1778: 			last;
                   1779: 		    }
                   1780: 		}
                   1781: 	    }
                   1782: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1783: 		foreach my $item (keys(%javafiles)) {
                   1784: 		    if ($attr->{$item}) {
                   1785: 			$javafiles{$item} = $attr->{$item};
                   1786: 			last;
                   1787: 		    }
                   1788: 		}
                   1789: 		foreach my $item (keys(%mediafiles)) {
                   1790: 		    if ($attr->{$item}) {
                   1791: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1792: 			last;
                   1793: 		    }
                   1794: 		}
                   1795: 	    }
                   1796: 	} elsif ($t->[0] eq 'E') {
                   1797: 	    my ($tagname) = ($t->[1]);
                   1798: 	    if ($javafiles{'codebase'} ne '') {
                   1799: 		$javafiles{'codebase'} .= '/';
                   1800: 	    }  
                   1801: 	    if (lc($tagname) eq 'applet' ||
                   1802: 		lc($tagname) eq 'object' ||
                   1803: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1804: 		) {
                   1805: 		foreach my $item (keys(%javafiles)) {
                   1806: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1807: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1808: 			&add_filetype($allfiles,$file,$item);
                   1809: 		    }
                   1810: 		}
                   1811: 	    } 
                   1812: 	    pop @state;
                   1813: 	}
                   1814:     }
1.637     raeburn  1815:     return 'ok';
                   1816: }
                   1817: 
1.639     albertel 1818: sub add_filetype {
                   1819:     my ($allfiles,$file,$type)=@_;
                   1820:     if (exists($allfiles->{$file})) {
                   1821: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1822: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1823: 	}
                   1824:     } else {
                   1825: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1826:     }
                   1827: }
                   1828: 
1.493     albertel 1829: sub removeuploadedurl {
                   1830:     my ($url)=@_;
                   1831:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1832:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1833: }
                   1834: 
                   1835: sub removeuserfile {
                   1836:     my ($docuname,$docudom,$fname)=@_;
                   1837:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1838:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1839:     if ($result eq 'ok') {
                   1840:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1841:             my $metafile = $fname.'.meta';
                   1842:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1843: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1844:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1845:             my $sqlresult = 
1.823     albertel 1846:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1847:                                         'portfolio_metadata',$group,
                   1848:                                         'delete');
1.798     raeburn  1849:         }
                   1850:     }
                   1851:     return $result;
1.257     www      1852: }
1.15      www      1853: 
1.530     albertel 1854: sub mkdiruserfile {
                   1855:     my ($docuname,$docudom,$dir)=@_;
                   1856:     my $home=&homeserver($docuname,$docudom);
                   1857:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1858: }
                   1859: 
1.531     albertel 1860: sub renameuserfile {
                   1861:     my ($docuname,$docudom,$old,$new)=@_;
                   1862:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1863:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1864:                         &escape("$old").':'.&escape("$new"),$home);
                   1865:     if ($result eq 'ok') {
                   1866:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1867:             my $oldmeta = $old.'.meta';
                   1868:             my $newmeta = $new.'.meta';
                   1869:             my $metaresult = 
                   1870:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1871: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1872:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1873:             my $sqlresult = 
1.823     albertel 1874:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1875:                                         'portfolio_metadata',$group,
                   1876:                                         'delete');
1.798     raeburn  1877:         }
                   1878:     }
                   1879:     return $result;
1.531     albertel 1880: }
                   1881: 
1.14      www      1882: # ------------------------------------------------------------------------- Log
                   1883: 
                   1884: sub log {
                   1885:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1886:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1887: }
                   1888: 
                   1889: # ------------------------------------------------------------------ Course Log
1.352     www      1890: #
                   1891: # This routine flushes several buffers of non-mission-critical nature
                   1892: #
1.157     www      1893: 
                   1894: sub flushcourselogs {
1.352     www      1895:     &logthis('Flushing log buffers');
                   1896: #
                   1897: # course logs
                   1898: # This is a log of all transactions in a course, which can be used
                   1899: # for data mining purposes
                   1900: #
                   1901: # It also collects the courseid database, which lists last transaction
                   1902: # times and course titles for all courseids
                   1903: #
                   1904:     my %courseidbuffer=();
1.800     albertel 1905:     foreach my $crsid (keys %courselogs) {
1.352     www      1906:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1907: 		          &escape($courselogs{$crsid}),
                   1908: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1909: 	    delete $courselogs{$crsid};
                   1910:         } else {
                   1911:             &logthis('Failed to flush log buffer for '.$crsid);
                   1912:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1913:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1914:                         " exceeded maximum size, deleting.</font>");
                   1915:                delete $courselogs{$crsid};
                   1916:             }
1.352     www      1917:         }
                   1918:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1919:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1920: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1921:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1922:         } else {
                   1923:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1924: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1925:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1926:         }
1.191     harris41 1927:     }
1.352     www      1928: #
                   1929: # Write course id database (reverse lookup) to homeserver of courses 
                   1930: # Is used in pickcourse
                   1931: #
1.840     albertel 1932:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1933:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1934: 		     $crs_home);
1.352     www      1935:     }
                   1936: #
                   1937: # File accesses
                   1938: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1939: #
1.449     matthew  1940:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1941:         if ($entry =~ /___count$/) {
                   1942:             my ($dom,$name);
1.807     albertel 1943:             ($dom,$name,undef)=
1.811     albertel 1944: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1945:             if (! defined($dom) || $dom eq '' || 
                   1946:                 ! defined($name) || $name eq '') {
1.620     albertel 1947:                 my $cid = $env{'request.course.id'};
                   1948:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1949:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1950:             }
1.450     matthew  1951:             my $value = $accesshash{$entry};
                   1952:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1953:             my %temphash=($url => $value);
1.449     matthew  1954:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1955:             if ($result eq 'ok') {
                   1956:                 delete $accesshash{$entry};
                   1957:             } elsif ($result eq 'unknown_cmd') {
                   1958:                 # Target server has old code running on it.
1.450     matthew  1959:                 my %temphash=($entry => $value);
1.449     matthew  1960:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1961:                     delete $accesshash{$entry};
                   1962:                 }
                   1963:             }
                   1964:         } else {
1.811     albertel 1965:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1966:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1967:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1968:                 delete $accesshash{$entry};
                   1969:             }
1.185     www      1970:         }
1.191     harris41 1971:     }
1.352     www      1972: #
                   1973: # Roles
                   1974: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1975: #
1.800     albertel 1976:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1977:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1978: 	    split(/\:/,$entry);
                   1979:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1980:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1981:                 $rudom,$runame) eq 'ok') {
                   1982: 	    delete $userrolehash{$entry};
                   1983:         }
                   1984:     }
1.662     raeburn  1985: #
                   1986: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1987: #
                   1988:     my %domrolebuffer = ();
                   1989:     foreach my $entry (keys %domainrolehash) {
                   1990:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1991:         if ($domrolebuffer{$rudom}) {
                   1992:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1993:                       '='.&escape($domainrolehash{$entry});
                   1994:         } else {
                   1995:             $domrolebuffer{$rudom}.=&escape($entry).
                   1996:                       '='.&escape($domainrolehash{$entry});
                   1997:         }
                   1998:         delete $domainrolehash{$entry};
                   1999:     }
                   2000:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2001: 	my %servers = &get_servers($dom,'library');
                   2002: 	foreach my $tryserver (keys(%servers)) {
                   2003: 	    unless (&reply('domroleput:'.$dom.':'.
                   2004: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2005: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2006: 	    }
1.662     raeburn  2007:         }
                   2008:     }
1.186     www      2009:     $dumpcount++;
1.157     www      2010: }
                   2011: 
                   2012: sub courselog {
                   2013:     my $what=shift;
1.158     www      2014:     $what=time.':'.$what;
1.620     albertel 2015:     unless ($env{'request.course.id'}) { return ''; }
                   2016:     $coursedombuf{$env{'request.course.id'}}=
                   2017:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2018:     $coursenumbuf{$env{'request.course.id'}}=
                   2019:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2020:     $coursehombuf{$env{'request.course.id'}}=
                   2021:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2022:     $coursedescrbuf{$env{'request.course.id'}}=
                   2023:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2024:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2025:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2026:     $courseownerbuf{$env{'request.course.id'}}=
                   2027:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2028:     $coursetypebuf{$env{'request.course.id'}}=
                   2029:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2030:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2031: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2032:     } else {
1.620     albertel 2033: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2034:     }
1.620     albertel 2035:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2036: 	&flushcourselogs();
                   2037:     }
1.158     www      2038: }
                   2039: 
                   2040: sub courseacclog {
                   2041:     my $fnsymb=shift;
1.620     albertel 2042:     unless ($env{'request.course.id'}) { return ''; }
                   2043:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2044:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2045:         $what.=':POST';
1.583     matthew  2046:         # FIXME: Probably ought to escape things....
1.800     albertel 2047: 	foreach my $key (keys(%env)) {
                   2048:             if ($key=~/^form\.(.*)/) {
                   2049: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2050:             }
1.191     harris41 2051:         }
1.583     matthew  2052:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2053:         # FIXME: We should not be depending on a form parameter that someone
                   2054:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2055:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2056:             $what.= ':POST';
                   2057:             # FIXME: Probably ought to escape things....
                   2058:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2059:                                  'crsdiscuss') {
1.620     albertel 2060:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2061:             }
                   2062:         }
1.158     www      2063:     }
                   2064:     &courselog($what);
1.149     www      2065: }
                   2066: 
1.185     www      2067: sub countacc {
                   2068:     my $url=&declutter(shift);
1.458     matthew  2069:     return if (! defined($url) || $url eq '');
1.620     albertel 2070:     unless ($env{'request.course.id'}) { return ''; }
                   2071:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2072:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2073:     $accesshash{$key}++;
1.185     www      2074: }
1.349     www      2075: 
1.361     www      2076: sub linklog {
                   2077:     my ($from,$to)=@_;
                   2078:     $from=&declutter($from);
                   2079:     $to=&declutter($to);
                   2080:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2081:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2082: }
                   2083:   
1.349     www      2084: sub userrolelog {
                   2085:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2086:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2087:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2088:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2089:         ($trole=~/^ta/)) {
1.350     www      2090:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2091:        $userrolehash
                   2092:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2093:                     =$tend.':'.$tstart;
1.662     raeburn  2094:     }
                   2095:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2096:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2097:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2098:         ($trole=~/^sc/)) {
                   2099:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2100:        $domainrolehash
                   2101:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2102:                     = $tend.':'.$tstart;
                   2103:     }
1.351     www      2104: }
                   2105: 
                   2106: sub get_course_adv_roles {
                   2107:     my $cid=shift;
1.620     albertel 2108:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2109:     my %coursehash=&coursedescription($cid);
1.470     www      2110:     my %nothide=();
1.800     albertel 2111:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2112: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2113:     }
1.351     www      2114:     my %returnhash=();
                   2115:     my %dumphash=
                   2116:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2117:     my $now=time;
1.800     albertel 2118:     foreach my $entry (keys %dumphash) {
                   2119: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2120:         if (($tstart) && ($tstart<0)) { next; }
                   2121:         if (($tend) && ($tend<$now)) { next; }
                   2122:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2123:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2124: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2125: 	if ((&privileged($username,$domain)) && 
                   2126: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2127: 	if ($role eq 'cr') { next; }
1.351     www      2128:         my $key=&plaintext($role);
                   2129:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2130:         if ($returnhash{$key}) {
                   2131: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2132:         } else {
                   2133:             $returnhash{$key}=$username.':'.$domain;
                   2134:         }
1.400     www      2135:      }
                   2136:     return %returnhash;
                   2137: }
                   2138: 
                   2139: sub get_my_roles {
1.858     raeburn  2140:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2141:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2142:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2143:     my %dumphash;
                   2144:     if ($context eq 'userroles') { 
                   2145:         %dumphash = &dump('roles',$udom,$uname);
                   2146:     } else {
                   2147:         %dumphash=
1.400     www      2148:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2149:     }
1.400     www      2150:     my %returnhash=();
                   2151:     my $now=time;
1.800     albertel 2152:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2153:         my ($role,$tend,$tstart);
                   2154:         if ($context eq 'userroles') {
                   2155: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2156:         } else {
                   2157:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2158:         }
1.400     www      2159:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2160:         my $status = 'active';
                   2161:         if (($tend) && ($tend<$now)) {
                   2162:             $status = 'previous';
                   2163:         } 
                   2164:         if (($tstart) && ($now<$tstart)) {
                   2165:             $status = 'future';
                   2166:         }
                   2167:         if (ref($types) eq 'ARRAY') {
                   2168:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2169:                 next;
                   2170:             } 
                   2171:         } else {
                   2172:             if ($status ne 'active') {
                   2173:                 next;
                   2174:             }
                   2175:         }
1.867     raeburn  2176:         my ($rolecode,$username,$domain,$section,$area);
                   2177:         if ($context eq 'userroles') {
                   2178:             ($area,$rolecode) = split(/_/,$entry);
                   2179:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2180:         } else {
                   2181:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2182:         }
1.832     raeburn  2183:         if (ref($roledoms) eq 'ARRAY') {
                   2184:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2185:                 next;
                   2186:             }
                   2187:         }
                   2188:         if (ref($roles) eq 'ARRAY') {
                   2189:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2190:                 next;
                   2191:             }
1.867     raeburn  2192:         }
1.400     www      2193: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2194:     }
1.373     www      2195:     return %returnhash;
1.399     www      2196: }
                   2197: 
                   2198: # ----------------------------------------------------- Frontpage Announcements
                   2199: #
                   2200: #
                   2201: 
                   2202: sub postannounce {
                   2203:     my ($server,$text)=@_;
1.844     albertel 2204:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2205:     unless ($text=~/\w/) { $text=''; }
                   2206:     return &reply('setannounce:'.&escape($text),$server);
                   2207: }
                   2208: 
                   2209: sub getannounce {
1.448     albertel 2210: 
                   2211:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2212: 	my $announcement='';
1.800     albertel 2213: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2214: 	close($fh);
1.399     www      2215: 	if ($announcement=~/\w/) { 
                   2216: 	    return 
                   2217:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2218:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2219: 	} else {
                   2220: 	    return '';
                   2221: 	}
                   2222:     } else {
                   2223: 	return '';
                   2224:     }
1.351     www      2225: }
1.353     www      2226: 
                   2227: # ---------------------------------------------------------- Course ID routines
                   2228: # Deal with domain's nohist_courseid.db files
                   2229: #
                   2230: 
                   2231: sub courseidput {
                   2232:     my ($domain,$what,$coursehome)=@_;
                   2233:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2234: }
                   2235: 
                   2236: sub courseiddump {
1.791     raeburn  2237:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2238:     my %returnhash=();
1.355     www      2239:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2240:     my %libserv = &all_library();
                   2241:     foreach my $tryserver (keys(%libserv)) {
                   2242:         if ( (  $hostidflag == 1 
                   2243: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2244: 	     || (!defined($hostidflag)) ) {
                   2245: 
                   2246: 	    if ($domfilter eq ''
                   2247: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2248: 	        foreach my $line (
1.844     albertel 2249:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2250: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2251:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2252:                                $tryserver))) {
1.800     albertel 2253: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2254:                     if (($key) && ($value)) {
1.516     raeburn  2255: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2256:                     }
1.353     www      2257:                 }
                   2258:             }
                   2259:         }
                   2260:     }
                   2261:     return %returnhash;
                   2262: }
                   2263: 
1.658     raeburn  2264: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2265: 
                   2266: sub dcmailput {
1.685     raeburn  2267:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2268:     my $status = &Apache::lonnet::critical(
1.740     www      2269:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2270:        &escape($message),$server);
1.662     raeburn  2271:     return $status;
                   2272: }
                   2273: 
1.658     raeburn  2274: sub dcmaildump {
                   2275:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2276:     my %returnhash=();
1.846     albertel 2277: 
                   2278:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2279:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2280:                                                          &escape($enddate).':';
                   2281: 	my @esc_senders=map { &escape($_)} @$senders;
                   2282: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2283: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2284:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2285:             if (($key) && ($value)) {
                   2286:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2287:             }
                   2288:         }
                   2289:     }
                   2290:     return %returnhash;
                   2291: }
1.662     raeburn  2292: # ---------------------------------------------------------- Domain roles
                   2293: 
                   2294: sub get_domain_roles {
                   2295:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2296:     if (undef($startdate) || $startdate eq '') {
                   2297:         $startdate = '.';
                   2298:     }
                   2299:     if (undef($enddate) || $enddate eq '') {
                   2300:         $enddate = '.';
                   2301:     }
                   2302:     my $rolelist = join(':',@{$roles});
                   2303:     my %personnel = ();
1.841     albertel 2304: 
                   2305:     my %servers = &get_servers($dom,'library');
                   2306:     foreach my $tryserver (keys(%servers)) {
                   2307: 	%{$personnel{$tryserver}}=();
                   2308: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2309: 					    &escape($startdate).':'.
                   2310: 					    &escape($enddate).':'.
                   2311: 					    &escape($rolelist), $tryserver))) {
                   2312: 	    my ($key,$value) = split(/\=/,$line,2);
                   2313: 	    if (($key) && ($value)) {
                   2314: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2315: 	    }
                   2316: 	}
1.662     raeburn  2317:     }
                   2318:     return %personnel;
                   2319: }
1.658     raeburn  2320: 
1.149     www      2321: # ----------------------------------------------------------- Check out an item
                   2322: 
1.504     albertel 2323: sub get_first_access {
                   2324:     my ($type,$argsymb)=@_;
1.790     albertel 2325:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2326:     if ($argsymb) { $symb=$argsymb; }
                   2327:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2328:     if ($type eq 'map') {
                   2329: 	$res=&symbread($map);
                   2330:     } else {
                   2331: 	$res=$symb;
                   2332:     }
                   2333:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2334:     return $times{"$courseid\0$res"};
1.504     albertel 2335: }
                   2336: 
                   2337: sub set_first_access {
                   2338:     my ($type)=@_;
1.790     albertel 2339:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2340:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2341:     if ($type eq 'map') {
                   2342: 	$res=&symbread($map);
                   2343:     } else {
                   2344: 	$res=$symb;
                   2345:     }
                   2346:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2347:     if (!$firstaccess) {
1.588     albertel 2348: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2349:     }
                   2350:     return 'already_set';
1.504     albertel 2351: }
                   2352: 
1.149     www      2353: sub checkout {
                   2354:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2355:     my $now=time;
                   2356:     my $lonhost=$perlvar{'lonHostID'};
                   2357:     my $infostr=&escape(
1.234     www      2358:                  'CHECKOUTTOKEN&'.
1.149     www      2359:                  $tuname.'&'.
                   2360:                  $tudom.'&'.
                   2361:                  $tcrsid.'&'.
                   2362:                  $symb.'&'.
                   2363: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2364:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2365:     if ($token=~/^error\:/) { 
1.672     albertel 2366:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2367:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2368:                  "</font>");
                   2369:         return ''; 
                   2370:     }
                   2371: 
1.149     www      2372:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2373:     $token=~tr/a-z/A-Z/;
                   2374: 
1.153     www      2375:     my %infohash=('resource.0.outtoken' => $token,
                   2376:                   'resource.0.checkouttime' => $now,
                   2377:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2378: 
                   2379:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2380:        return '';
1.151     www      2381:     } else {
1.672     albertel 2382:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2383:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2384:                  "</font>");
1.149     www      2385:     }    
                   2386: 
                   2387:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2388:                          &escape('Checkout '.$infostr.' - '.
                   2389:                                                  $token)) ne 'ok') {
                   2390: 	return '';
1.151     www      2391:     } else {
1.672     albertel 2392:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2393:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2394:                  "</font>");
1.149     www      2395:     }
1.151     www      2396:     return $token;
1.149     www      2397: }
                   2398: 
                   2399: # ------------------------------------------------------------ Check in an item
                   2400: 
                   2401: sub checkin {
                   2402:     my $token=shift;
1.150     www      2403:     my $now=time;
                   2404:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2405:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2406:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2407:     $dtoken=~s/\W/\_/g;
1.234     www      2408:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2409:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2410: 
1.154     www      2411:     unless (($tuname) && ($tudom)) {
                   2412:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2413:         return '';
                   2414:     }
                   2415:     
                   2416:     unless (&allowed('mgr',$tcrsid)) {
                   2417:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2418:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2419:         return '';
                   2420:     }
                   2421: 
1.153     www      2422:     my %infohash=('resource.0.intoken' => $token,
                   2423:                   'resource.0.checkintime' => $now,
                   2424:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2425: 
                   2426:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2427:        return '';
                   2428:     }    
                   2429: 
                   2430:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2431:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2432: 	return '';
                   2433:     }
                   2434: 
                   2435:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2436: }
                   2437: 
                   2438: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2439: 
                   2440: sub expirespread {
                   2441:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2442:     my $cid=$env{'request.course.id'}; 
1.110     www      2443:     if ($cid) {
                   2444:        my $now=time;
                   2445:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2446:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2447:                             $env{'course.'.$cid.'.num'}.
1.110     www      2448: 	        	    ':nohist_expirationdates:'.
                   2449:                             &escape($key).'='.$now,
1.620     albertel 2450:                             $env{'course.'.$cid.'.home'})
1.110     www      2451:     }
                   2452:     return 'ok';
1.14      www      2453: }
                   2454: 
1.109     www      2455: # ----------------------------------------------------- Devalidate Spreadsheets
                   2456: 
                   2457: sub devalidate {
1.325     www      2458:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2459:     my $cid=$env{'request.course.id'}; 
1.109     www      2460:     if ($cid) {
1.391     matthew  2461:         # delete the stored spreadsheets for
                   2462:         # - the student level sheet of this user in course's homespace
                   2463:         # - the assessment level sheet for this resource 
                   2464:         #   for this user in user's homespace
1.553     albertel 2465: 	# - current conditional state info
1.325     www      2466: 	my $key=$uname.':'.$udom.':';
1.109     www      2467:         my $status=
1.299     matthew  2468: 	    &del('nohist_calculatedsheets',
1.391     matthew  2469: 		 [$key.'studentcalc:'],
1.620     albertel 2470: 		 $env{'course.'.$cid.'.domain'},
                   2471: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2472: 		.' '.
                   2473: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2474: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2475:         unless ($status eq 'ok ok') {
                   2476:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2477:                     $uname.' at '.$udom.' for '.
1.109     www      2478: 		    $symb.': '.$status);
1.133     albertel 2479:         }
1.553     albertel 2480: 	&delenv('user.state.'.$cid);
1.109     www      2481:     }
                   2482: }
                   2483: 
1.265     albertel 2484: sub get_scalar {
                   2485:     my ($string,$end) = @_;
                   2486:     my $value;
                   2487:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2488: 	$value = $1;
                   2489:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2490: 	$value = $1;
                   2491:     }
                   2492:     return &unescape($value);
                   2493: }
                   2494: 
                   2495: sub array2str {
                   2496:   my (@array) = @_;
                   2497:   my $result=&arrayref2str(\@array);
                   2498:   $result=~s/^__ARRAY_REF__//;
                   2499:   $result=~s/__END_ARRAY_REF__$//;
                   2500:   return $result;
                   2501: }
                   2502: 
1.204     albertel 2503: sub arrayref2str {
                   2504:   my ($arrayref) = @_;
1.265     albertel 2505:   my $result='__ARRAY_REF__';
1.204     albertel 2506:   foreach my $elem (@$arrayref) {
1.265     albertel 2507:     if(ref($elem) eq 'ARRAY') {
                   2508:       $result.=&arrayref2str($elem).'&';
                   2509:     } elsif(ref($elem) eq 'HASH') {
                   2510:       $result.=&hashref2str($elem).'&';
                   2511:     } elsif(ref($elem)) {
                   2512:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2513:     } else {
                   2514:       $result.=&escape($elem).'&';
                   2515:     }
                   2516:   }
                   2517:   $result=~s/\&$//;
1.265     albertel 2518:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2519:   return $result;
                   2520: }
                   2521: 
1.168     albertel 2522: sub hash2str {
1.204     albertel 2523:   my (%hash) = @_;
                   2524:   my $result=&hashref2str(\%hash);
1.265     albertel 2525:   $result=~s/^__HASH_REF__//;
                   2526:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2527:   return $result;
                   2528: }
                   2529: 
                   2530: sub hashref2str {
                   2531:   my ($hashref)=@_;
1.265     albertel 2532:   my $result='__HASH_REF__';
1.800     albertel 2533:   foreach my $key (sort(keys(%$hashref))) {
                   2534:     if (ref($key) eq 'ARRAY') {
                   2535:       $result.=&arrayref2str($key).'=';
                   2536:     } elsif (ref($key) eq 'HASH') {
                   2537:       $result.=&hashref2str($key).'=';
                   2538:     } elsif (ref($key)) {
1.265     albertel 2539:       $result.='=';
1.800     albertel 2540:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2541:     } else {
1.800     albertel 2542: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2543:     }
                   2544: 
1.800     albertel 2545:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2546:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2547:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2548:       $result.=&hashref2str($hashref->{$key}).'&';
                   2549:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2550:        $result.='&';
1.800     albertel 2551:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2552:     } else {
1.800     albertel 2553:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2554:     }
                   2555:   }
1.168     albertel 2556:   $result=~s/\&$//;
1.265     albertel 2557:   $result .= '__END_HASH_REF__';
1.168     albertel 2558:   return $result;
                   2559: }
                   2560: 
                   2561: sub str2hash {
1.265     albertel 2562:     my ($string)=@_;
                   2563:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2564:     return %$hash;
                   2565: }
                   2566: 
                   2567: sub str2hashref {
1.168     albertel 2568:   my ($string) = @_;
1.265     albertel 2569: 
                   2570:   my %hash;
                   2571: 
                   2572:   if($string !~ /^__HASH_REF__/) {
                   2573:       if (! ($string eq '' || !defined($string))) {
                   2574: 	  $hash{'error'}='Not hash reference';
                   2575:       }
                   2576:       return (\%hash, $string);
                   2577:   }
                   2578: 
                   2579:   $string =~ s/^__HASH_REF__//;
                   2580: 
                   2581:   while($string !~ /^__END_HASH_REF__/) {
                   2582:       #key
                   2583:       my $key='';
                   2584:       if($string =~ /^__HASH_REF__/) {
                   2585:           ($key, $string)=&str2hashref($string);
                   2586:           if(defined($key->{'error'})) {
                   2587:               $hash{'error'}='Bad data';
                   2588:               return (\%hash, $string);
                   2589:           }
                   2590:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2591:           ($key, $string)=&str2arrayref($string);
                   2592:           if($key->[0] eq 'Array reference error') {
                   2593:               $hash{'error'}='Bad data';
                   2594:               return (\%hash, $string);
                   2595:           }
                   2596:       } else {
                   2597:           $string =~ s/^(.*?)=//;
1.267     albertel 2598: 	  $key=&unescape($1);
1.265     albertel 2599:       }
                   2600:       $string =~ s/^=//;
                   2601: 
                   2602:       #value
                   2603:       my $value='';
                   2604:       if($string =~ /^__HASH_REF__/) {
                   2605:           ($value, $string)=&str2hashref($string);
                   2606:           if(defined($value->{'error'})) {
                   2607:               $hash{'error'}='Bad data';
                   2608:               return (\%hash, $string);
                   2609:           }
                   2610:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2611:           ($value, $string)=&str2arrayref($string);
                   2612:           if($value->[0] eq 'Array reference error') {
                   2613:               $hash{'error'}='Bad data';
                   2614:               return (\%hash, $string);
                   2615:           }
                   2616:       } else {
                   2617: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2618:       }
                   2619:       $string =~ s/^&//;
                   2620: 
                   2621:       $hash{$key}=$value;
1.204     albertel 2622:   }
1.265     albertel 2623: 
                   2624:   $string =~ s/^__END_HASH_REF__//;
                   2625: 
                   2626:   return (\%hash, $string);
1.204     albertel 2627: }
                   2628: 
                   2629: sub str2array {
1.265     albertel 2630:     my ($string)=@_;
                   2631:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2632:     return @$array;
                   2633: }
                   2634: 
                   2635: sub str2arrayref {
1.204     albertel 2636:   my ($string) = @_;
1.265     albertel 2637:   my @array;
                   2638: 
                   2639:   if($string !~ /^__ARRAY_REF__/) {
                   2640:       if (! ($string eq '' || !defined($string))) {
                   2641: 	  $array[0]='Array reference error';
                   2642:       }
                   2643:       return (\@array, $string);
                   2644:   }
                   2645: 
                   2646:   $string =~ s/^__ARRAY_REF__//;
                   2647: 
                   2648:   while($string !~ /^__END_ARRAY_REF__/) {
                   2649:       my $value='';
                   2650:       if($string =~ /^__HASH_REF__/) {
                   2651:           ($value, $string)=&str2hashref($string);
                   2652:           if(defined($value->{'error'})) {
                   2653:               $array[0] ='Array reference error';
                   2654:               return (\@array, $string);
                   2655:           }
                   2656:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2657:           ($value, $string)=&str2arrayref($string);
                   2658:           if($value->[0] eq 'Array reference error') {
                   2659:               $array[0] ='Array reference error';
                   2660:               return (\@array, $string);
                   2661:           }
                   2662:       } else {
                   2663: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2664:       }
                   2665:       $string =~ s/^&//;
                   2666: 
                   2667:       push(@array, $value);
1.191     harris41 2668:   }
1.265     albertel 2669: 
                   2670:   $string =~ s/^__END_ARRAY_REF__//;
                   2671: 
                   2672:   return (\@array, $string);
1.168     albertel 2673: }
                   2674: 
1.167     albertel 2675: # -------------------------------------------------------------------Temp Store
                   2676: 
1.168     albertel 2677: sub tmpreset {
                   2678:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2679:   if (!$symb) {
                   2680:     $symb=&symbread();
1.620     albertel 2681:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2682:   }
                   2683:   $symb=escape($symb);
                   2684: 
1.620     albertel 2685:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2686:   $namespace=~s/\//\_/g;
                   2687:   $namespace=~s/\W//g;
                   2688: 
1.620     albertel 2689:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2690:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2691:   if ($domain eq 'public' && $stuname eq 'public') {
                   2692:       $stuname=$ENV{'REMOTE_ADDR'};
                   2693:   }
1.168     albertel 2694:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2695:   my %hash;
                   2696:   if (tie(%hash,'GDBM_File',
                   2697: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2698: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2699:     foreach my $key (keys %hash) {
1.180     albertel 2700:       if ($key=~ /:$symb/) {
1.168     albertel 2701: 	delete($hash{$key});
                   2702:       }
                   2703:     }
                   2704:   }
                   2705: }
                   2706: 
1.167     albertel 2707: sub tmpstore {
1.168     albertel 2708:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2709: 
                   2710:   if (!$symb) {
                   2711:     $symb=&symbread();
1.620     albertel 2712:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2713:   }
                   2714:   $symb=escape($symb);
                   2715: 
                   2716:   if (!$namespace) {
                   2717:     # I don't think we would ever want to store this for a course.
                   2718:     # it seems this will only be used if we don't have a course.
1.620     albertel 2719:     #$namespace=$env{'request.course.id'};
1.168     albertel 2720:     #if (!$namespace) {
1.620     albertel 2721:       $namespace=$env{'request.state'};
1.168     albertel 2722:     #}
                   2723:   }
                   2724:   $namespace=~s/\//\_/g;
                   2725:   $namespace=~s/\W//g;
1.620     albertel 2726:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2727:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2728:   if ($domain eq 'public' && $stuname eq 'public') {
                   2729:       $stuname=$ENV{'REMOTE_ADDR'};
                   2730:   }
1.168     albertel 2731:   my $now=time;
                   2732:   my %hash;
                   2733:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2734:   if (tie(%hash,'GDBM_File',
                   2735: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2736: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2737:     $hash{"version:$symb"}++;
                   2738:     my $version=$hash{"version:$symb"};
                   2739:     my $allkeys=''; 
                   2740:     foreach my $key (keys(%$storehash)) {
                   2741:       $allkeys.=$key.':';
1.591     albertel 2742:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2743:     }
                   2744:     $hash{"$version:$symb:timestamp"}=$now;
                   2745:     $allkeys.='timestamp';
                   2746:     $hash{"$version:keys:$symb"}=$allkeys;
                   2747:     if (untie(%hash)) {
                   2748:       return 'ok';
                   2749:     } else {
                   2750:       return "error:$!";
                   2751:     }
                   2752:   } else {
                   2753:     return "error:$!";
                   2754:   }
                   2755: }
1.167     albertel 2756: 
1.168     albertel 2757: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2758: 
1.168     albertel 2759: sub tmprestore {
                   2760:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2761: 
1.168     albertel 2762:   if (!$symb) {
                   2763:     $symb=&symbread();
1.620     albertel 2764:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2765:   }
                   2766:   $symb=escape($symb);
                   2767: 
1.620     albertel 2768:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2769: 
1.620     albertel 2770:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2771:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2772:   if ($domain eq 'public' && $stuname eq 'public') {
                   2773:       $stuname=$ENV{'REMOTE_ADDR'};
                   2774:   }
1.168     albertel 2775:   my %returnhash;
                   2776:   $namespace=~s/\//\_/g;
                   2777:   $namespace=~s/\W//g;
                   2778:   my %hash;
                   2779:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2780:   if (tie(%hash,'GDBM_File',
                   2781: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2782: 	  &GDBM_READER(),0640)) {
1.168     albertel 2783:     my $version=$hash{"version:$symb"};
                   2784:     $returnhash{'version'}=$version;
                   2785:     my $scope;
                   2786:     for ($scope=1;$scope<=$version;$scope++) {
                   2787:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2788:       my @keys=split(/:/,$vkeys);
                   2789:       my $key;
                   2790:       $returnhash{"$scope:keys"}=$vkeys;
                   2791:       foreach $key (@keys) {
1.591     albertel 2792: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2793: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2794:       }
                   2795:     }
1.168     albertel 2796:     if (!(untie(%hash))) {
                   2797:       return "error:$!";
                   2798:     }
                   2799:   } else {
                   2800:     return "error:$!";
                   2801:   }
                   2802:   return %returnhash;
1.167     albertel 2803: }
                   2804: 
1.9       www      2805: # ----------------------------------------------------------------------- Store
                   2806: 
                   2807: sub store {
1.124     www      2808:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2809:     my $home='';
                   2810: 
1.168     albertel 2811:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2812: 
1.213     www      2813:     $symb=&symbclean($symb);
1.122     albertel 2814:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2815: 
1.620     albertel 2816:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2817:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2818: 
                   2819:     &devalidate($symb,$stuname,$domain);
1.109     www      2820: 
                   2821:     $symb=escape($symb);
1.187     www      2822:     if (!$namespace) { 
1.620     albertel 2823:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2824:           return ''; 
                   2825:        } 
                   2826:     }
1.620     albertel 2827:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2828: 
                   2829:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2830:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2831: 
1.12      www      2832:     my $namevalue='';
1.800     albertel 2833:     foreach my $key (keys(%$storehash)) {
                   2834:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2835:     }
1.12      www      2836:     $namevalue=~s/\&$//;
1.187     www      2837:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2838:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2839: }
                   2840: 
1.47      www      2841: # -------------------------------------------------------------- Critical Store
                   2842: 
                   2843: sub cstore {
1.124     www      2844:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2845:     my $home='';
                   2846: 
1.168     albertel 2847:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2848: 
1.213     www      2849:     $symb=&symbclean($symb);
1.122     albertel 2850:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2851: 
1.620     albertel 2852:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2853:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2854: 
                   2855:     &devalidate($symb,$stuname,$domain);
1.109     www      2856: 
                   2857:     $symb=escape($symb);
1.187     www      2858:     if (!$namespace) { 
1.620     albertel 2859:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2860:           return ''; 
                   2861:        } 
                   2862:     }
1.620     albertel 2863:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2864: 
                   2865:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2866:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2867: 
1.47      www      2868:     my $namevalue='';
1.800     albertel 2869:     foreach my $key (keys(%$storehash)) {
                   2870:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2871:     }
1.47      www      2872:     $namevalue=~s/\&$//;
1.187     www      2873:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2874:     return critical
                   2875:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2876: }
                   2877: 
1.9       www      2878: # --------------------------------------------------------------------- Restore
                   2879: 
                   2880: sub restore {
1.124     www      2881:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2882:     my $home='';
                   2883: 
1.168     albertel 2884:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2885: 
1.122     albertel 2886:     if (!$symb) {
                   2887:       unless ($symb=escape(&symbread())) { return ''; }
                   2888:     } else {
1.213     www      2889:       $symb=&escape(&symbclean($symb));
1.122     albertel 2890:     }
1.188     www      2891:     if (!$namespace) { 
1.620     albertel 2892:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2893:           return ''; 
                   2894:        } 
                   2895:     }
1.620     albertel 2896:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2897:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2898:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2899:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2900: 
1.12      www      2901:     my %returnhash=();
1.800     albertel 2902:     foreach my $line (split(/\&/,$answer)) {
                   2903: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2904:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2905:     }
1.75      www      2906:     my $version;
                   2907:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2908:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2909:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2910:        }
1.75      www      2911:     }
1.13      www      2912:     return %returnhash;
1.34      www      2913: }
                   2914: 
                   2915: # ---------------------------------------------------------- Course Description
                   2916: 
                   2917: sub coursedescription {
1.731     albertel 2918:     my ($courseid,$args)=@_;
1.34      www      2919:     $courseid=~s/^\///;
1.49      www      2920:     $courseid=~s/\_/\//g;
1.34      www      2921:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2922:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2923:     my $normalid=$cdomain.'_'.$cnum;
                   2924:     # need to always cache even if we get errors otherwise we keep 
                   2925:     # trying and trying and trying to get the course description.
                   2926:     my %envhash=();
                   2927:     my %returnhash=();
1.731     albertel 2928:     
                   2929:     my $expiretime=600;
                   2930:     if ($env{'request.course.id'} eq $normalid) {
                   2931: 	$expiretime=120;
                   2932:     }
                   2933: 
                   2934:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2935:     if (!$args->{'freshen_cache'}
                   2936: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2937: 	foreach my $key (keys(%env)) {
                   2938: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2939: 	    my ($setting) = $1;
                   2940: 	    $returnhash{$setting} = $env{$key};
                   2941: 	}
                   2942: 	return %returnhash;
                   2943:     }
                   2944: 
                   2945:     # get the data agin
                   2946:     if (!$args->{'one_time'}) {
                   2947: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2948:     }
1.811     albertel 2949: 
1.34      www      2950:     if ($chome ne 'no_host') {
1.302     albertel 2951:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2952:        if (!exists($returnhash{'con_lost'})) {
                   2953:            $returnhash{'home'}= $chome;
                   2954: 	   $returnhash{'domain'} = $cdomain;
                   2955: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2956:            if (!defined($returnhash{'type'})) {
                   2957:                $returnhash{'type'} = 'Course';
                   2958:            }
1.130     albertel 2959:            while (my ($name,$value) = each %returnhash) {
1.53      www      2960:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2961:            }
1.270     www      2962:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2963:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2964: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2965:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2966:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2967:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2968:        }
                   2969:     }
1.731     albertel 2970:     if (!$args->{'one_time'}) {
                   2971: 	&appenv(%envhash);
                   2972:     }
1.302     albertel 2973:     return %returnhash;
1.461     www      2974: }
                   2975: 
                   2976: # -------------------------------------------------See if a user is privileged
                   2977: 
                   2978: sub privileged {
                   2979:     my ($username,$domain)=@_;
                   2980:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2981: 			&homeserver($username,$domain));
                   2982:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2983:     my $now=time;
                   2984:     if ($rolesdump ne '') {
1.800     albertel 2985:         foreach my $entry (split(/&/,$rolesdump)) {
                   2986: 	    if ($entry!~/^rolesdef_/) {
                   2987: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2988: 		$area=~s/\_\w\w$//;
                   2989: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2990: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2991: 		    my $active=1;
                   2992: 		    if ($tend) {
                   2993: 			if ($tend<$now) { $active=0; }
                   2994: 		    }
                   2995: 		    if ($tstart) {
                   2996: 			if ($tstart>$now) { $active=0; }
                   2997: 		    }
                   2998: 		    if ($active) { return 1; }
                   2999: 		}
                   3000: 	    }
                   3001: 	}
                   3002:     }
                   3003:     return 0;
1.9       www      3004: }
1.1       albertel 3005: 
1.103     harris41 3006: # -------------------------------------------------------- Get user privileges
1.11      www      3007: 
                   3008: sub rolesinit {
                   3009:     my ($domain,$username,$authhost)=@_;
                   3010:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3011:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3012:     my %allroles=();
1.678     raeburn  3013:     my %allgroups=();   
1.11      www      3014:     my $now=time;
1.743     albertel 3015:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3016:     my $group_privs;
1.11      www      3017: 
                   3018:     if ($rolesdump ne '') {
1.800     albertel 3019:         foreach my $entry (split(/&/,$rolesdump)) {
                   3020: 	  if ($entry!~/^rolesdef_/) {
                   3021:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3022: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3023:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3024: 	    if ($role=~/^cr/) { 
1.807     albertel 3025: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3026: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3027: 		    ($tend,$tstart)=split('_',$trest);
                   3028: 		} else {
                   3029: 		    $trole=$role;
                   3030: 		}
1.678     raeburn  3031:             } elsif ($role =~ m|^gr/|) {
                   3032:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3033:                 ($trole,$group_privs) = split(/\//,$trole);
                   3034:                 $group_privs = &unescape($group_privs);
1.587     albertel 3035: 	    } else {
                   3036: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3037: 	    }
1.743     albertel 3038: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3039: 					 $username);
                   3040: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3041:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3042:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3043:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3044: 		my $spec=$trole.'.'.$area;
                   3045: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3046: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3047:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3048:                 } elsif ($trole eq 'gr') {
                   3049:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3050: 		} else {
1.567     raeburn  3051:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3052: 		}
1.12      www      3053:             }
1.662     raeburn  3054:           }
1.191     harris41 3055:         }
1.743     albertel 3056:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3057:         $userroles{'user.adv'}    = $adv;
                   3058: 	$userroles{'user.author'} = $author;
1.620     albertel 3059:         $env{'user.adv'}=$adv;
1.11      www      3060:     }
1.743     albertel 3061:     return \%userroles;  
1.11      www      3062: }
                   3063: 
1.567     raeburn  3064: sub set_arearole {
                   3065:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3066: # log the associated role with the area
                   3067:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3068:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3069: }
                   3070: 
                   3071: sub custom_roleprivs {
                   3072:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3073:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3074:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3075:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3076:         my ($rdummy,$roledef)=
                   3077:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3078:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3079:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3080:             if (defined($syspriv)) {
                   3081:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3082:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3083:             }
                   3084:             if ($tdomain ne '') {
                   3085:                 if (defined($dompriv)) {
                   3086:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3087:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3088:                 }
                   3089:                 if (($trest ne '') && (defined($coursepriv))) {
                   3090:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3091:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3092:                 }
                   3093:             }
                   3094:         }
                   3095:     }
                   3096: }
                   3097: 
1.678     raeburn  3098: sub group_roleprivs {
                   3099:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3100:     my $access = 1;
                   3101:     my $now = time;
                   3102:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3103:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3104:     if ($access) {
1.811     albertel 3105:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3106:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3107:     }
                   3108: }
1.567     raeburn  3109: 
                   3110: sub standard_roleprivs {
                   3111:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3112:     if (defined($pr{$trole.':s'})) {
                   3113:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3114:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3115:     }
                   3116:     if ($tdomain ne '') {
                   3117:         if (defined($pr{$trole.':d'})) {
                   3118:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3119:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3120:         }
                   3121:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3122:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3123:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3124:         }
                   3125:     }
                   3126: }
                   3127: 
                   3128: sub set_userprivs {
1.678     raeburn  3129:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3130:     my $author=0;
                   3131:     my $adv=0;
1.678     raeburn  3132:     my %grouproles = ();
                   3133:     if (keys(%{$allgroups}) > 0) {
                   3134:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3135:             my ($trole,$area,$sec,$extendedarea);
1.881   ! raeburn  3136:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3137:                 $trole = $1;
                   3138:                 $area = $2;
1.681     raeburn  3139:                 $sec = $3;
                   3140:                 $extendedarea = $area.$sec;
                   3141:                 if (exists($$allgroups{$area})) {
                   3142:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3143:                         my $spec = $trole.'.'.$extendedarea;
                   3144:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3145:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3146:                     }
                   3147:                 }
                   3148:             }
                   3149:         }
                   3150:     }
1.800     albertel 3151:     foreach my $group (keys(%grouproles)) {
                   3152:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3153:     }
1.800     albertel 3154:     foreach my $role (keys(%{$allroles})) {
                   3155:         my %thesepriv;
                   3156:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3157:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3158:             if ($item ne '') {
                   3159:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3160:                 if ($restrictions eq '') {
                   3161:                     $thesepriv{$privilege}='F';
                   3162:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3163:                     $thesepriv{$privilege}.=$restrictions;
                   3164:                 }
                   3165:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3166:             }
                   3167:         }
                   3168:         my $thesestr='';
1.800     albertel 3169:         foreach my $priv (keys(%thesepriv)) {
                   3170: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3171: 	}
                   3172:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3173:     }
                   3174:     return ($author,$adv);
                   3175: }
                   3176: 
1.12      www      3177: # --------------------------------------------------------------- get interface
                   3178: 
                   3179: sub get {
1.131     albertel 3180:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3181:    my $items='';
1.800     albertel 3182:    foreach my $item (@$storearr) {
                   3183:        $items.=&escape($item).'&';
1.191     harris41 3184:    }
1.12      www      3185:    $items=~s/\&$//;
1.620     albertel 3186:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3187:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3188:    my $uhome=&homeserver($uname,$udomain);
                   3189: 
1.133     albertel 3190:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3191:    my @pairs=split(/\&/,$rep);
1.273     albertel 3192:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3193:      return @pairs;
                   3194:    }
1.15      www      3195:    my %returnhash=();
1.42      www      3196:    my $i=0;
1.800     albertel 3197:    foreach my $item (@$storearr) {
                   3198:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3199:       $i++;
1.191     harris41 3200:    }
1.15      www      3201:    return %returnhash;
1.27      www      3202: }
                   3203: 
                   3204: # --------------------------------------------------------------- del interface
                   3205: 
                   3206: sub del {
1.133     albertel 3207:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3208:    my $items='';
1.800     albertel 3209:    foreach my $item (@$storearr) {
                   3210:        $items.=&escape($item).'&';
1.191     harris41 3211:    }
1.27      www      3212:    $items=~s/\&$//;
1.620     albertel 3213:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3214:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3215:    my $uhome=&homeserver($uname,$udomain);
                   3216: 
                   3217:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3218: }
                   3219: 
                   3220: # -------------------------------------------------------------- dump interface
                   3221: 
                   3222: sub dump {
1.755     albertel 3223:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3224:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3225:     if (!$uname) { $uname=$env{'user.name'}; }
                   3226:     my $uhome=&homeserver($uname,$udomain);
                   3227:     if ($regexp) {
                   3228: 	$regexp=&escape($regexp);
                   3229:     } else {
                   3230: 	$regexp='.';
                   3231:     }
                   3232:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3233:     my @pairs=split(/\&/,$rep);
                   3234:     my %returnhash=();
                   3235:     foreach my $item (@pairs) {
                   3236: 	my ($key,$value)=split(/=/,$item,2);
                   3237: 	$key = &unescape($key);
                   3238: 	next if ($key =~ /^error: 2 /);
                   3239: 	$returnhash{$key}=&thaw_unescape($value);
                   3240:     }
                   3241:     return %returnhash;
1.407     www      3242: }
                   3243: 
1.717     albertel 3244: # --------------------------------------------------------- dumpstore interface
                   3245: 
                   3246: sub dumpstore {
                   3247:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3248:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3249:    if (!$uname) { $uname=$env{'user.name'}; }
                   3250:    my $uhome=&homeserver($uname,$udomain);
                   3251:    if ($regexp) {
                   3252:        $regexp=&escape($regexp);
                   3253:    } else {
                   3254:        $regexp='.';
                   3255:    }
                   3256:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3257:    my @pairs=split(/\&/,$rep);
                   3258:    my %returnhash=();
                   3259:    foreach my $item (@pairs) {
                   3260:        my ($key,$value)=split(/=/,$item,2);
                   3261:        next if ($key =~ /^error: 2 /);
                   3262:        $returnhash{$key}=&thaw_unescape($value);
                   3263:    }
                   3264:    return %returnhash;
1.717     albertel 3265: }
                   3266: 
1.407     www      3267: # -------------------------------------------------------------- keys interface
                   3268: 
                   3269: sub getkeys {
                   3270:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3271:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3272:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3273:    my $uhome=&homeserver($uname,$udomain);
                   3274:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3275:    my @keyarray=();
1.800     albertel 3276:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3277:       next if ($key =~ /^error: 2 /);
1.800     albertel 3278:       push(@keyarray,&unescape($key));
1.407     www      3279:    }
                   3280:    return @keyarray;
1.318     matthew  3281: }
                   3282: 
1.319     matthew  3283: # --------------------------------------------------------------- currentdump
                   3284: sub currentdump {
1.328     matthew  3285:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3286:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3287:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3288:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3289:    my $uhome = &homeserver($sname,$sdom);
                   3290:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3291:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3292:    #
1.318     matthew  3293:    my %returnhash=();
1.319     matthew  3294:    #
                   3295:    if ($rep eq "unknown_cmd") { 
                   3296:        # an old lond will not know currentdump
                   3297:        # Do a dump and make it look like a currentdump
1.822     albertel 3298:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3299:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3300:        my %hash = @tmp;
                   3301:        @tmp=();
1.424     matthew  3302:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3303:    } else {
                   3304:        my @pairs=split(/\&/,$rep);
1.800     albertel 3305:        foreach my $pair (@pairs) {
                   3306:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3307:            my ($symb,$param) = split(/:/,$key);
                   3308:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3309:                                                         &thaw_unescape($value);
1.319     matthew  3310:        }
1.191     harris41 3311:    }
1.12      www      3312:    return %returnhash;
1.424     matthew  3313: }
                   3314: 
                   3315: sub convert_dump_to_currentdump{
                   3316:     my %hash = %{shift()};
                   3317:     my %returnhash;
                   3318:     # Code ripped from lond, essentially.  The only difference
                   3319:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3320:     # we might run in to problems with parameter names =~ /^v\./
                   3321:     while (my ($key,$value) = each(%hash)) {
                   3322:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3323: 	$symb  = &unescape($symb);
                   3324: 	$param = &unescape($param);
1.424     matthew  3325:         next if ($v eq 'version' || $symb eq 'keys');
                   3326:         next if (exists($returnhash{$symb}) &&
                   3327:                  exists($returnhash{$symb}->{$param}) &&
                   3328:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3329:         $returnhash{$symb}->{$param}=$value;
                   3330:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3331:     }
                   3332:     #
                   3333:     # Remove all of the keys in the hashes which keep track of
                   3334:     # the version of the parameter.
                   3335:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3336:         # use a foreach because we are going to delete from the hash.
                   3337:         foreach my $key (keys(%$param_hash)) {
                   3338:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3339:         }
                   3340:     }
                   3341:     return \%returnhash;
1.12      www      3342: }
                   3343: 
1.627     albertel 3344: # ------------------------------------------------------ critical inc interface
                   3345: 
                   3346: sub cinc {
                   3347:     return &inc(@_,'critical');
                   3348: }
                   3349: 
1.449     matthew  3350: # --------------------------------------------------------------- inc interface
                   3351: 
                   3352: sub inc {
1.627     albertel 3353:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3354:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3355:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3356:     my $uhome=&homeserver($uname,$udomain);
                   3357:     my $items='';
                   3358:     if (! ref($store)) {
                   3359:         # got a single value, so use that instead
                   3360:         $items = &escape($store).'=&';
                   3361:     } elsif (ref($store) eq 'SCALAR') {
                   3362:         $items = &escape($$store).'=&';        
                   3363:     } elsif (ref($store) eq 'ARRAY') {
                   3364:         $items = join('=&',map {&escape($_);} @{$store});
                   3365:     } elsif (ref($store) eq 'HASH') {
                   3366:         while (my($key,$value) = each(%{$store})) {
                   3367:             $items.= &escape($key).'='.&escape($value).'&';
                   3368:         }
                   3369:     }
                   3370:     $items=~s/\&$//;
1.627     albertel 3371:     if ($critical) {
                   3372: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3373:     } else {
                   3374: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3375:     }
1.449     matthew  3376: }
                   3377: 
1.12      www      3378: # --------------------------------------------------------------- put interface
                   3379: 
                   3380: sub put {
1.134     albertel 3381:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3382:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3383:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3384:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3385:    my $items='';
1.800     albertel 3386:    foreach my $item (keys(%$storehash)) {
                   3387:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3388:    }
1.12      www      3389:    $items=~s/\&$//;
1.134     albertel 3390:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3391: }
                   3392: 
1.631     albertel 3393: # ------------------------------------------------------------ newput interface
                   3394: 
                   3395: sub newput {
                   3396:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3397:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3398:    if (!$uname) { $uname=$env{'user.name'}; }
                   3399:    my $uhome=&homeserver($uname,$udomain);
                   3400:    my $items='';
                   3401:    foreach my $key (keys(%$storehash)) {
                   3402:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3403:    }
                   3404:    $items=~s/\&$//;
                   3405:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3406: }
                   3407: 
                   3408: # ---------------------------------------------------------  putstore interface
                   3409: 
1.524     raeburn  3410: sub putstore {
1.715     albertel 3411:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3412:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3413:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3414:    my $uhome=&homeserver($uname,$udomain);
                   3415:    my $items='';
1.715     albertel 3416:    foreach my $key (keys(%$storehash)) {
                   3417:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3418:    }
1.715     albertel 3419:    $items=~s/\&$//;
1.716     albertel 3420:    my $esc_symb=&escape($symb);
                   3421:    my $esc_v=&escape($version);
1.715     albertel 3422:    my $reply =
1.716     albertel 3423:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3424: 	      $uhome);
                   3425:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3426:        # gfall back to way things use to be done
1.715     albertel 3427:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3428: 			    $uname);
1.524     raeburn  3429:    }
1.715     albertel 3430:    return $reply;
                   3431: }
                   3432: 
                   3433: sub old_putstore {
1.716     albertel 3434:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3435:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3436:     if (!$uname) { $uname=$env{'user.name'}; }
                   3437:     my $uhome=&homeserver($uname,$udomain);
                   3438:     my %newstorehash;
1.800     albertel 3439:     foreach my $item (keys(%$storehash)) {
                   3440: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3441: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3442:     }
                   3443:     my $items='';
                   3444:     my %allitems = ();
1.800     albertel 3445:     foreach my $item (keys(%newstorehash)) {
                   3446: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3447: 	    my $key = $1.':keys:'.$2;
                   3448: 	    $allitems{$key} .= $3.':';
                   3449: 	}
1.800     albertel 3450: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3451:     }
1.800     albertel 3452:     foreach my $item (keys(%allitems)) {
                   3453: 	$allitems{$item} =~ s/\:$//;
                   3454: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3455:     }
                   3456:     $items=~s/\&$//;
                   3457:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3458: }
                   3459: 
1.47      www      3460: # ------------------------------------------------------ critical put interface
                   3461: 
                   3462: sub cput {
1.134     albertel 3463:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3464:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3465:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3466:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3467:    my $items='';
1.800     albertel 3468:    foreach my $item (keys(%$storehash)) {
                   3469:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3470:    }
1.47      www      3471:    $items=~s/\&$//;
1.134     albertel 3472:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3473: }
                   3474: 
                   3475: # -------------------------------------------------------------- eget interface
                   3476: 
                   3477: sub eget {
1.133     albertel 3478:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3479:    my $items='';
1.800     albertel 3480:    foreach my $item (@$storearr) {
                   3481:        $items.=&escape($item).'&';
1.191     harris41 3482:    }
1.12      www      3483:    $items=~s/\&$//;
1.620     albertel 3484:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3485:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3486:    my $uhome=&homeserver($uname,$udomain);
                   3487:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3488:    my @pairs=split(/\&/,$rep);
                   3489:    my %returnhash=();
1.42      www      3490:    my $i=0;
1.800     albertel 3491:    foreach my $item (@$storearr) {
                   3492:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3493:       $i++;
1.191     harris41 3494:    }
1.12      www      3495:    return %returnhash;
                   3496: }
                   3497: 
1.667     albertel 3498: # ------------------------------------------------------------ tmpput interface
                   3499: sub tmpput {
1.802     raeburn  3500:     my ($storehash,$server,$context)=@_;
1.667     albertel 3501:     my $items='';
1.800     albertel 3502:     foreach my $item (keys(%$storehash)) {
                   3503: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3504:     }
                   3505:     $items=~s/\&$//;
1.802     raeburn  3506:     if (defined($context)) {
                   3507:         $items .= ':'.&escape($context);
                   3508:     }
1.667     albertel 3509:     return &reply("tmpput:$items",$server);
                   3510: }
                   3511: 
                   3512: # ------------------------------------------------------------ tmpget interface
                   3513: sub tmpget {
1.688     albertel 3514:     my ($token,$server)=@_;
                   3515:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3516:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3517:     my %returnhash;
                   3518:     foreach my $item (split(/\&/,$rep)) {
                   3519: 	my ($key,$value)=split(/=/,$item);
                   3520: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3521:     }
                   3522:     return %returnhash;
                   3523: }
                   3524: 
1.688     albertel 3525: # ------------------------------------------------------------ tmpget interface
                   3526: sub tmpdel {
                   3527:     my ($token,$server)=@_;
                   3528:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3529:     return &reply("tmpdel:$token",$server);
                   3530: }
                   3531: 
1.765     albertel 3532: # -------------------------------------------------- portfolio access checking
                   3533: 
                   3534: sub portfolio_access {
1.766     albertel 3535:     my ($requrl) = @_;
1.765     albertel 3536:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3537:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3538:     if ($result) {
                   3539:         my %setters;
                   3540:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3541:             my ($startblock,$endblock) =
                   3542:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3543:             if ($startblock && $endblock) {
                   3544:                 return 'B';
                   3545:             }
                   3546:         } else {
                   3547:             my ($startblock,$endblock) =
                   3548:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3549:             if ($startblock && $endblock) {
                   3550:                 return 'B';
                   3551:             }
                   3552:         }
                   3553:     }
1.765     albertel 3554:     if ($result eq 'ok') {
1.766     albertel 3555:        return 'F';
1.765     albertel 3556:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3557:        return 'A';
1.765     albertel 3558:     }
1.766     albertel 3559:     return '';
1.765     albertel 3560: }
                   3561: 
                   3562: sub get_portfolio_access {
1.767     albertel 3563:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3564: 
                   3565:     if (!ref($access_hash)) {
                   3566: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3567: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3568: 						   $file_name);
                   3569: 	$access_hash = $access_controls{$file_name};
                   3570:     }
                   3571: 
1.765     albertel 3572:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3573:     my $now = time;
                   3574:     if (ref($access_hash) eq 'HASH') {
                   3575:         foreach my $key (keys(%{$access_hash})) {
                   3576:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3577:             if ($start > $now) {
                   3578:                 next;
                   3579:             }
                   3580:             if ($end && $end<$now) {
                   3581:                 next;
                   3582:             }
                   3583:             if ($scope eq 'public') {
                   3584:                 $public = $key;
                   3585:                 last;
                   3586:             } elsif ($scope eq 'guest') {
                   3587:                 $guest = $key;
                   3588:             } elsif ($scope eq 'domains') {
                   3589:                 push(@domains,$key);
                   3590:             } elsif ($scope eq 'users') {
                   3591:                 push(@users,$key);
                   3592:             } elsif ($scope eq 'course') {
                   3593:                 push(@courses,$key);
                   3594:             } elsif ($scope eq 'group') {
                   3595:                 push(@groups,$key);
                   3596:             }
                   3597:         }
                   3598:         if ($public) {
                   3599:             return 'ok';
                   3600:         }
                   3601:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3602:             if ($guest) {
                   3603:                 return $guest;
                   3604:             }
                   3605:         } else {
                   3606:             if (@domains > 0) {
                   3607:                 foreach my $domkey (@domains) {
                   3608:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3609:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3610:                             return 'ok';
                   3611:                         }
                   3612:                     }
                   3613:                 }
                   3614:             }
                   3615:             if (@users > 0) {
                   3616:                 foreach my $userkey (@users) {
1.865     raeburn  3617:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3618:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3619:                             if (ref($item) eq 'HASH') {
                   3620:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3621:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3622:                                     return 'ok';
                   3623:                                 }
                   3624:                             }
                   3625:                         }
                   3626:                     } 
1.765     albertel 3627:                 }
                   3628:             }
                   3629:             my %roleshash;
                   3630:             my @courses_and_groups = @courses;
                   3631:             push(@courses_and_groups,@groups); 
                   3632:             if (@courses_and_groups > 0) {
                   3633:                 my (%allgroups,%allroles); 
                   3634:                 my ($start,$end,$role,$sec,$group);
                   3635:                 foreach my $envkey (%env) {
1.811     albertel 3636:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3637:                         my $cid = $2.'_'.$3; 
                   3638:                         if ($1 eq 'gr') {
                   3639:                             $group = $4;
                   3640:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3641:                         } else {
                   3642:                             if ($4 eq '') {
                   3643:                                 $sec = 'none';
                   3644:                             } else {
                   3645:                                 $sec = $4;
                   3646:                             }
                   3647:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3648:                         }
1.811     albertel 3649:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3650:                         my $cid = $2.'_'.$3;
                   3651:                         if ($4 eq '') {
                   3652:                             $sec = 'none';
                   3653:                         } else {
                   3654:                             $sec = $4;
                   3655:                         }
                   3656:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3657:                     }
                   3658:                 }
                   3659:                 if (keys(%allroles) == 0) {
                   3660:                     return;
                   3661:                 }
                   3662:                 foreach my $key (@courses_and_groups) {
                   3663:                     my %content = %{$$access_hash{$key}};
                   3664:                     my $cnum = $content{'number'};
                   3665:                     my $cdom = $content{'domain'};
                   3666:                     my $cid = $cdom.'_'.$cnum;
                   3667:                     if (!exists($allroles{$cid})) {
                   3668:                         next;
                   3669:                     }    
                   3670:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3671:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3672:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3673:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3674:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3675:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3676:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3677:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3678:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3679:                                         if (grep/^all$/,@sections) {
                   3680:                                             return 'ok';
                   3681:                                         } else {
                   3682:                                             if (grep/^$sec$/,@sections) {
                   3683:                                                 return 'ok';
                   3684:                                             }
                   3685:                                         }
                   3686:                                     }
                   3687:                                 }
                   3688:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3689:                                     if (grep/^none$/,@groups) {
                   3690:                                         return 'ok';
                   3691:                                     }
                   3692:                                 } else {
                   3693:                                     if (grep/^all$/,@groups) {
                   3694:                                         return 'ok';
                   3695:                                     } 
                   3696:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3697:                                         if (grep/^$group$/,@groups) {
                   3698:                                             return 'ok';
                   3699:                                         }
                   3700:                                     }
                   3701:                                 } 
                   3702:                             }
                   3703:                         }
                   3704:                     }
                   3705:                 }
                   3706:             }
                   3707:             if ($guest) {
                   3708:                 return $guest;
                   3709:             }
                   3710:         }
                   3711:     }
                   3712:     return;
                   3713: }
                   3714: 
                   3715: sub course_group_datechecker {
                   3716:     my ($dates,$now,$status) = @_;
                   3717:     my ($start,$end) = split(/\./,$dates);
                   3718:     if (!$start && !$end) {
                   3719:         return 'ok';
                   3720:     }
                   3721:     if (grep/^active$/,@{$status}) {
                   3722:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3723:             return 'ok';
                   3724:         }
                   3725:     }
                   3726:     if (grep/^previous$/,@{$status}) {
                   3727:         if ($end > $now ) {
                   3728:             return 'ok';
                   3729:         }
                   3730:     }
                   3731:     if (grep/^future$/,@{$status}) {
                   3732:         if ($start > $now) {
                   3733:             return 'ok';
                   3734:         }
                   3735:     }
                   3736:     return; 
                   3737: }
                   3738: 
                   3739: sub parse_portfolio_url {
                   3740:     my ($url) = @_;
                   3741: 
                   3742:     my ($type,$udom,$unum,$group,$file_name);
                   3743:     
1.823     albertel 3744:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3745: 	$type = 1;
                   3746:         $udom = $1;
                   3747:         $unum = $2;
                   3748:         $file_name = $3;
1.823     albertel 3749:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3750: 	$type = 2;
                   3751:         $udom = $1;
                   3752:         $unum = $2;
                   3753:         $group = $3;
                   3754:         $file_name = $3.'/'.$4;
                   3755:     }
                   3756:     if (wantarray) {
                   3757: 	return ($type,$udom,$unum,$file_name,$group);
                   3758:     }
                   3759:     return $type;
                   3760: }
                   3761: 
                   3762: sub is_portfolio_url {
                   3763:     my ($url) = @_;
                   3764:     return scalar(&parse_portfolio_url($url));
                   3765: }
                   3766: 
1.798     raeburn  3767: sub is_portfolio_file {
                   3768:     my ($file) = @_;
1.820     raeburn  3769:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3770:         return 1;
                   3771:     }
                   3772:     return;
                   3773: }
                   3774: 
                   3775: 
1.341     www      3776: # ---------------------------------------------- Custom access rule evaluation
                   3777: 
                   3778: sub customaccess {
                   3779:     my ($priv,$uri)=@_;
1.807     albertel 3780:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3781:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3782:     $udom = &LONCAPA::clean_domain($udom);
                   3783:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3784:     my $access=0;
1.800     albertel 3785:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3786: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3787:         if ($role) {
                   3788: 	   if ($role ne $urole) { next; }
                   3789:         }
1.800     albertel 3790:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3791:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3792:             if ($tdom) {
                   3793: 		if ($tdom ne $udom) { next; }
                   3794:             }
                   3795:             if ($tcrs) {
                   3796: 		if ($tcrs ne $ucrs) { next; }
                   3797:             }
                   3798:             if ($tsec) {
                   3799: 		if ($tsec ne $usec) { next; }
                   3800:             }
                   3801:             $access=($effect eq 'allow');
                   3802:             last;
1.342     www      3803:         }
1.402     bowersj2 3804: 	if ($realm eq '' && $role eq '') {
                   3805:             $access=($effect eq 'allow');
                   3806: 	}
1.341     www      3807:     }
                   3808:     return $access;
                   3809: }
                   3810: 
1.103     harris41 3811: # ------------------------------------------------- Check for a user privilege
1.12      www      3812: 
                   3813: sub allowed {
1.810     raeburn  3814:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3815:     my $ver_orguri=$uri;
1.439     www      3816:     $uri=&deversion($uri);
1.152     www      3817:     my $orguri=$uri;
1.52      www      3818:     $uri=&declutter($uri);
1.809     raeburn  3819: 
1.810     raeburn  3820:     if ($priv eq 'evb') {
                   3821: # Evade communication block restrictions for specified role in a course
                   3822:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3823:             return $1;
                   3824:         } else {
                   3825:             return;
                   3826:         }
                   3827:     }
                   3828: 
1.620     albertel 3829:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3830: # Free bre access to adm and meta resources
1.775     albertel 3831:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3832: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3833: 	&& ($priv eq 'bre')) {
1.14      www      3834: 	return 'F';
1.159     www      3835:     }
                   3836: 
1.545     banghart 3837: # Free bre access to user's own portfolio contents
1.714     raeburn  3838:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3839:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3840: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3841:         my %setters;
                   3842:         my ($startblock,$endblock) = 
                   3843:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3844:         if ($startblock && $endblock) {
                   3845:             return 'B';
                   3846:         } else {
                   3847:             return 'F';
                   3848:         }
1.545     banghart 3849:     }
                   3850: 
1.762     raeburn  3851: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3852:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3853:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3854:         if (exists($env{'request.course.id'})) {
                   3855:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3856:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3857:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3858:                 my $courseprivid=$env{'request.course.id'};
                   3859:                 $courseprivid=~s/\_/\//;
                   3860:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3861:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3862:                     return $1; 
1.762     raeburn  3863:                 } else {
                   3864:                     if ($env{'request.course.sec'}) {
                   3865:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3866:                     }
                   3867:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3868:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3869:                         return $2;
                   3870:                     }
1.714     raeburn  3871:                 }
                   3872:             }
                   3873:         }
                   3874:     }
                   3875: 
1.159     www      3876: # Free bre to public access
                   3877: 
                   3878:     if ($priv eq 'bre') {
1.238     www      3879:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3880: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3881:            return 'F'; 
                   3882:         }
1.238     www      3883:         if ($copyright eq 'priv') {
                   3884:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3885: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3886: 		return '';
                   3887:             }
                   3888:         }
                   3889:         if ($copyright eq 'domain') {
                   3890:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3891: 	    unless (($env{'user.domain'} eq $1) ||
                   3892:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3893: 		return '';
                   3894:             }
1.262     matthew  3895:         }
1.620     albertel 3896:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3897:             # Library role, so allow browsing of resources in this domain.
                   3898:             return 'F';
1.238     www      3899:         }
1.341     www      3900:         if ($copyright eq 'custom') {
                   3901: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3902:         }
1.14      www      3903:     }
1.264     matthew  3904:     # Domain coordinator is trying to create a course
1.620     albertel 3905:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3906:         # uri is the requested domain in this case.
                   3907:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3908:         # a role of dc for the domain in question.
1.620     albertel 3909:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3910:     }
1.29      www      3911: 
1.52      www      3912:     my $thisallowed='';
                   3913:     my $statecond=0;
                   3914:     my $courseprivid='';
                   3915: 
                   3916: # Course
                   3917: 
1.620     albertel 3918:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3919:        $thisallowed.=$1;
                   3920:     }
1.29      www      3921: 
1.52      www      3922: # Domain
                   3923: 
1.620     albertel 3924:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3925:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3926:        $thisallowed.=$1;
                   3927:     }
1.52      www      3928: 
                   3929: # Course: uri itself is a course
1.66      www      3930:     my $courseuri=$uri;
                   3931:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3932:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3933: 
1.620     albertel 3934:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3935:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3936:        $thisallowed.=$1;
                   3937:     }
1.29      www      3938: 
1.665     albertel 3939: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3940: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3941:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3942: 	$thisallowed='';
1.671     raeburn  3943:         my ($match)=&is_on_map($uri);
                   3944:         if ($match) {
                   3945:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3946:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3947:                 $thisallowed.=$1;
                   3948:             }
                   3949:         } else {
1.705     albertel 3950:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3951:             if ($refuri) {
                   3952:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3953:                     $thisallowed='F';
1.671     raeburn  3954:                 } else {
                   3955:                     $refuri=&declutter($refuri);
                   3956:                     my ($match) = &is_on_map($refuri);
                   3957:                     if ($match) {
                   3958:                         $thisallowed='F';
                   3959:                     }
1.669     raeburn  3960:                 }
1.671     raeburn  3961:             }
                   3962:         }
1.314     www      3963:     }
1.492     albertel 3964: 
1.766     albertel 3965:     if ($priv eq 'bre'
                   3966: 	&& $thisallowed ne 'F' 
                   3967: 	&& $thisallowed ne '2'
                   3968: 	&& &is_portfolio_url($uri)) {
                   3969: 	$thisallowed = &portfolio_access($uri);
                   3970:     }
                   3971:     
1.52      www      3972: # Full access at system, domain or course-wide level? Exit.
1.29      www      3973: 
                   3974:     if ($thisallowed=~/F/) {
                   3975: 	return 'F';
                   3976:     }
                   3977: 
1.52      www      3978: # If this is generating or modifying users, exit with special codes
1.29      www      3979: 
1.643     www      3980:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3981: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3982: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3983: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3984: 	    unless ($auname) { return $thisallowed; }
                   3985: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3986: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3987: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3988: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3989: 	}
1.52      www      3990: 	return $thisallowed;
                   3991:     }
                   3992: #
1.103     harris41 3993: # Gathered so far: system, domain and course wide privileges
1.52      www      3994: #
                   3995: # Course: See if uri or referer is an individual resource that is part of 
                   3996: # the course
                   3997: 
1.620     albertel 3998:     if ($env{'request.course.id'}) {
1.232     www      3999: 
1.620     albertel 4000:        $courseprivid=$env{'request.course.id'};
                   4001:        if ($env{'request.course.sec'}) {
                   4002:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4003:        }
                   4004:        $courseprivid=~s/\_/\//;
                   4005:        my $checkreferer=1;
1.232     www      4006:        my ($match,$cond)=&is_on_map($uri);
                   4007:        if ($match) {
                   4008:            $statecond=$cond;
1.620     albertel 4009:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4010:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4011:                $thisallowed.=$1;
                   4012:                $checkreferer=0;
                   4013:            }
1.29      www      4014:        }
1.83      www      4015:        
1.148     www      4016:        if ($checkreferer) {
1.620     albertel 4017: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4018:             unless ($refuri) {
1.800     albertel 4019:                 foreach my $key (keys(%env)) {
                   4020: 		    if ($key=~/^httpref\..*\*/) {
                   4021: 			my $pattern=$key;
1.156     www      4022:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4023:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4024:                         $pattern=~s/\//\\\//g;
1.152     www      4025:                         if ($orguri=~/$pattern/) {
1.800     albertel 4026: 			    $refuri=$env{$key};
1.148     www      4027:                         }
                   4028:                     }
1.191     harris41 4029:                 }
1.148     www      4030:             }
1.232     www      4031: 
1.148     www      4032:          if ($refuri) { 
1.152     www      4033: 	  $refuri=&declutter($refuri);
1.232     www      4034:           my ($match,$cond)=&is_on_map($refuri);
                   4035:             if ($match) {
                   4036:               my $refstatecond=$cond;
1.620     albertel 4037:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4038:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4039:                   $thisallowed.=$1;
1.53      www      4040:                   $uri=$refuri;
                   4041:                   $statecond=$refstatecond;
1.52      www      4042:               }
                   4043:           }
1.148     www      4044:         }
1.29      www      4045:        }
1.52      www      4046:    }
1.29      www      4047: 
1.52      www      4048: #
1.103     harris41 4049: # Gathered now: all privileges that could apply, and condition number
1.52      www      4050: # 
                   4051: #
                   4052: # Full or no access?
                   4053: #
1.29      www      4054: 
1.52      www      4055:     if ($thisallowed=~/F/) {
                   4056: 	return 'F';
                   4057:     }
1.29      www      4058: 
1.52      www      4059:     unless ($thisallowed) {
                   4060:         return '';
                   4061:     }
1.29      www      4062: 
1.52      www      4063: # Restrictions exist, deal with them
                   4064: #
                   4065: #   C:according to course preferences
                   4066: #   R:according to resource settings
                   4067: #   L:unless locked
                   4068: #   X:according to user session state
                   4069: #
                   4070: 
                   4071: # Possibly locked functionality, check all courses
1.54      www      4072: # Locks might take effect only after 10 minutes cache expiration for other
                   4073: # courses, and 2 minutes for current course
1.52      www      4074: 
                   4075:     my $envkey;
                   4076:     if ($thisallowed=~/L/) {
1.620     albertel 4077:         foreach $envkey (keys %env) {
1.54      www      4078:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4079:                my $courseid=$2;
                   4080:                my $roleid=$1.'.'.$2;
1.92      www      4081:                $courseid=~s/^\///;
1.54      www      4082:                my $expiretime=600;
1.620     albertel 4083:                if ($env{'request.role'} eq $roleid) {
1.54      www      4084: 		  $expiretime=120;
                   4085:                }
                   4086: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4087:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4088:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4089: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4090:                }
1.620     albertel 4091:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4092:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4093: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4094:                        &log($env{'user.domain'},$env{'user.name'},
                   4095:                             $env{'user.home'},
1.57      www      4096:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4097:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4098:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4099: 		       return '';
                   4100:                    }
                   4101:                }
1.620     albertel 4102:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4103:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4104: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4105:                        &log($env{'user.domain'},$env{'user.name'},
                   4106:                             $env{'user.home'},
1.57      www      4107:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4108:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4109:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4110: 		       return '';
                   4111:                    }
                   4112:                }
                   4113: 	   }
1.29      www      4114:        }
1.52      www      4115:     }
                   4116:    
                   4117: #
                   4118: # Rest of the restrictions depend on selected course
                   4119: #
                   4120: 
1.620     albertel 4121:     unless ($env{'request.course.id'}) {
1.766     albertel 4122: 	if ($thisallowed eq 'A') {
                   4123: 	    return 'A';
1.814     raeburn  4124:         } elsif ($thisallowed eq 'B') {
                   4125:             return 'B';
1.766     albertel 4126: 	} else {
                   4127: 	    return '1';
                   4128: 	}
1.52      www      4129:     }
1.29      www      4130: 
1.52      www      4131: #
                   4132: # Now user is definitely in a course
                   4133: #
1.53      www      4134: 
                   4135: 
                   4136: # Course preferences
                   4137: 
                   4138:    if ($thisallowed=~/C/) {
1.620     albertel 4139:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4140:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4141:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4142: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4143: 	   if ($priv ne 'pch') { 
                   4144: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4145: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4146: 			$env{'request.course.id'});
                   4147: 	   }
1.237     www      4148:            return '';
                   4149:        }
                   4150: 
1.620     albertel 4151:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4152: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4153: 	   if ($priv ne 'pch') { 
                   4154: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4155: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4156: 			$env{'request.course.id'});
                   4157: 	   }
1.54      www      4158:            return '';
                   4159:        }
1.53      www      4160:    }
                   4161: 
                   4162: # Resource preferences
                   4163: 
                   4164:    if ($thisallowed=~/R/) {
1.620     albertel 4165:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4166:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4167: 	   if ($priv ne 'pch') { 
                   4168: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4169: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4170: 	   }
                   4171: 	   return '';
1.54      www      4172:        }
1.53      www      4173:    }
1.30      www      4174: 
1.246     www      4175: # Restricted by state or randomout?
1.30      www      4176: 
1.52      www      4177:    if ($thisallowed=~/X/) {
1.620     albertel 4178:       if ($env{'acc.randomout'}) {
1.579     albertel 4179: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4180:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4181:             return ''; 
                   4182:          }
1.247     www      4183:       }
                   4184:       if (&condval($statecond)) {
1.52      www      4185: 	 return '2';
                   4186:       } else {
                   4187:          return '';
                   4188:       }
                   4189:    }
1.30      www      4190: 
1.766     albertel 4191:     if ($thisallowed eq 'A') {
                   4192: 	return 'A';
1.814     raeburn  4193:     } elsif ($thisallowed eq 'B') {
                   4194:         return 'B';
1.766     albertel 4195:     }
1.52      www      4196:    return 'F';
1.232     www      4197: }
                   4198: 
1.710     albertel 4199: sub split_uri_for_cond {
                   4200:     my $uri=&deversion(&declutter(shift));
                   4201:     my @uriparts=split(/\//,$uri);
                   4202:     my $filename=pop(@uriparts);
                   4203:     my $pathname=join('/',@uriparts);
                   4204:     return ($pathname,$filename);
                   4205: }
1.232     www      4206: # --------------------------------------------------- Is a resource on the map?
                   4207: 
                   4208: sub is_on_map {
1.710     albertel 4209:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4210:     #Trying to find the conditional for the file
1.620     albertel 4211:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4212: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4213:     if ($match) {
1.289     bowersj2 4214: 	return (1,$1);
                   4215:     } else {
1.434     www      4216: 	return (0,0);
1.289     bowersj2 4217:     }
1.12      www      4218: }
                   4219: 
1.427     www      4220: # --------------------------------------------------------- Get symb from alias
                   4221: 
                   4222: sub get_symb_from_alias {
                   4223:     my $symb=shift;
                   4224:     my ($map,$resid,$url)=&decode_symb($symb);
                   4225: # Already is a symb
                   4226:     if ($url) { return $symb; }
                   4227: # Must be an alias
                   4228:     my $aliassymb='';
                   4229:     my %bighash;
1.620     albertel 4230:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4231:                             &GDBM_READER(),0640)) {
                   4232:         my $rid=$bighash{'mapalias_'.$symb};
                   4233: 	if ($rid) {
                   4234: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4235: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4236: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4237: 	}
                   4238:         untie %bighash;
                   4239:     }
                   4240:     return $aliassymb;
                   4241: }
                   4242: 
1.12      www      4243: # ----------------------------------------------------------------- Define Role
                   4244: 
                   4245: sub definerole {
                   4246:   if (allowed('mcr','/')) {
                   4247:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4248:     foreach my $role (split(':',$sysrole)) {
                   4249: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4250:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4251:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4252: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4253:                return "refused:s:$crole&$cqual"; 
                   4254:             }
                   4255:         }
1.191     harris41 4256:     }
1.800     albertel 4257:     foreach my $role (split(':',$domrole)) {
                   4258: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4259:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4260:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4261: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4262:                return "refused:d:$crole&$cqual"; 
                   4263:             }
                   4264:         }
1.191     harris41 4265:     }
1.800     albertel 4266:     foreach my $role (split(':',$courole)) {
                   4267: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4268:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4269:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4270: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4271:                return "refused:c:$crole&$cqual"; 
                   4272:             }
                   4273:         }
1.191     harris41 4274:     }
1.620     albertel 4275:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4276:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4277: 	        "rolesdef_$rolename=".
                   4278:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4279:     return reply($command,$env{'user.home'});
1.12      www      4280:   } else {
                   4281:     return 'refused';
                   4282:   }
1.105     harris41 4283: }
                   4284: 
                   4285: # ---------------- Make a metadata query against the network of library servers
                   4286: 
                   4287: sub metadata_query {
1.244     matthew  4288:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4289:     my %rhash;
1.845     albertel 4290:     my %libserv = &all_library();
1.244     matthew  4291:     my @server_list = (defined($server_array) ? @$server_array
                   4292:                                               : keys(%libserv) );
                   4293:     for my $server (@server_list) {
1.118     harris41 4294: 	unless ($custom or $customshow) {
                   4295: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4296: 	    $rhash{$server}=$reply;
                   4297: 	}
                   4298: 	else {
                   4299: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4300: 			     &escape($custom).':'.&escape($customshow),
                   4301: 			     $server);
                   4302: 	    $rhash{$server}=$reply;
                   4303: 	}
1.112     harris41 4304:     }
1.118     harris41 4305:     return \%rhash;
1.240     www      4306: }
                   4307: 
                   4308: # ----------------------------------------- Send log queries and wait for reply
                   4309: 
                   4310: sub log_query {
                   4311:     my ($uname,$udom,$query,%filters)=@_;
                   4312:     my $uhome=&homeserver($uname,$udom);
                   4313:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4314:     my $uhost=&hostname($uhome);
1.800     albertel 4315:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4316:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4317:                        $uhome);
1.479     albertel 4318:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4319:     return get_query_reply($queryid);
                   4320: }
                   4321: 
1.818     raeburn  4322: # -------------------------- Update MySQL table for portfolio file
                   4323: 
                   4324: sub update_portfolio_table {
1.821     raeburn  4325:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4326:     my $homeserver = &homeserver($uname,$udom);
                   4327:     my $queryid=
1.821     raeburn  4328:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4329:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4330:     my $reply = &get_query_reply($queryid);
                   4331:     return $reply;
                   4332: }
                   4333: 
1.508     raeburn  4334: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4335: 
                   4336: sub fetch_enrollment_query {
1.511     raeburn  4337:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4338:     my $homeserver;
1.547     raeburn  4339:     my $maxtries = 1;
1.508     raeburn  4340:     if ($context eq 'automated') {
                   4341:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4342:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4343:     } else {
                   4344:         $homeserver = &homeserver($cnum,$dom);
                   4345:     }
1.838     albertel 4346:     my $host=&hostname($homeserver);
1.506     raeburn  4347:     my $cmd = '';
1.800     albertel 4348:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4349:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4350:     }
                   4351:     $cmd =~ s/%%$//;
                   4352:     $cmd = &escape($cmd);
                   4353:     my $query = 'fetchenrollment';
1.620     albertel 4354:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4355:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4356:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4357:         return 'error: '.$queryid;
                   4358:     }
1.506     raeburn  4359:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4360:     my $tries = 1;
                   4361:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4362:         $reply = &get_query_reply($queryid);
                   4363:         $tries ++;
                   4364:     }
1.526     raeburn  4365:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4366:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4367:     } else {
1.515     raeburn  4368:         my @responses = split/:/,$reply;
                   4369:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4370:             foreach my $line (@responses) {
                   4371:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4372:                 $$replyref{$key} = $value;
                   4373:             }
                   4374:         } else {
1.506     raeburn  4375:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4376:             foreach my $line (@responses) {
                   4377:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4378:                 $$replyref{$key} = $value;
                   4379:                 if ($value > 0) {
1.800     albertel 4380:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4381:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4382:                         my $destname = $pathname.'/'.$filename;
                   4383:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4384:                         if ($xml_classlist =~ /^error/) {
                   4385:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4386:                         } else {
1.506     raeburn  4387:                             if ( open(FILE,">$destname") ) {
                   4388:                                 print FILE &unescape($xml_classlist);
                   4389:                                 close(FILE);
1.526     raeburn  4390:                             } else {
                   4391:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4392:                             }
                   4393:                         }
                   4394:                     }
                   4395:                 }
                   4396:             }
                   4397:         }
                   4398:         return 'ok';
                   4399:     }
                   4400:     return 'error';
                   4401: }
                   4402: 
1.242     www      4403: sub get_query_reply {
                   4404:     my $queryid=shift;
1.240     www      4405:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4406:     my $reply='';
                   4407:     for (1..100) {
                   4408: 	sleep 2;
                   4409:         if (-e $replyfile.'.end') {
1.448     albertel 4410: 	    if (open(my $fh,$replyfile)) {
1.240     www      4411:                $reply.=<$fh>;
1.448     albertel 4412:                close($fh);
1.240     www      4413: 	   } else { return 'error: reply_file_error'; }
1.242     www      4414:            return &unescape($reply);
                   4415: 	}
1.240     www      4416:     }
1.242     www      4417:     return 'timeout:'.$queryid;
1.240     www      4418: }
                   4419: 
                   4420: sub courselog_query {
1.241     www      4421: #
                   4422: # possible filters:
                   4423: # url: url or symb
                   4424: # username
                   4425: # domain
                   4426: # action: view, submit, grade
                   4427: # start: timestamp
                   4428: # end: timestamp
                   4429: #
1.240     www      4430:     my (%filters)=@_;
1.620     albertel 4431:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4432:     if ($filters{'url'}) {
                   4433: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4434:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4435:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4436:     }
1.620     albertel 4437:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4438:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4439:     return &log_query($cname,$cdom,'courselog',%filters);
                   4440: }
                   4441: 
                   4442: sub userlog_query {
1.858     raeburn  4443: #
                   4444: # possible filters:
                   4445: # action: log check role
                   4446: # start: timestamp
                   4447: # end: timestamp
                   4448: #
1.240     www      4449:     my ($uname,$udom,%filters)=@_;
                   4450:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4451: }
                   4452: 
1.506     raeburn  4453: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4454: 
                   4455: sub auto_run {
1.508     raeburn  4456:     my ($cnum,$cdom) = @_;
1.876     raeburn  4457:     my $response = 0;
                   4458:     my $settings;
                   4459:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4460:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4461:         $settings = $domconfig{'autoenroll'};
                   4462:         if ($settings->{'run'} eq '1') {
                   4463:             $response = 1;
                   4464:         }
                   4465:     } else {
                   4466:         my $homeserver = &homeserver($cnum,$cdom);
                   4467:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4468:     }
1.506     raeburn  4469:     return $response;
                   4470: }
1.776     albertel 4471: 
1.506     raeburn  4472: sub auto_get_sections {
1.508     raeburn  4473:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4474:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4475:     my @secs = ();
1.511     raeburn  4476:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4477:     unless ($response eq 'refused') {
                   4478:         @secs = split/:/,$response;
                   4479:     }
                   4480:     return @secs;
                   4481: }
1.776     albertel 4482: 
1.506     raeburn  4483: sub auto_new_course {
1.508     raeburn  4484:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4485:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4486:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4487:     return $response;
                   4488: }
1.776     albertel 4489: 
1.506     raeburn  4490: sub auto_validate_courseID {
1.508     raeburn  4491:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4492:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4493:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4494:     return $response;
                   4495: }
1.776     albertel 4496: 
1.506     raeburn  4497: sub auto_create_password {
1.873     raeburn  4498:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4499:     my ($homeserver,$response);
1.506     raeburn  4500:     my $create_passwd = 0;
                   4501:     my $authchk = '';
1.873     raeburn  4502:     if ($udom =~ /^$match_domain$/) {
                   4503:         $homeserver = &domain($udom,'primary');
                   4504:     }
                   4505:     if ($homeserver eq '') {
                   4506:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4507:             $homeserver = &homeserver($cnum,$cdom);
                   4508:         }
                   4509:     }
                   4510:     if ($homeserver eq '') {
                   4511:         $authchk = 'nodomain';
1.506     raeburn  4512:     } else {
1.873     raeburn  4513:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4514:         if ($response eq 'refused') {
                   4515:             $authchk = 'refused';
                   4516:         } else {
                   4517:             ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4518:         }
1.506     raeburn  4519:     }
                   4520:     return ($authparam,$create_passwd,$authchk);
                   4521: }
                   4522: 
1.706     raeburn  4523: sub auto_photo_permission {
                   4524:     my ($cnum,$cdom,$students) = @_;
                   4525:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4526:     my ($outcome,$perm_reqd,$conditions) = 
                   4527: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4528:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4529: 	return (undef,undef);
                   4530:     }
1.706     raeburn  4531:     return ($outcome,$perm_reqd,$conditions);
                   4532: }
                   4533: 
                   4534: sub auto_checkphotos {
                   4535:     my ($uname,$udom,$pid) = @_;
                   4536:     my $homeserver = &homeserver($uname,$udom);
                   4537:     my ($result,$resulttype);
                   4538:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4539: 				   &escape($uname).':'.&escape($pid),
                   4540: 				   $homeserver));
1.709     albertel 4541:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4542: 	return (undef,undef);
                   4543:     }
1.706     raeburn  4544:     if ($outcome) {
                   4545:         ($result,$resulttype) = split(/:/,$outcome);
                   4546:     } 
                   4547:     return ($result,$resulttype);
                   4548: }
                   4549: 
                   4550: sub auto_photochoice {
                   4551:     my ($cnum,$cdom) = @_;
                   4552:     my $homeserver = &homeserver($cnum,$cdom);
                   4553:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4554: 						       &escape($cdom),
                   4555: 						       $homeserver)));
1.709     albertel 4556:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4557: 	return (undef,undef);
                   4558:     }
1.706     raeburn  4559:     return ($update,$comment);
                   4560: }
                   4561: 
                   4562: sub auto_photoupdate {
                   4563:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4564:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4565:     my $host=&hostname($homeserver);
1.706     raeburn  4566:     my $cmd = '';
                   4567:     my $maxtries = 1;
1.800     albertel 4568:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4569:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4570:     }
                   4571:     $cmd =~ s/%%$//;
                   4572:     $cmd = &escape($cmd);
                   4573:     my $query = 'institutionalphotos';
                   4574:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4575:     unless ($queryid=~/^\Q$host\E\_/) {
                   4576:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4577:         return 'error: '.$queryid;
                   4578:     }
                   4579:     my $reply = &get_query_reply($queryid);
                   4580:     my $tries = 1;
                   4581:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4582:         $reply = &get_query_reply($queryid);
                   4583:         $tries ++;
                   4584:     }
                   4585:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4586:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4587:     } else {
                   4588:         my @responses = split(/:/,$reply);
                   4589:         my $outcome = shift(@responses); 
                   4590:         foreach my $item (@responses) {
                   4591:             my ($key,$value) = split(/=/,$item);
                   4592:             $$photo{$key} = $value;
                   4593:         }
                   4594:         return $outcome;
                   4595:     }
                   4596:     return 'error';
                   4597: }
                   4598: 
1.521     raeburn  4599: sub auto_instcode_format {
1.793     albertel 4600:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4601: 	$cat_order) = @_;
1.521     raeburn  4602:     my $courses = '';
1.772     raeburn  4603:     my @homeservers;
1.521     raeburn  4604:     if ($caller eq 'global') {
1.841     albertel 4605: 	my %servers = &get_servers($codedom,'library');
                   4606: 	foreach my $tryserver (keys(%servers)) {
                   4607: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4608: 		push(@homeservers,$tryserver);
                   4609: 	    }
1.584     raeburn  4610:         }
1.521     raeburn  4611:     } else {
1.772     raeburn  4612:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4613:     }
1.793     albertel 4614:     foreach my $code (keys(%{$instcodes})) {
                   4615:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4616:     }
                   4617:     chop($courses);
1.772     raeburn  4618:     my $ok_response = 0;
                   4619:     my $response;
                   4620:     while (@homeservers > 0 && $ok_response == 0) {
                   4621:         my $server = shift(@homeservers); 
                   4622:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4623:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4624:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4625: 		split/:/,$response;
1.772     raeburn  4626:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4627:             push(@{$codetitles},&str2array($codetitles_str));
                   4628:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4629:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4630:             $ok_response = 1;
                   4631:         }
                   4632:     }
                   4633:     if ($ok_response) {
1.521     raeburn  4634:         return 'ok';
1.772     raeburn  4635:     } else {
                   4636:         return $response;
1.521     raeburn  4637:     }
                   4638: }
                   4639: 
1.792     raeburn  4640: sub auto_instcode_defaults {
                   4641:     my ($domain,$returnhash,$code_order) = @_;
                   4642:     my @homeservers;
1.841     albertel 4643: 
                   4644:     my %servers = &get_servers($domain,'library');
                   4645:     foreach my $tryserver (keys(%servers)) {
                   4646: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4647: 	    push(@homeservers,$tryserver);
                   4648: 	}
1.792     raeburn  4649:     }
1.841     albertel 4650: 
1.792     raeburn  4651:     my $response;
1.841     albertel 4652:     foreach my $server (@homeservers) {
1.792     raeburn  4653:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4654:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4655: 	
                   4656: 	foreach my $pair (split(/\&/,$response)) {
                   4657: 	    my ($name,$value)=split(/\=/,$pair);
                   4658: 	    if ($name eq 'code_order') {
                   4659: 		@{$code_order} = split(/\&/,&unescape($value));
                   4660: 	    } else {
                   4661: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4662: 	    }
                   4663: 	}
                   4664: 	return 'ok';
1.792     raeburn  4665:     }
1.841     albertel 4666: 
                   4667:     return $response;
1.792     raeburn  4668: } 
                   4669: 
1.777     albertel 4670: sub auto_validate_class_sec {
1.773     raeburn  4671:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4672:     my $homeserver = &homeserver($cnum,$cdom);
                   4673:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4674:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4675:     return $response;
                   4676: }
                   4677: 
1.679     raeburn  4678: # ------------------------------------------------------- Course Group routines
                   4679: 
                   4680: sub get_coursegroups {
1.809     raeburn  4681:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4682:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4683: }
                   4684: 
1.679     raeburn  4685: sub modify_coursegroup {
                   4686:     my ($cdom,$cnum,$groupsettings) = @_;
                   4687:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4688: }
                   4689: 
1.809     raeburn  4690: sub toggle_coursegroup_status {
                   4691:     my ($cdom,$cnum,$group,$action) = @_;
                   4692:     my ($from_namespace,$to_namespace);
                   4693:     if ($action eq 'delete') {
                   4694:         $from_namespace = 'coursegroups';
                   4695:         $to_namespace = 'deleted_groups';
                   4696:     } else {
                   4697:         $from_namespace = 'deleted_groups';
                   4698:         $to_namespace = 'coursegroups';
                   4699:     }
                   4700:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4701:     if (my $tmp = &error(%curr_group)) {
                   4702:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4703:         return ('read error',$tmp);
                   4704:     } else {
                   4705:         my %savedsettings = %curr_group; 
1.809     raeburn  4706:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4707:         my $deloutcome;
                   4708:         if ($result eq 'ok') {
1.809     raeburn  4709:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4710:         } else {
                   4711:             return ('write error',$result);
                   4712:         }
                   4713:         if ($deloutcome eq 'ok') {
                   4714:             return 'ok';
                   4715:         } else {
                   4716:             return ('delete error',$deloutcome);
                   4717:         }
                   4718:     }
                   4719: }
                   4720: 
1.679     raeburn  4721: sub modify_group_roles {
                   4722:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4723:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4724:     my $role = 'gr/'.&escape($userprivs);
                   4725:     my ($uname,$udom) = split(/:/,$user);
                   4726:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4727:     if ($result eq 'ok') {
                   4728:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4729:     }
1.679     raeburn  4730:     return $result;
                   4731: }
                   4732: 
                   4733: sub modify_coursegroup_membership {
                   4734:     my ($cdom,$cnum,$membership) = @_;
                   4735:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4736:     return $result;
                   4737: }
                   4738: 
1.682     raeburn  4739: sub get_active_groups {
                   4740:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4741:     my $now = time;
                   4742:     my %groups = ();
                   4743:     foreach my $key (keys(%env)) {
1.811     albertel 4744:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4745:             my ($start,$end) = split(/\./,$env{$key});
                   4746:             if (($end!=0) && ($end<$now)) { next; }
                   4747:             if (($start!=0) && ($start>$now)) { next; }
                   4748:             if ($1 eq $cdom && $2 eq $cnum) {
                   4749:                 $groups{$3} = $env{$key} ;
                   4750:             }
                   4751:         }
                   4752:     }
                   4753:     return %groups;
                   4754: }
                   4755: 
1.683     raeburn  4756: sub get_group_membership {
                   4757:     my ($cdom,$cnum,$group) = @_;
                   4758:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4759: }
                   4760: 
                   4761: sub get_users_groups {
                   4762:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4763:     my @usersgroups;
1.683     raeburn  4764:     my $cachetime=1800;
                   4765: 
                   4766:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4767:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4768:     if (defined($cached)) {
1.734     albertel 4769:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4770:     } else {  
                   4771:         $grouplist = '';
1.816     raeburn  4772:         my $courseurl = &courseid_to_courseurl($courseid);
                   4773:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4774:         my $access_end = $env{'course.'.$courseid.
                   4775:                               '.default_enrollment_end_date'};
                   4776:         my $now = time;
                   4777:         foreach my $key (keys(%roleshash)) {
                   4778:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4779:                 my $group = $1;
                   4780:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4781:                     my $start = $2;
                   4782:                     my $end = $1;
                   4783:                     if ($start == -1) { next; } # deleted from group
                   4784:                     if (($start!=0) && ($start>$now)) { next; }
                   4785:                     if (($end!=0) && ($end<$now)) {
                   4786:                         if ($access_end && $access_end < $now) {
                   4787:                             if ($access_end - $end < 86400) {
                   4788:                                 push(@usersgroups,$group);
1.733     raeburn  4789:                             }
                   4790:                         }
1.817     raeburn  4791:                         next;
1.733     raeburn  4792:                     }
1.817     raeburn  4793:                     push(@usersgroups,$group);
1.683     raeburn  4794:                 }
                   4795:             }
                   4796:         }
1.817     raeburn  4797:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4798:         $grouplist = join(':',@usersgroups);
                   4799:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4800:     }
1.733     raeburn  4801:     return @usersgroups;
1.683     raeburn  4802: }
                   4803: 
                   4804: sub devalidate_getgroups_cache {
                   4805:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4806:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4807: 
1.683     raeburn  4808:     my $hashid="$udom:$uname:$courseid";
                   4809:     &devalidate_cache_new('getgroups',$hashid);
                   4810: }
                   4811: 
1.12      www      4812: # ------------------------------------------------------------------ Plain Text
                   4813: 
                   4814: sub plaintext {
1.742     raeburn  4815:     my ($short,$type,$cid) = @_;
1.758     albertel 4816:     if ($short =~ /^cr/) {
                   4817: 	return (split('/',$short))[-1];
                   4818:     }
1.742     raeburn  4819:     if (!defined($cid)) {
                   4820:         $cid = $env{'request.course.id'};
                   4821:     }
                   4822:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4823:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4824:                                           '.plaintext'});
                   4825:     }
                   4826:     my %rolenames = (
                   4827:                       Course => 'std',
                   4828:                       Group => 'alt1',
                   4829:                     );
                   4830:     if (defined($type) && 
                   4831:          defined($rolenames{$type}) && 
                   4832:          defined($prp{$short}{$rolenames{$type}})) {
                   4833:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4834:     } else {
                   4835:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4836:     }
1.12      www      4837: }
                   4838: 
                   4839: # ----------------------------------------------------------------- Assign Role
                   4840: 
                   4841: sub assignrole {
1.357     www      4842:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4843:     my $mrole;
                   4844:     if ($role =~ /^cr\//) {
1.393     www      4845:         my $cwosec=$url;
1.811     albertel 4846:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4847: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4848:            &logthis('Refused custom assignrole: '.
                   4849:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4850: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4851:            return 'refused'; 
                   4852:         }
1.21      www      4853:         $mrole='cr';
1.678     raeburn  4854:     } elsif ($role =~ /^gr\//) {
                   4855:         my $cwogrp=$url;
1.811     albertel 4856:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4857:         unless (&allowed('mdg',$cwogrp)) {
                   4858:             &logthis('Refused group assignrole: '.
                   4859:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4860:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4861:             return 'refused';
                   4862:         }
                   4863:         $mrole='gr';
1.21      www      4864:     } else {
1.82      www      4865:         my $cwosec=$url;
1.811     albertel 4866:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4867:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4868:            &logthis('Refused assignrole: '.
                   4869:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4870: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4871:            return 'refused'; 
                   4872:         }
1.21      www      4873:         $mrole=$role;
                   4874:     }
1.620     albertel 4875:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4876:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4877:     if ($end) { $command.='_'.$end; }
1.21      www      4878:     if ($start) {
                   4879: 	if ($end) { 
1.81      www      4880:            $command.='_'.$start; 
1.21      www      4881:         } else {
1.81      www      4882:            $command.='_0_'.$start;
1.21      www      4883:         }
                   4884:     }
1.739     raeburn  4885:     my $origstart = $start;
                   4886:     my $origend = $end;
1.357     www      4887: # actually delete
                   4888:     if ($deleteflag) {
1.373     www      4889: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4890: # modify command to delete the role
1.620     albertel 4891:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4892:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4893: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4894: # set start and finish to negative values for userrolelog
                   4895:            $start=-1;
                   4896:            $end=-1;
                   4897:         }
                   4898:     }
                   4899: # send command
1.349     www      4900:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4901: # log new user role if status is ok
1.349     www      4902:     if ($answer eq 'ok') {
1.663     raeburn  4903: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4904: # for course roles, perform group memberships changes triggered by role change.
                   4905:         unless ($role =~ /^gr/) {
                   4906:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4907:                                              $origstart);
                   4908:         }
1.349     www      4909:     }
                   4910:     return $answer;
1.169     harris41 4911: }
                   4912: 
                   4913: # -------------------------------------------------- Modify user authentication
1.197     www      4914: # Overrides without validation
                   4915: 
1.169     harris41 4916: sub modifyuserauth {
                   4917:     my ($udom,$uname,$umode,$upass)=@_;
                   4918:     my $uhome=&homeserver($uname,$udom);
1.197     www      4919:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4920:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4921:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4922:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4923:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4924: 		     &escape($upass),$uhome);
1.620     albertel 4925:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4926:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4927:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4928:     &log($udom,,$uname,$uhome,
1.620     albertel 4929:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4930:                                      $env{'user.name'}.', '.$umode.
1.197     www      4931:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4932:     unless ($reply eq 'ok') {
1.197     www      4933:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4934: 	return 'error: '.$reply;
                   4935:     }   
1.170     harris41 4936:     return 'ok';
1.80      www      4937: }
                   4938: 
1.81      www      4939: # --------------------------------------------------------------- Modify a user
1.80      www      4940: 
1.81      www      4941: sub modifyuser {
1.206     matthew  4942:     my ($udom,    $uname, $uid,
                   4943:         $umode,   $upass, $first,
                   4944:         $middle,  $last,  $gene,
1.387     www      4945:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4946:     $udom= &LONCAPA::clean_domain($udom);
                   4947:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4948:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4949:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4950: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4951:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4952:                                      ' desiredhome not specified'). 
1.620     albertel 4953:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4954:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4955:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4956: # ----------------------------------------------------------------- Create User
1.406     albertel 4957:     if (($uhome eq 'no_host') && 
                   4958: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4959:         my $unhome='';
1.844     albertel 4960:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4961:             $unhome = $desiredhome;
1.620     albertel 4962: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4963: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4964:         } else { # load balancing routine for determining $unhome
1.81      www      4965:             my $loadm=10000000;
1.841     albertel 4966: 	    my %servers = &get_servers($udom,'library');
                   4967: 	    foreach my $tryserver (keys(%servers)) {
                   4968: 		my $answer=reply('load',$tryserver);
                   4969: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4970: 		    $loadm=$answer;
                   4971: 		    $unhome=$tryserver;
                   4972: 		}
1.80      www      4973: 	    }
                   4974:         }
                   4975:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4976: 	    return 'error: unable to find a home server for '.$uname.
                   4977:                    ' in domain '.$udom;
1.80      www      4978:         }
                   4979:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4980:                          &escape($upass),$unhome);
                   4981: 	unless ($reply eq 'ok') {
                   4982:             return 'error: '.$reply;
                   4983:         }   
1.230     stredwic 4984:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4985:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4986: 	    return 'error: unable verify users home machine.';
1.80      www      4987:         }
1.209     matthew  4988:     }   # End of creation of new user
1.80      www      4989: # ---------------------------------------------------------------------- Add ID
                   4990:     if ($uid) {
                   4991:        $uid=~tr/A-Z/a-z/;
                   4992:        my %uidhash=&idrget($udom,$uname);
1.196     www      4993:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4994:          && (!$forceid)) {
1.80      www      4995: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4996: 	      return 'error: user id "'.$uid.'" does not match '.
                   4997:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4998:           }
                   4999:        } else {
                   5000: 	  &idput($udom,($uname => $uid));
                   5001:        }
                   5002:     }
                   5003: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5004:     my @tmp=&get('environment',
1.134     albertel 5005: 		   ['firstname','middlename','lastname','generation'],
                   5006: 		   $udom,$uname);
1.313     matthew  5007:     my %names;
                   5008:     if ($tmp[0] =~ m/^error:.*/) { 
                   5009:         %names=(); 
                   5010:     } else {
                   5011:         %names = @tmp;
                   5012:     }
1.388     www      5013: #
                   5014: # Make sure to not trash student environment if instructor does not bother
                   5015: # to supply name and email information
                   5016: #
                   5017:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5018:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5019:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5020:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5021:     if ($email) {
                   5022:        $email=~s/[^\w\@\.\-\,]//gs;
                   5023:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5024: 			   $names{'critnotification'} = $email;
                   5025: 			   $names{'permanentemail'} = $email; }
                   5026:     }
1.134     albertel 5027:     my $reply = &put('environment', \%names, $udom,$uname);
                   5028:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      5029:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5030:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5031:              $umode.', '.$first.', '.$middle.', '.
                   5032: 	     $last.', '.$gene.' by '.
1.620     albertel 5033:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5034:     return 'ok';
1.80      www      5035: }
                   5036: 
1.81      www      5037: # -------------------------------------------------------------- Modify student
1.80      www      5038: 
1.81      www      5039: sub modifystudent {
                   5040:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5041:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5042:     if (!$cid) {
1.620     albertel 5043: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5044: 	    return 'not_in_class';
                   5045: 	}
1.80      www      5046:     }
                   5047: # --------------------------------------------------------------- Make the user
1.81      www      5048:     my $reply=&modifyuser
1.209     matthew  5049: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5050:          $desiredhome,$email);
1.80      www      5051:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5052:     # This will cause &modify_student_enrollment to get the uid from the
                   5053:     # students environment
                   5054:     $uid = undef if (!$forceid);
1.455     albertel 5055:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5056: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5057:     return $reply;
                   5058: }
                   5059: 
                   5060: sub modify_student_enrollment {
1.515     raeburn  5061:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5062:     my ($cdom,$cnum,$chome);
                   5063:     if (!$cid) {
1.620     albertel 5064: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5065: 	    return 'not_in_class';
                   5066: 	}
1.620     albertel 5067: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5068: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5069:     } else {
                   5070: 	($cdom,$cnum)=split(/_/,$cid);
                   5071:     }
1.620     albertel 5072:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5073:     if (!$chome) {
1.457     raeburn  5074: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5075:     }
1.455     albertel 5076:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5077:     # Make sure the user exists
1.81      www      5078:     my $uhome=&homeserver($uname,$udom);
                   5079:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5080: 	return 'error: no such user';
                   5081:     }
1.297     matthew  5082:     # Get student data if we were not given enough information
                   5083:     if (!defined($first)  || $first  eq '' || 
                   5084:         !defined($last)   || $last   eq '' || 
                   5085:         !defined($uid)    || $uid    eq '' || 
                   5086:         !defined($middle) || $middle eq '' || 
                   5087:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5088:         # They did not supply us with enough data to enroll the student, so
                   5089:         # we need to pick up more information.
1.297     matthew  5090:         my %tmp = &get('environment',
1.294     matthew  5091:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5092:                        ,$udom,$uname);
                   5093: 
1.800     albertel 5094:         #foreach my $key (keys(%tmp)) {
                   5095:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5096:         #}
1.294     matthew  5097:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5098:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5099:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5100:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5101:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5102:     }
1.556     albertel 5103:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5104:     my $reply=cput('classlist',
                   5105: 		   {"$uname:$udom" => 
1.515     raeburn  5106: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5107: 		   $cdom,$cnum);
1.81      www      5108:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5109: 	return 'error: '.$reply;
1.652     albertel 5110:     } else {
                   5111: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5112:     }
1.297     matthew  5113:     # Add student role to user
1.83      www      5114:     my $uurl='/'.$cid;
1.81      www      5115:     $uurl=~s/\_/\//g;
                   5116:     if ($usec) {
                   5117: 	$uurl.='/'.$usec;
                   5118:     }
                   5119:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5120: }
                   5121: 
1.556     albertel 5122: sub format_name {
                   5123:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5124:     my $name;
                   5125:     if ($first ne 'lastname') {
                   5126: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5127:     } else {
                   5128: 	if ($lastname=~/\S/) {
                   5129: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5130: 	    $name=~s/\s+,/,/;
                   5131: 	} else {
                   5132: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5133: 	}
                   5134:     }
                   5135:     $name=~s/^\s+//;
                   5136:     $name=~s/\s+$//;
                   5137:     $name=~s/\s+/ /g;
                   5138:     return $name;
                   5139: }
                   5140: 
1.84      www      5141: # ------------------------------------------------- Write to course preferences
                   5142: 
                   5143: sub writecoursepref {
                   5144:     my ($courseid,%prefs)=@_;
                   5145:     $courseid=~s/^\///;
                   5146:     $courseid=~s/\_/\//g;
                   5147:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5148:     my $chome=homeserver($cnum,$cdomain);
                   5149:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5150: 	return 'error: no such course';
                   5151:     }
                   5152:     my $cstring='';
1.800     albertel 5153:     foreach my $pref (keys(%prefs)) {
                   5154: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5155:     }
1.84      www      5156:     $cstring=~s/\&$//;
                   5157:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5158: }
                   5159: 
                   5160: # ---------------------------------------------------------- Make/modify course
                   5161: 
                   5162: sub createcourse {
1.741     raeburn  5163:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5164:         $course_owner,$crstype)=@_;
1.84      www      5165:     $url=&declutter($url);
                   5166:     my $cid='';
1.264     matthew  5167:     unless (&allowed('ccc',$udom)) {
1.84      www      5168:         return 'refused';
                   5169:     }
                   5170: # ------------------------------------------------------------------- Create ID
1.674     www      5171:    my $uname=int(1+rand(9)).
                   5172:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5173:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5174:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5175: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5176:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5177:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5178:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5179:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5180:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5181:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5182:            return 'error: unable to generate unique course-ID';
                   5183:        } 
                   5184:    }
1.264     matthew  5185: # ------------------------------------------------ Check supplied server name
1.620     albertel 5186:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5187:     if (! &is_library($course_server)) {
1.264     matthew  5188:         return 'error:bad server name '.$course_server;
                   5189:     }
1.84      www      5190: # ------------------------------------------------------------- Make the course
                   5191:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5192:                       $course_server);
1.84      www      5193:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5194:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5195:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5196: 	return 'error: no such course';
                   5197:     }
1.271     www      5198: # ----------------------------------------------------------------- Course made
1.516     raeburn  5199: # log existence
                   5200:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5201:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5202:                   &escape($crstype),$uhome);
1.358     www      5203:     &flushcourselogs();
                   5204: # set toplevel url
1.271     www      5205:     my $topurl=$url;
                   5206:     unless ($nonstandard) {
                   5207: # ------------------------------------------ For standard courses, make top url
                   5208:         my $mapurl=&clutter($url);
1.278     www      5209:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5210:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5211: <map>
                   5212: <resource id="1" type="start"></resource>
                   5213: <resource id="2" src="$mapurl"></resource>
                   5214: <resource id="3" type="finish"></resource>
                   5215: <link index="1" from="1" to="2"></link>
                   5216: <link index="2" from="2" to="3"></link>
                   5217: </map>
                   5218: ENDINITMAP
                   5219:         $topurl=&declutter(
1.638     albertel 5220:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5221:                           );
                   5222:     }
                   5223: # ----------------------------------------------------------- Write preferences
1.84      www      5224:     &writecoursepref($udom.'_'.$uname,
                   5225:                      ('description' => $description,
1.271     www      5226:                       'url'         => $topurl));
1.84      www      5227:     return '/'.$udom.'/'.$uname;
                   5228: }
                   5229: 
1.813     albertel 5230: sub is_course {
                   5231:     my ($cdom,$cnum) = @_;
                   5232:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5233: 				undef,'.');
                   5234:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5235:         return 1;
                   5236:     }
                   5237:     return 0;
                   5238: }
                   5239: 
1.21      www      5240: # ---------------------------------------------------------- Assign Custom Role
                   5241: 
                   5242: sub assigncustomrole {
1.357     www      5243:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5244:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5245:                        $end,$start,$deleteflag);
1.21      www      5246: }
                   5247: 
                   5248: # ----------------------------------------------------------------- Revoke Role
                   5249: 
                   5250: sub revokerole {
1.357     www      5251:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5252:     my $now=time;
1.357     www      5253:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5254: }
                   5255: 
                   5256: # ---------------------------------------------------------- Revoke Custom Role
                   5257: 
                   5258: sub revokecustomrole {
1.357     www      5259:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5260:     my $now=time;
1.357     www      5261:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5262:            $deleteflag);
1.17      www      5263: }
                   5264: 
1.533     banghart 5265: # ------------------------------------------------------------ Disk usage
1.535     albertel 5266: sub diskusage {
1.533     banghart 5267:     my ($udom,$uname,$directoryRoot)=@_;
                   5268:     $directoryRoot =~ s/\/$//;
1.535     albertel 5269:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5270:     return $listing;
1.512     banghart 5271: }
                   5272: 
1.566     banghart 5273: sub is_locked {
                   5274:     my ($file_name, $domain, $user) = @_;
                   5275:     my @check;
                   5276:     my $is_locked;
                   5277:     push @check, $file_name;
1.613     albertel 5278:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5279: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5280:     my ($tmp)=keys(%locked);
                   5281:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5282:     
1.566     banghart 5283:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5284:         $is_locked = 'false';
                   5285:         foreach my $entry (@{$locked{$file_name}}) {
                   5286:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5287:                $is_locked = 'true';
                   5288:                last;
1.745     raeburn  5289:            }
                   5290:        }
1.566     banghart 5291:     } else {
                   5292:         $is_locked = 'false';
                   5293:     }
                   5294: }
                   5295: 
1.759     albertel 5296: sub declutter_portfile {
                   5297:     my ($file) = @_;
1.833     albertel 5298:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5299:     return $file;
                   5300: }
                   5301: 
1.559     banghart 5302: # ------------------------------------------------------------- Mark as Read Only
                   5303: 
                   5304: sub mark_as_readonly {
                   5305:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5306:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5307:     my ($tmp)=keys(%current_permissions);
                   5308:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5309:     foreach my $file (@{$files}) {
1.759     albertel 5310: 	$file = &declutter_portfile($file);
1.561     banghart 5311:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5312:     }
1.613     albertel 5313:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5314:     return;
                   5315: }
                   5316: 
1.572     banghart 5317: # ------------------------------------------------------------Save Selected Files
                   5318: 
                   5319: sub save_selected_files {
                   5320:     my ($user, $path, @files) = @_;
                   5321:     my $filename = $user."savedfiles";
1.573     banghart 5322:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5323:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5324:     foreach my $file (@files) {
1.620     albertel 5325:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5326:     }
                   5327:     foreach my $file (@other_files) {
1.574     banghart 5328:         print (OUT $file."\n");
1.572     banghart 5329:     }
1.574     banghart 5330:     close (OUT);
1.572     banghart 5331:     return 'ok';
                   5332: }
                   5333: 
1.574     banghart 5334: sub clear_selected_files {
                   5335:     my ($user) = @_;
                   5336:     my $filename = $user."savedfiles";
                   5337:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5338:     print (OUT undef);
                   5339:     close (OUT);
                   5340:     return ("ok");    
                   5341: }
                   5342: 
1.572     banghart 5343: sub files_in_path {
                   5344:     my ($user, $path) = @_;
                   5345:     my $filename = $user."savedfiles";
                   5346:     my %return_files;
1.574     banghart 5347:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5348:     while (my $line_in = <IN>) {
1.574     banghart 5349:         chomp ($line_in);
                   5350:         my @paths_and_file = split (m!/!, $line_in);
                   5351:         my $file_part = pop (@paths_and_file);
                   5352:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5353:         $path_part.='/';
                   5354:         my $path_and_file = $path_part.$file_part;
                   5355:         if ($path_part eq $path) {
                   5356:             $return_files{$file_part}= 'selected';
                   5357:         }
                   5358:     }
1.574     banghart 5359:     close (IN);
                   5360:     return (\%return_files);
1.572     banghart 5361: }
                   5362: 
                   5363: # called in portfolio select mode, to show files selected NOT in current directory
                   5364: sub files_not_in_path {
                   5365:     my ($user, $path) = @_;
                   5366:     my $filename = $user."savedfiles";
                   5367:     my @return_files;
                   5368:     my $path_part;
1.800     albertel 5369:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5370:     while (my $line = <IN>) {
1.572     banghart 5371:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5372:         my @paths_and_file = split(m|/|, $line);
                   5373:         my $file_part = pop(@paths_and_file);
                   5374:         chomp($file_part);
                   5375:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5376:         $path_part .= '/';
                   5377:         my $path_and_file = $path_part.$file_part;
                   5378:         if ($path_part ne $path) {
1.800     albertel 5379:             push(@return_files, ($path_and_file));
1.572     banghart 5380:         }
                   5381:     }
1.800     albertel 5382:     close(OUT);
1.574     banghart 5383:     return (@return_files);
1.572     banghart 5384: }
                   5385: 
1.745     raeburn  5386: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5387: 
1.745     raeburn  5388: sub get_portfile_permissions {
                   5389:     my ($domain,$user) = @_;
1.613     albertel 5390:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5391:     my ($tmp)=keys(%current_permissions);
                   5392:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5393:     return \%current_permissions;
                   5394: }
                   5395: 
                   5396: #---------------------------------------------Get portfolio file access controls
                   5397: 
1.749     raeburn  5398: sub get_access_controls {
1.745     raeburn  5399:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5400:     my %access;
                   5401:     my $real_file = $file;
                   5402:     $file =~ s/\.meta$//;
1.745     raeburn  5403:     if (defined($file)) {
1.749     raeburn  5404:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5405:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5406:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5407:             }
                   5408:         }
1.745     raeburn  5409:     } else {
1.749     raeburn  5410:         foreach my $key (keys(%{$current_permissions})) {
                   5411:             if ($key =~ /\0accesscontrol$/) {
                   5412:                 if (defined($group)) {
                   5413:                     if ($key !~ m-^\Q$group\E/-) {
                   5414:                         next;
                   5415:                     }
                   5416:                 }
                   5417:                 my ($fullpath) = split(/\0/,$key);
                   5418:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5419:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5420:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5421:                     }
                   5422:                 }
                   5423:             }
                   5424:         }
                   5425:     }
                   5426:     return %access;
                   5427: }
                   5428: 
                   5429: sub modify_access_controls {
                   5430:     my ($file_name,$changes,$domain,$user)=@_;
                   5431:     my ($outcome,$deloutcome);
                   5432:     my %store_permissions;
                   5433:     my %new_values;
                   5434:     my %new_control;
                   5435:     my %translation;
                   5436:     my @deletions = ();
                   5437:     my $now = time;
                   5438:     if (exists($$changes{'activate'})) {
                   5439:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5440:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5441:             my $numnew = scalar(@newitems);
                   5442:             for (my $i=0; $i<$numnew; $i++) {
                   5443:                 my $newkey = $newitems[$i];
                   5444:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5445:                 if ($newkey =~ /^\d+:/) { 
                   5446:                     $newkey =~ s/^(\d+)/$newid/;
                   5447:                     $translation{$1} = $newid;
                   5448:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5449:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5450:                     $translation{$1} = $newid;
                   5451:                 }
1.749     raeburn  5452:                 $new_values{$file_name."\0".$newkey} = 
                   5453:                                           $$changes{'activate'}{$newitems[$i]};
                   5454:                 $new_control{$newkey} = $now;
                   5455:             }
                   5456:         }
                   5457:     }
                   5458:     my %todelete;
                   5459:     my %changed_items;
                   5460:     foreach my $action ('delete','update') {
                   5461:         if (exists($$changes{$action})) {
                   5462:             if (ref($$changes{$action}) eq 'HASH') {
                   5463:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5464:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5465:                     if ($action eq 'delete') { 
                   5466:                         $todelete{$itemnum} = 1;
                   5467:                     } else {
                   5468:                         $changed_items{$itemnum} = $key;
                   5469:                     }
                   5470:                 }
1.745     raeburn  5471:             }
                   5472:         }
1.749     raeburn  5473:     }
                   5474:     # get lock on access controls for file.
                   5475:     my $lockhash = {
                   5476:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5477:                                                        ':'.$env{'user.domain'},
                   5478:                    }; 
                   5479:     my $tries = 0;
                   5480:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5481:    
                   5482:     while (($gotlock ne 'ok') && $tries <3) {
                   5483:         $tries ++;
                   5484:         sleep 1;
                   5485:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5486:     }
                   5487:     if ($gotlock eq 'ok') {
                   5488:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5489:         my ($tmp)=keys(%curr_permissions);
                   5490:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5491:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5492:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5493:             if (ref($curr_controls) eq 'HASH') {
                   5494:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5495:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5496:                     if (defined($todelete{$itemnum})) {
                   5497:                         push(@deletions,$file_name."\0".$control_item);
                   5498:                     } else {
                   5499:                         if (defined($changed_items{$itemnum})) {
                   5500:                             $new_control{$changed_items{$itemnum}} = $now;
                   5501:                             push(@deletions,$file_name."\0".$control_item);
                   5502:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5503:                         } else {
                   5504:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5505:                         }
                   5506:                     }
1.745     raeburn  5507:                 }
                   5508:             }
                   5509:         }
1.749     raeburn  5510:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5511:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5512:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5513:         #  remove lock
                   5514:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5515:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5516:         my ($file,$group);
                   5517:         if (&is_course($domain,$user)) {
                   5518:             ($group,$file) = split(/\//,$file_name,2);
                   5519:         } else {
                   5520:             $file = $file_name;
                   5521:         }
                   5522:         my $sqlresult =
                   5523:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5524:                                     $group);
1.749     raeburn  5525:     } else {
                   5526:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5527:     }
1.749     raeburn  5528:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5529: }
                   5530: 
1.827     raeburn  5531: sub make_public_indefinitely {
                   5532:     my ($requrl) = @_;
                   5533:     my $now = time;
                   5534:     my $action = 'activate';
                   5535:     my $aclnum = 0;
                   5536:     if (&is_portfolio_url($requrl)) {
                   5537:         my (undef,$udom,$unum,$file_name,$group) =
                   5538:             &parse_portfolio_url($requrl);
                   5539:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5540:         my %access_controls = &get_access_controls($current_perms,
                   5541:                                                    $group,$file_name);
                   5542:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5543:             my ($num,$scope,$end,$start) = 
                   5544:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5545:             if ($scope eq 'public') {
                   5546:                 if ($start <= $now && $end == 0) {
                   5547:                     $action = 'none';
                   5548:                 } else {
                   5549:                     $action = 'update';
                   5550:                     $aclnum = $num;
                   5551:                 }
                   5552:                 last;
                   5553:             }
                   5554:         }
                   5555:         if ($action eq 'none') {
                   5556:              return 'ok';
                   5557:         } else {
                   5558:             my %changes;
                   5559:             my $newend = 0;
                   5560:             my $newstart = $now;
                   5561:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5562:             $changes{$action}{$newkey} = {
                   5563:                 type => 'public',
                   5564:                 time => {
                   5565:                     start => $newstart,
                   5566:                     end   => $newend,
                   5567:                 },
                   5568:             };
                   5569:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5570:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5571:             return $outcome;
                   5572:         }
                   5573:     } else {
                   5574:         return 'invalid';
                   5575:     }
                   5576: }
                   5577: 
1.745     raeburn  5578: #------------------------------------------------------Get Marked as Read Only
                   5579: 
                   5580: sub get_marked_as_readonly {
                   5581:     my ($domain,$user,$what,$group) = @_;
                   5582:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5583:     my @readonly_files;
1.629     banghart 5584:     my $cmp1=$what;
                   5585:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5586:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5587:         if (defined($group)) {
                   5588:             if ($file_name !~ m-^\Q$group\E/-) {
                   5589:                 next;
                   5590:             }
                   5591:         }
1.561     banghart 5592:         if (ref($value) eq "ARRAY"){
                   5593:             foreach my $stored_what (@{$value}) {
1.629     banghart 5594:                 my $cmp2=$stored_what;
1.759     albertel 5595:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5596:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5597:                 }
1.629     banghart 5598:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5599:                     push(@readonly_files, $file_name);
1.745     raeburn  5600:                     last;
1.563     banghart 5601:                 } elsif (!defined($what)) {
                   5602:                     push(@readonly_files, $file_name);
1.745     raeburn  5603:                     last;
1.561     banghart 5604:                 }
                   5605:             }
1.745     raeburn  5606:         }
1.561     banghart 5607:     }
                   5608:     return @readonly_files;
                   5609: }
1.577     banghart 5610: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5611: 
1.577     banghart 5612: sub get_marked_as_readonly_hash {
1.745     raeburn  5613:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5614:     my %readonly_files;
1.745     raeburn  5615:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5616:         if (defined($group)) {
                   5617:             if ($file_name !~ m-^\Q$group\E/-) {
                   5618:                 next;
                   5619:             }
                   5620:         }
1.577     banghart 5621:         if (ref($value) eq "ARRAY"){
                   5622:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5623:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5624:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5625:                         if ($lock_descriptor eq 'graded') {
                   5626:                             $readonly_files{$file_name} = 'graded';
                   5627:                         } elsif ($lock_descriptor eq 'handback') {
                   5628:                             $readonly_files{$file_name} = 'handback';
                   5629:                         } else {
                   5630:                             if (!exists($readonly_files{$file_name})) {
                   5631:                                 $readonly_files{$file_name} = 'locked';
                   5632:                             }
                   5633:                         }
1.745     raeburn  5634:                     }
1.750     banghart 5635:                 } 
1.577     banghart 5636:             }
                   5637:         } 
                   5638:     }
                   5639:     return %readonly_files;
                   5640: }
1.559     banghart 5641: # ------------------------------------------------------------ Unmark as Read Only
                   5642: 
                   5643: sub unmark_as_readonly {
1.629     banghart 5644:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5645:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5646:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5647:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5648:     my $symb_crs = $what;
                   5649:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5650:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5651:     my ($tmp)=keys(%current_permissions);
                   5652:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5653:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5654:     foreach my $file (@readonly_files) {
1.759     albertel 5655: 	my $clean_file = &declutter_portfile($file);
                   5656: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5657: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5658:         my @new_locks;
                   5659:         my @del_keys;
                   5660:         if (ref($current_locks) eq "ARRAY"){
                   5661:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5662:                 my $compare=$locker;
1.749     raeburn  5663:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5664:                     $compare=join('',@{$locker});
1.746     raeburn  5665:                     if ($compare ne $symb_crs) {
                   5666:                         push(@new_locks, $locker);
                   5667:                     }
1.563     banghart 5668:                 }
                   5669:             }
1.650     albertel 5670:             if (scalar(@new_locks) > 0) {
1.563     banghart 5671:                 $current_permissions{$file} = \@new_locks;
                   5672:             } else {
                   5673:                 push(@del_keys, $file);
1.613     albertel 5674:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5675:                 delete($current_permissions{$file});
1.563     banghart 5676:             }
                   5677:         }
1.561     banghart 5678:     }
1.613     albertel 5679:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5680:     return;
                   5681: }
1.512     banghart 5682: 
1.17      www      5683: # ------------------------------------------------------------ Directory lister
                   5684: 
                   5685: sub dirlist {
1.253     stredwic 5686:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5687: 
1.18      www      5688:     $uri=~s/^\///;
                   5689:     $uri=~s/\/$//;
1.253     stredwic 5690:     my ($udom, $uname);
                   5691:     (undef,$udom,$uname)=split(/\//,$uri);
                   5692:     if(defined($userdomain)) {
                   5693:         $udom = $userdomain;
                   5694:     }
                   5695:     if(defined($username)) {
                   5696:         $uname = $username;
                   5697:     }
                   5698: 
                   5699:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5700:     if(defined($alternateDirectoryRoot)) {
                   5701:         $dirRoot = $alternateDirectoryRoot;
                   5702:         $dirRoot =~ s/\/$//;
1.751     banghart 5703:     }
1.253     stredwic 5704: 
                   5705:     if($udom) {
                   5706:         if($uname) {
1.800     albertel 5707:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5708: 				 &homeserver($uname,$udom));
1.605     matthew  5709:             my @listing_results;
                   5710:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5711:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5712: 				  &homeserver($uname,$udom));
1.605     matthew  5713:                 @listing_results = split(/:/,$listing);
                   5714:             } else {
                   5715:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5716:             }
                   5717:             return @listing_results;
1.253     stredwic 5718:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5719:             my %allusers;
1.841     albertel 5720: 	    my %servers = &get_servers($udom,'library');
                   5721: 	    foreach my $tryserver (keys(%servers)) {
                   5722: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5723: 				     $udom, $tryserver);
                   5724: 		my @listing_results;
                   5725: 		if ($listing eq 'unknown_cmd') {
                   5726: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5727: 				      $udom, $tryserver);
                   5728: 		    @listing_results = split(/:/,$listing);
                   5729: 		} else {
                   5730: 		    @listing_results =
                   5731: 			map { &unescape($_); } split(/:/,$listing);
                   5732: 		}
                   5733: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5734: 		    $listing_results[0] ne 'empty'       &&
                   5735: 		    $listing_results[0] ne 'con_lost') {
                   5736: 		    foreach my $line (@listing_results) {
                   5737: 			my ($entry) = split(/&/,$line,2);
                   5738: 			$allusers{$entry} = 1;
                   5739: 		    }
                   5740: 		}
1.253     stredwic 5741:             }
                   5742:             my $alluserstr='';
1.800     albertel 5743:             foreach my $user (sort(keys(%allusers))) {
                   5744:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5745:             }
                   5746:             $alluserstr=~s/:$//;
                   5747:             return split(/:/,$alluserstr);
                   5748:         } else {
1.800     albertel 5749:             return ('missing user name');
1.253     stredwic 5750:         }
                   5751:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5752:         my @all_domains = sort(&all_domains());
                   5753:          foreach my $domain (@all_domains) {
                   5754:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5755:          }
                   5756:          return @all_domains;
                   5757:      } else {
1.800     albertel 5758:         return ('missing domain');
1.275     stredwic 5759:     }
                   5760: }
                   5761: 
                   5762: # --------------------------------------------- GetFileTimestamp
                   5763: # This function utilizes dirlist and returns the date stamp for
                   5764: # when it was last modified.  It will also return an error of -1
                   5765: # if an error occurs
                   5766: 
1.410     matthew  5767: ##
                   5768: ## FIXME: This subroutine assumes its caller knows something about the
                   5769: ## directory structure of the home server for the student ($root).
                   5770: ## Not a good assumption to make.  Since this is for looking up files
                   5771: ## in user directories, the full path should be constructed by lond, not
                   5772: ## whatever machine we request data from.
                   5773: ##
1.275     stredwic 5774: sub GetFileTimestamp {
                   5775:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5776:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5777:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5778:     my $subdir=$studentName.'__';
                   5779:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5780:     my $proname="$studentDomain/$subdir/$studentName";
                   5781:     $proname .= '/'.$filename;
1.375     matthew  5782:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5783:                                               $studentName, $root);
1.275     stredwic 5784:     my @stats = split('&', $fileStat);
                   5785:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5786:         # @stats contains first the filename, then the stat output
                   5787:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5788:     } else {
                   5789:         return -1;
1.253     stredwic 5790:     }
1.26      www      5791: }
                   5792: 
1.712     albertel 5793: sub stat_file {
                   5794:     my ($uri) = @_;
1.787     albertel 5795:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5796: 
1.712     albertel 5797:     my ($udom,$uname,$file,$dir);
                   5798:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5799: 	($udom,$uname,$file) =
1.811     albertel 5800: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5801: 	$file = 'userfiles/'.$file;
1.740     www      5802: 	$dir = &propath($udom,$uname);
1.712     albertel 5803:     }
                   5804:     if ($uri =~ m-^/res/-) {
                   5805: 	($udom,$uname) = 
1.807     albertel 5806: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5807: 	$file = $uri;
                   5808:     }
                   5809: 
                   5810:     if (!$udom || !$uname || !$file) {
                   5811: 	# unable to handle the uri
                   5812: 	return ();
                   5813:     }
                   5814: 
                   5815:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5816:     my @stats = split('&', $result);
1.721     banghart 5817:     
1.712     albertel 5818:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5819: 	shift(@stats); #filename is first
                   5820: 	return @stats;
                   5821:     }
                   5822:     return ();
                   5823: }
                   5824: 
1.26      www      5825: # -------------------------------------------------------- Value of a Condition
                   5826: 
1.713     albertel 5827: # gets the value of a specific preevaluated condition
                   5828: #    stored in the string  $env{user.state.<cid>}
                   5829: # or looks up a condition reference in the bighash and if if hasn't
                   5830: # already been evaluated recurses into docondval to get the value of
                   5831: # the condition, then memoizing it to 
                   5832: #   $env{user.state.<cid>.<condition>}
1.40      www      5833: sub directcondval {
                   5834:     my $number=shift;
1.620     albertel 5835:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5836: 	&Apache::lonuserstate::evalstate();
                   5837:     }
1.713     albertel 5838:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5839: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5840:     } elsif ($number =~ /^_/) {
                   5841: 	my $sub_condition;
                   5842: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5843: 		&GDBM_READER(),0640)) {
                   5844: 	    $sub_condition=$bighash{'conditions'.$number};
                   5845: 	    untie(%bighash);
                   5846: 	}
                   5847: 	my $value = &docondval($sub_condition);
                   5848: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5849: 	return $value;
                   5850:     }
1.620     albertel 5851:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5852:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5853:     } else {
                   5854:        return 2;
                   5855:     }
                   5856: }
                   5857: 
1.713     albertel 5858: # get the collection of conditions for this resource
1.26      www      5859: sub condval {
                   5860:     my $condidx=shift;
1.54      www      5861:     my $allpathcond='';
1.713     albertel 5862:     foreach my $cond (split(/\|/,$condidx)) {
                   5863: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5864: 	    $allpathcond.=
                   5865: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5866: 	}
1.191     harris41 5867:     }
1.54      www      5868:     $allpathcond=~s/\|$//;
1.713     albertel 5869:     return &docondval($allpathcond);
                   5870: }
                   5871: 
                   5872: #evaluates an expression of conditions
                   5873: sub docondval {
                   5874:     my ($allpathcond) = @_;
                   5875:     my $result=0;
                   5876:     if ($env{'request.course.id'}
                   5877: 	&& defined($allpathcond)) {
                   5878: 	my $operand='|';
                   5879: 	my @stack;
                   5880: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5881: 	    if ($chunk eq '(') {
                   5882: 		push @stack,($operand,$result);
                   5883: 	    } elsif ($chunk eq ')') {
                   5884: 		my $before=pop @stack;
                   5885: 		if (pop @stack eq '&') {
                   5886: 		    $result=$result>$before?$before:$result;
                   5887: 		} else {
                   5888: 		    $result=$result>$before?$result:$before;
                   5889: 		}
                   5890: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5891: 		$operand=$chunk;
                   5892: 	    } else {
                   5893: 		my $new=directcondval($chunk);
                   5894: 		if ($operand eq '&') {
                   5895: 		    $result=$result>$new?$new:$result;
                   5896: 		} else {
                   5897: 		    $result=$result>$new?$result:$new;
                   5898: 		}
                   5899: 	    }
                   5900: 	}
1.26      www      5901:     }
                   5902:     return $result;
1.421     albertel 5903: }
                   5904: 
                   5905: # ---------------------------------------------------- Devalidate courseresdata
                   5906: 
                   5907: sub devalidatecourseresdata {
                   5908:     my ($coursenum,$coursedomain)=@_;
                   5909:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5910:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5911: }
                   5912: 
1.763     www      5913: 
1.200     www      5914: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     5915: #
                   5916: #  Parameters:
                   5917: #      $coursenum    - Number of the course.
                   5918: #      $coursedomain - Domain at which the course was created.
                   5919: #  Returns:
                   5920: #     A hash of the course parameters along (I think) with timestamps
                   5921: #     and version info.
1.877     foxr     5922: 
1.624     albertel 5923: sub get_courseresdata {
                   5924:     my ($coursenum,$coursedomain)=@_;
1.200     www      5925:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5926:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5927:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5928:     my %dumpreply;
1.417     albertel 5929:     unless (defined($cached)) {
1.624     albertel 5930: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5931: 	$result=\%dumpreply;
1.251     albertel 5932: 	my ($tmp) = keys(%dumpreply);
                   5933: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5934: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5935: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5936: 	    return $tmp;
1.416     albertel 5937: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5938: 	    $result=undef;
1.599     albertel 5939: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5940: 	}
                   5941:     }
1.624     albertel 5942:     return $result;
                   5943: }
                   5944: 
1.633     albertel 5945: sub devalidateuserresdata {
                   5946:     my ($uname,$udom)=@_;
                   5947:     my $hashid="$udom:$uname";
                   5948:     &devalidate_cache_new('userres',$hashid);
                   5949: }
                   5950: 
1.624     albertel 5951: sub get_userresdata {
                   5952:     my ($uname,$udom)=@_;
                   5953:     #most student don\'t have any data set, check if there is some data
                   5954:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5955: 
                   5956:     my $hashid="$udom:$uname";
                   5957:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5958:     if (!defined($cached)) {
                   5959: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5960: 	$result=\%resourcedata;
                   5961: 	&do_cache_new('userres',$hashid,$result,600);
                   5962:     }
                   5963:     my ($tmp)=keys(%$result);
                   5964:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5965: 	return $result;
                   5966:     }
                   5967:     #error 2 occurs when the .db doesn't exist
                   5968:     if ($tmp!~/error: 2 /) {
1.672     albertel 5969: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5970: 		 " Trying to get resource data for ".
                   5971: 		 $uname." at ".$udom.": ".
                   5972: 		 $tmp."</font>");
                   5973:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5974: 	#&EXT_cache_set($udom,$uname);
                   5975: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5976: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5977:     }
                   5978:     return $tmp;
                   5979: }
1.879     foxr     5980: #----------------------------------------------- resdata - return resource data
                   5981: #  Purpose:
                   5982: #    Return resource data for either users or for a course.
                   5983: #  Parameters:
                   5984: #     $name      - Course/user name.
                   5985: #     $domain    - Name of the domain the user/course is registered on.
                   5986: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   5987: #     @which     - Array of names of resources desired.
                   5988: #  Returns:
                   5989: #     The value of the first reasource in @which that is found in the
                   5990: #     resource hash.
                   5991: #  Exceptional Conditions:
                   5992: #     If the $type passed in is not valid (not the string 'course' or 
                   5993: #     'user', an undefined  reference is returned.
                   5994: #     If none of the resources are found, an undef is returned
1.624     albertel 5995: sub resdata {
                   5996:     my ($name,$domain,$type,@which)=@_;
                   5997:     my $result;
                   5998:     if ($type eq 'course') {
                   5999: 	$result=&get_courseresdata($name,$domain);
                   6000:     } elsif ($type eq 'user') {
                   6001: 	$result=&get_userresdata($name,$domain);
                   6002:     }
                   6003:     if (!ref($result)) { return $result; }    
1.251     albertel 6004:     foreach my $item (@which) {
1.417     albertel 6005: 	if (defined($result->{$item})) {
                   6006: 	    return $result->{$item};
1.251     albertel 6007: 	}
1.250     albertel 6008:     }
1.291     albertel 6009:     return undef;
1.200     www      6010: }
                   6011: 
1.379     matthew  6012: #
                   6013: # EXT resource caching routines
                   6014: #
                   6015: 
                   6016: sub clear_EXT_cache_status {
1.383     albertel 6017:     &delenv('cache.EXT.');
1.379     matthew  6018: }
                   6019: 
                   6020: sub EXT_cache_status {
                   6021:     my ($target_domain,$target_user) = @_;
1.383     albertel 6022:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6023:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6024:         # We know already the user has no data
                   6025:         return 1;
                   6026:     } else {
                   6027:         return 0;
                   6028:     }
                   6029: }
                   6030: 
                   6031: sub EXT_cache_set {
                   6032:     my ($target_domain,$target_user) = @_;
1.383     albertel 6033:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6034:     #&appenv($cachename => time);
1.379     matthew  6035: }
                   6036: 
1.28      www      6037: # --------------------------------------------------------- Value of a Variable
1.58      www      6038: sub EXT {
1.715     albertel 6039: 
1.395     albertel 6040:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6041:     unless ($varname) { return ''; }
1.218     albertel 6042:     #get real user name/domain, courseid and symb
                   6043:     my $courseid;
1.359     albertel 6044:     my $publicuser;
1.427     www      6045:     if ($symbparm) {
                   6046: 	$symbparm=&get_symb_from_alias($symbparm);
                   6047:     }
1.218     albertel 6048:     if (!($uname && $udom)) {
1.790     albertel 6049:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6050:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6051:     } else {
1.620     albertel 6052: 	$courseid=$env{'request.course.id'};
1.218     albertel 6053:     }
1.48      www      6054:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6055:     my $rest;
1.320     albertel 6056:     if (defined($therest[0])) {
1.48      www      6057:        $rest=join('.',@therest);
                   6058:     } else {
                   6059:        $rest='';
                   6060:     }
1.320     albertel 6061: 
1.57      www      6062:     my $qualifierrest=$qualifier;
                   6063:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6064:     my $spacequalifierrest=$space;
                   6065:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6066:     if ($realm eq 'user') {
1.48      www      6067: # --------------------------------------------------------------- user.resource
                   6068: 	if ($space eq 'resource') {
1.651     albertel 6069: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6070: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6071: 		 &&
1.744     albertel 6072: 		 ($symbparm eq &symbread()) ) {	
                   6073: 		# if we are in the middle of processing the resource the
                   6074: 		# get the value we are planning on committing
                   6075:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6076:                     return $Apache::lonhomework::results{$qualifierrest};
                   6077:                 } else {
                   6078:                     return $Apache::lonhomework::history{$qualifierrest};
                   6079:                 }
1.335     albertel 6080: 	    } else {
1.359     albertel 6081: 		my %restored;
1.620     albertel 6082: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6083: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6084: 		} else {
                   6085: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6086: 		}
1.335     albertel 6087: 		return $restored{$qualifierrest};
                   6088: 	    }
1.48      www      6089: # ----------------------------------------------------------------- user.access
                   6090:         } elsif ($space eq 'access') {
1.218     albertel 6091: 	    # FIXME - not supporting calls for a specific user
1.48      www      6092:             return &allowed($qualifier,$rest);
                   6093: # ------------------------------------------ user.preferences, user.environment
                   6094:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6095: 	    if (($uname eq $env{'user.name'}) &&
                   6096: 		($udom eq $env{'user.domain'})) {
                   6097: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6098: 	    } else {
1.359     albertel 6099: 		my %returnhash;
                   6100: 		if (!$publicuser) {
                   6101: 		    %returnhash=&userenvironment($udom,$uname,
                   6102: 						 $qualifierrest);
                   6103: 		}
1.218     albertel 6104: 		return $returnhash{$qualifierrest};
                   6105: 	    }
1.48      www      6106: # ----------------------------------------------------------------- user.course
                   6107:         } elsif ($space eq 'course') {
1.218     albertel 6108: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6109:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6110: # ------------------------------------------------------------------- user.role
                   6111:         } elsif ($space eq 'role') {
1.218     albertel 6112: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6113:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6114:             if ($qualifier eq 'value') {
                   6115: 		return $role;
                   6116:             } elsif ($qualifier eq 'extent') {
                   6117:                 return $where;
                   6118:             }
                   6119: # ----------------------------------------------------------------- user.domain
                   6120:         } elsif ($space eq 'domain') {
1.218     albertel 6121:             return $udom;
1.48      www      6122: # ------------------------------------------------------------------- user.name
                   6123:         } elsif ($space eq 'name') {
1.218     albertel 6124:             return $uname;
1.48      www      6125: # ---------------------------------------------------- Any other user namespace
1.29      www      6126:         } else {
1.359     albertel 6127: 	    my %reply;
                   6128: 	    if (!$publicuser) {
                   6129: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6130: 	    }
                   6131: 	    return $reply{$qualifierrest};
1.48      www      6132:         }
1.236     www      6133:     } elsif ($realm eq 'query') {
                   6134: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6135:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6136: 						[$spacequalifierrest]);
1.620     albertel 6137: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6138:    } elsif ($realm eq 'request') {
1.48      www      6139: # ------------------------------------------------------------- request.browser
                   6140:         if ($space eq 'browser') {
1.430     www      6141: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6142: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6143: 		    return 1;
                   6144: 		} else {
                   6145: 		    return 0;
                   6146: 		}
                   6147: 	    } else {
1.620     albertel 6148: 		return $env{'browser.'.$qualifier};
1.430     www      6149: 	    }
1.57      www      6150: # ------------------------------------------------------------ request.filename
                   6151:         } else {
1.620     albertel 6152:             return $env{'request.'.$spacequalifierrest};
1.29      www      6153:         }
1.28      www      6154:     } elsif ($realm eq 'course') {
1.48      www      6155: # ---------------------------------------------------------- course.description
1.620     albertel 6156:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6157:     } elsif ($realm eq 'resource') {
1.165     www      6158: 
1.620     albertel 6159: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6160: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6161: 	}
1.693     albertel 6162: 
                   6163: 	if ($space eq 'title') {
                   6164: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6165: 	    return &gettitle($symbparm);
                   6166: 	}
                   6167: 	
                   6168: 	if ($space eq 'map') {
                   6169: 	    my ($map) = &decode_symb($symbparm);
                   6170: 	    return &symbread($map);
                   6171: 	}
                   6172: 
                   6173: 	my ($section, $group, @groups);
1.593     albertel 6174: 	my ($courselevelm,$courselevel);
1.539     albertel 6175: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6176: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6177: 
1.218     albertel 6178: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6179: 
1.60      www      6180: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6181: 	    my $symbp=$symbparm;
1.735     albertel 6182: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6183: 
                   6184: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6185: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6186: 
1.620     albertel 6187: 	    if (($env{'user.name'} eq $uname) &&
                   6188: 		($env{'user.domain'} eq $udom)) {
                   6189: 		$section=$env{'request.course.sec'};
1.733     raeburn  6190:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6191:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6192: 	    } else {
1.539     albertel 6193: 		if (! defined($usection)) {
1.551     albertel 6194: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6195: 		} else {
                   6196: 		    $section = $usection;
                   6197: 		}
1.733     raeburn  6198:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6199: 	    }
                   6200: 
                   6201: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6202: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6203: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6204: 
1.593     albertel 6205: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6206: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6207: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6208: 
1.60      www      6209: # ----------------------------------------------------------- first, check user
1.624     albertel 6210: 
                   6211: 	    my $userreply=&resdata($uname,$udom,'user',
                   6212: 				       ($courselevelr,$courselevelm,
                   6213: 					$courselevel));
                   6214: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6215: 
1.594     albertel 6216: # ------------------------------------------------ second, check some of course
1.684     raeburn  6217:             my $coursereply;
1.691     raeburn  6218:             if (@groups > 0) {
                   6219:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6220:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6221:                 if (defined($coursereply)) { return $coursereply; }
                   6222:             }
1.96      www      6223: 
1.684     raeburn  6224: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6225: 				     $env{'course.'.$courseid.'.domain'},
                   6226: 				     'course',
                   6227: 				     ($seclevelr,$seclevelm,$seclevel,
                   6228: 				      $courselevelr));
1.287     albertel 6229: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6230: 
1.60      www      6231: # ------------------------------------------------------ third, check map parms
1.218     albertel 6232: 	    my %parmhash=();
                   6233: 	    my $thisparm='';
                   6234: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6235: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6236: 		    &GDBM_READER(),0640)) {
1.218     albertel 6237: 		$thisparm=$parmhash{$symbparm};
                   6238: 		untie(%parmhash);
                   6239: 	    }
                   6240: 	    if ($thisparm) { return $thisparm; }
                   6241: 	}
1.594     albertel 6242: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6243: 
1.218     albertel 6244: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6245: 	my $filename;
                   6246: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6247: 	if ($symbparm) {
1.409     www      6248: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6249: 	} else {
1.620     albertel 6250: 	    $filename=$env{'request.filename'};
1.282     albertel 6251: 	}
                   6252: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6253: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6254: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6255: 	if (defined($metadata)) { return $metadata; }
1.142     www      6256: 
1.594     albertel 6257: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6258: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6259: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6260: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6261: 				     $env{'course.'.$courseid.'.domain'},
                   6262: 				     'course',
                   6263: 				     ($courselevelm,$courselevel));
1.593     albertel 6264: 	    if (defined($coursereply)) { return $coursereply; }
                   6265: 	}
1.145     www      6266: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6267: 	unless ($space eq '0') {
1.336     albertel 6268: 	    my @parts=split(/_/,$space);
                   6269: 	    my $id=pop(@parts);
                   6270: 	    my $part=join('_',@parts);
                   6271: 	    if ($part eq '') { $part='0'; }
                   6272: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6273: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6274: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6275: 	}
1.395     albertel 6276: 	if ($recurse) { return undef; }
                   6277: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6278: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6279: 
1.48      www      6280: # ---------------------------------------------------- Any other user namespace
                   6281:     } elsif ($realm eq 'environment') {
                   6282: # ----------------------------------------------------------------- environment
1.620     albertel 6283: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6284: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6285: 	} else {
1.770     albertel 6286: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6287: 		return '';
                   6288: 	    }
1.219     albertel 6289: 	    my %returnhash=&userenvironment($udom,$uname,
                   6290: 					    $spacequalifierrest);
                   6291: 	    return $returnhash{$spacequalifierrest};
                   6292: 	}
1.28      www      6293:     } elsif ($realm eq 'system') {
1.48      www      6294: # ----------------------------------------------------------------- system.time
                   6295: 	if ($space eq 'time') {
                   6296: 	    return time;
                   6297:         }
1.696     albertel 6298:     } elsif ($realm eq 'server') {
                   6299: # ----------------------------------------------------------------- system.time
                   6300: 	if ($space eq 'name') {
                   6301: 	    return $ENV{'SERVER_NAME'};
                   6302:         }
1.28      www      6303:     }
1.48      www      6304:     return '';
1.61      www      6305: }
                   6306: 
1.691     raeburn  6307: sub check_group_parms {
                   6308:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6309:     my @groupitems = ();
                   6310:     my $resultitem;
                   6311:     my @levels = ($symbparm,$mapparm,$what);
                   6312:     foreach my $group (@{$groups}) {
                   6313:         foreach my $level (@levels) {
                   6314:              my $item = $courseid.'.['.$group.'].'.$level;
                   6315:              push(@groupitems,$item);
                   6316:         }
                   6317:     }
                   6318:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6319:                             $env{'course.'.$courseid.'.domain'},
                   6320:                                      'course',@groupitems);
                   6321:     return $coursereply;
                   6322: }
                   6323: 
                   6324: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6325:     my ($courseid,@groups) = @_;
                   6326:     @groups = sort(@groups);
1.691     raeburn  6327:     return @groups;
                   6328: }
                   6329: 
1.395     albertel 6330: sub packages_tab_default {
                   6331:     my ($uri,$varname)=@_;
                   6332:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6333: 
                   6334:     my (@extension,@specifics,$do_default);
                   6335:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6336: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6337: 	if ($pack_type eq 'default') {
                   6338: 	    $do_default=1;
                   6339: 	} elsif ($pack_type eq 'extension') {
                   6340: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.848     albertel 6341: 	} elsif ($pack_part eq $part) {
                   6342: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6343: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6344: 	}
                   6345:     }
                   6346:     # first look for a package that matches the requested part id
                   6347:     foreach my $package (@specifics) {
                   6348: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6349: 	next if ($pack_part ne $part);
                   6350: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6351: 	    return $packagetab{"$pack_type&$name&default"};
                   6352: 	}
                   6353:     }
                   6354:     # look for any possible matching non extension_ package
                   6355:     foreach my $package (@specifics) {
                   6356: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6357: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6358: 	    return $packagetab{"$pack_type&$name&default"};
                   6359: 	}
1.585     albertel 6360: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6361: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6362: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6363: 	}
                   6364:     }
1.738     albertel 6365:     # look for any posible extension_ match
                   6366:     foreach my $package (@extension) {
                   6367: 	my ($package,$pack_type)=@{$package};
                   6368: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6369: 	    return $packagetab{"$pack_type&$name&default"};
                   6370: 	}
                   6371: 	if (defined($packagetab{$package."&$name&default"})) {
                   6372: 	    return $packagetab{$package."&$name&default"};
                   6373: 	}
                   6374:     }
                   6375:     # look for a global default setting
                   6376:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6377: 	return $packagetab{"default&$name&default"};
                   6378:     }
1.395     albertel 6379:     return undef;
                   6380: }
                   6381: 
1.334     albertel 6382: sub add_prefix_and_part {
                   6383:     my ($prefix,$part)=@_;
                   6384:     my $keyroot;
                   6385:     if (defined($prefix) && $prefix !~ /^__/) {
                   6386: 	# prefix that has a part already
                   6387: 	$keyroot=$prefix;
                   6388:     } elsif (defined($prefix)) {
                   6389: 	# prefix that is missing a part
                   6390: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6391:     } else {
                   6392: 	# no prefix at all
                   6393: 	if (defined($part)) { $keyroot='_'.$part; }
                   6394:     }
                   6395:     return $keyroot;
                   6396: }
                   6397: 
1.71      www      6398: # ---------------------------------------------------------------- Get metadata
                   6399: 
1.599     albertel 6400: my %metaentry;
1.71      www      6401: sub metadata {
1.176     www      6402:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6403:     $uri=&declutter($uri);
1.288     albertel 6404:     # if it is a non metadata possible uri return quickly
1.529     albertel 6405:     if (($uri eq '') || 
                   6406: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6407: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6408:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6409: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6410: 	return undef;
1.288     albertel 6411:     }
1.73      www      6412:     my $filename=$uri;
                   6413:     $uri=~s/\.meta$//;
1.172     www      6414: #
                   6415: # Is the metadata already cached?
1.177     www      6416: # Look at timestamp of caching
1.172     www      6417: # Everything is cached by the main uri, libraries are never directly cached
                   6418: #
1.428     albertel 6419:     if (!defined($liburi)) {
1.599     albertel 6420: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6421: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6422:     }
                   6423:     {
1.172     www      6424: #
                   6425: # Is this a recursive call for a library?
                   6426: #
1.599     albertel 6427: #	if (! exists($metacache{$uri})) {
                   6428: #	    $metacache{$uri}={};
                   6429: #	}
1.171     www      6430:         if ($liburi) {
                   6431: 	    $liburi=&declutter($liburi);
                   6432:             $filename=$liburi;
1.401     bowersj2 6433:         } else {
1.599     albertel 6434: 	    &devalidate_cache_new('meta',$uri);
                   6435: 	    undef(%metaentry);
1.401     bowersj2 6436: 	}
1.140     www      6437:         my %metathesekeys=();
1.73      www      6438:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6439: 	my $metastring;
1.768     albertel 6440: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6441: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6442: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6443: 	    $metastring=&getfile($file);
1.489     albertel 6444: 	}
1.208     albertel 6445:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6446:         my $token;
1.140     www      6447:         undef %metathesekeys;
1.71      www      6448:         while ($token=$parser->get_token) {
1.339     albertel 6449: 	    if ($token->[0] eq 'S') {
                   6450: 		if (defined($token->[2]->{'package'})) {
1.172     www      6451: #
                   6452: # This is a package - get package info
                   6453: #
1.339     albertel 6454: 		    my $package=$token->[2]->{'package'};
                   6455: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6456: 		    if (defined($token->[2]->{'id'})) { 
                   6457: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6458: 		    }
1.599     albertel 6459: 		    if ($metaentry{':packages'}) {
                   6460: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6461: 		    } else {
1.599     albertel 6462: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6463: 		    }
1.736     albertel 6464: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6465: 			my $part=$keyroot;
                   6466: 			$part=~s/^\_//;
1.736     albertel 6467: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6468: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6469: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6470: 			    # ignore package.tab specified default values
                   6471:                             # here &package_tab_default() will fetch those
                   6472: 			    if ($subp eq 'default') { next; }
1.736     albertel 6473: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6474: 			    my $unikey;
                   6475: 			    if ($pack =~ /_0$/) {
                   6476: 				$unikey='parameter_0_'.$name;
                   6477: 				$part=0;
                   6478: 			    } else {
                   6479: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6480: 			    }
1.339     albertel 6481: 			    if ($subp eq 'display') {
                   6482: 				$value.=' [Part: '.$part.']';
                   6483: 			    }
1.599     albertel 6484: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6485: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6486: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6487: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6488: 			    }
1.599     albertel 6489: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6490: 				$metaentry{':'.$unikey}=
                   6491: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6492: 			    }
1.339     albertel 6493: 			}
                   6494: 		    }
                   6495: 		} else {
1.172     www      6496: #
                   6497: # This is not a package - some other kind of start tag
1.339     albertel 6498: #
                   6499: 		    my $entry=$token->[1];
                   6500: 		    my $unikey;
                   6501: 		    if ($entry eq 'import') {
                   6502: 			$unikey='';
                   6503: 		    } else {
                   6504: 			$unikey=$entry;
                   6505: 		    }
                   6506: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6507: 
                   6508: 		    if (defined($token->[2]->{'id'})) { 
                   6509: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6510: 		    }
1.175     www      6511: 
1.339     albertel 6512: 		    if ($entry eq 'import') {
1.175     www      6513: #
                   6514: # Importing a library here
1.339     albertel 6515: #
                   6516: 			if ($depthcount<20) {
                   6517: 			    my $location=$parser->get_text('/import');
                   6518: 			    my $dir=$filename;
                   6519: 			    $dir=~s|[^/]*$||;
                   6520: 			    $location=&filelocation($dir,$location);
1.736     albertel 6521: 			    my $metadata = 
                   6522: 				&metadata($uri,'keys', $location,$unikey,
                   6523: 					  $depthcount+1);
                   6524: 			    foreach my $meta (split(',',$metadata)) {
                   6525: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6526: 				$metathesekeys{$meta}=1;
1.339     albertel 6527: 			    }
                   6528: 			}
                   6529: 		    } else { 
                   6530: 			
                   6531: 			if (defined($token->[2]->{'name'})) { 
                   6532: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6533: 			}
                   6534: 			$metathesekeys{$unikey}=1;
1.736     albertel 6535: 			foreach my $param (@{$token->[3]}) {
                   6536: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6537: 				$token->[2]->{$param};
1.339     albertel 6538: 			}
                   6539: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6540: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6541: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6542: 		 # only ws inside the tag, and not in default, so use default
                   6543: 		 # as value
1.599     albertel 6544: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6545: 			} else {
1.321     albertel 6546: 		  # either something interesting inside the tag or default
                   6547:                   # uninteresting
1.599     albertel 6548: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6549: 			}
1.172     www      6550: # end of not-a-package not-a-library import
1.339     albertel 6551: 		    }
1.172     www      6552: # end of not-a-package start tag
1.339     albertel 6553: 		}
1.172     www      6554: # the next is the end of "start tag"
1.339     albertel 6555: 	    }
                   6556: 	}
1.483     albertel 6557: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6558: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6559: 	    #no specific packages #how's our extension
                   6560: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6561: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6562: 					 \%metathesekeys);
                   6563: 	}
1.599     albertel 6564: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6565: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6566: 		#no specific packages well let's get default then
                   6567: 		if ($key!~/^default&/) { next; }
1.488     albertel 6568: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6569: 					     \%metathesekeys);
                   6570: 	    }
                   6571: 	}
1.338     www      6572: # are there custom rights to evaluate
1.599     albertel 6573: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6574: 
1.338     www      6575:     #
                   6576:     # Importing a rights file here
1.339     albertel 6577:     #
                   6578: 	    unless ($depthcount) {
1.599     albertel 6579: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6580: 		my $dir=$filename;
                   6581: 		$dir=~s|[^/]*$||;
                   6582: 		$location=&filelocation($dir,$location);
1.736     albertel 6583: 		my $rights_metadata =
                   6584: 		    &metadata($uri,'keys',$location,'_rights',
                   6585: 			      $depthcount+1);
                   6586: 		foreach my $rights (split(',',$rights_metadata)) {
                   6587: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6588: 		    $metathesekeys{$rights}=1;
1.339     albertel 6589: 		}
                   6590: 	    }
                   6591: 	}
1.737     albertel 6592: 	# uniqifiy package listing
                   6593: 	my %seen;
                   6594: 	my @uniq_packages =
                   6595: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6596: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6597: 
                   6598: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6599: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6600: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6601: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6602: # this is the end of "was not already recently cached
1.71      www      6603:     }
1.599     albertel 6604:     return $metaentry{':'.$what};
1.261     albertel 6605: }
                   6606: 
1.488     albertel 6607: sub metadata_create_package_def {
1.483     albertel 6608:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6609:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6610:     if ($subp eq 'default') { next; }
                   6611:     
1.599     albertel 6612:     if (defined($metaentry{':packages'})) {
                   6613: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6614:     } else {
1.599     albertel 6615: 	$metaentry{':packages'}=$package;
1.483     albertel 6616:     }
                   6617:     my $value=$packagetab{$key};
                   6618:     my $unikey;
                   6619:     $unikey='parameter_0_'.$name;
1.599     albertel 6620:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6621:     $$metathesekeys{$unikey}=1;
1.599     albertel 6622:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6623: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6624:     }
1.599     albertel 6625:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6626: 	$metaentry{':'.$unikey}=
                   6627: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6628:     }
                   6629: }
                   6630: 
1.261     albertel 6631: sub metadata_generate_part0 {
                   6632:     my ($metadata,$metacache,$uri) = @_;
                   6633:     my %allnames;
1.737     albertel 6634:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6635: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6636: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6637: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6638: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6639: 	    $allnames{$name}=$part;
                   6640: 	  }
                   6641: 	}
                   6642:     }
                   6643:     foreach my $name (keys(%allnames)) {
                   6644:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6645:       my $key=":parameter_0_$name";
1.261     albertel 6646:       $$metacache{"$key.part"}='0';
                   6647:       $$metacache{"$key.name"}=$name;
1.428     albertel 6648:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6649: 					   $allnames{$name}.'_'.$name.
                   6650: 					   '.type'};
1.428     albertel 6651:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6652: 			     '.display'};
1.644     www      6653:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6654:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6655:       $$metacache{"$key.display"}=$olddis;
                   6656:     }
1.71      www      6657: }
                   6658: 
1.764     albertel 6659: # ------------------------------------------------------ Devalidate title cache
                   6660: 
                   6661: sub devalidate_title_cache {
                   6662:     my ($url)=@_;
                   6663:     if (!$env{'request.course.id'}) { return; }
                   6664:     my $symb=&symbread($url);
                   6665:     if (!$symb) { return; }
                   6666:     my $key=$env{'request.course.id'}."\0".$symb;
                   6667:     &devalidate_cache_new('title',$key);
                   6668: }
                   6669: 
1.301     www      6670: # ------------------------------------------------- Get the title of a resource
                   6671: 
                   6672: sub gettitle {
                   6673:     my $urlsymb=shift;
                   6674:     my $symb=&symbread($urlsymb);
1.534     albertel 6675:     if ($symb) {
1.620     albertel 6676: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6677: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6678: 	if (defined($cached)) { 
                   6679: 	    return $result;
                   6680: 	}
1.534     albertel 6681: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6682: 	my $title='';
                   6683: 	my %bighash;
1.620     albertel 6684: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6685: 		&GDBM_READER(),0640)) {
                   6686: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6687: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6688: 	    untie %bighash;
                   6689: 	}
                   6690: 	$title=~s/\&colon\;/\:/gs;
                   6691: 	if ($title) {
1.599     albertel 6692: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6693: 	}
                   6694: 	$urlsymb=$url;
                   6695:     }
                   6696:     my $title=&metadata($urlsymb,'title');
                   6697:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6698:     return $title;
1.301     www      6699: }
1.613     albertel 6700: 
1.614     albertel 6701: sub get_slot {
                   6702:     my ($which,$cnum,$cdom)=@_;
                   6703:     if (!$cnum || !$cdom) {
1.790     albertel 6704: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6705: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6706: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6707:     }
1.703     albertel 6708:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6709:     my %slotinfo;
                   6710:     if (exists($remembered{$key})) {
                   6711: 	$slotinfo{$which} = $remembered{$key};
                   6712:     } else {
                   6713: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6714: 	&Apache::lonhomework::showhash(%slotinfo);
                   6715: 	my ($tmp)=keys(%slotinfo);
                   6716: 	if ($tmp=~/^error:/) { return (); }
                   6717: 	$remembered{$key} = $slotinfo{$which};
                   6718:     }
1.616     albertel 6719:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6720: 	return %{$slotinfo{$which}};
                   6721:     }
                   6722:     return $slotinfo{$which};
1.614     albertel 6723: }
1.31      www      6724: # ------------------------------------------------- Update symbolic store links
                   6725: 
                   6726: sub symblist {
                   6727:     my ($mapname,%newhash)=@_;
1.438     www      6728:     $mapname=&deversion(&declutter($mapname));
1.31      www      6729:     my %hash;
1.620     albertel 6730:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6731:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6732:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6733: 	    foreach my $url (keys %newhash) {
                   6734: 		next if ($url eq 'last_known'
                   6735: 			 && $env{'form.no_update_last_known'});
                   6736: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6737: 						    $newhash{$url}->[1],
                   6738: 						    $newhash{$url}->[0]);
1.191     harris41 6739:             }
1.31      www      6740:             if (untie(%hash)) {
                   6741: 		return 'ok';
                   6742:             }
                   6743:         }
                   6744:     }
                   6745:     return 'error';
1.212     www      6746: }
                   6747: 
                   6748: # --------------------------------------------------------------- Verify a symb
                   6749: 
                   6750: sub symbverify {
1.510     www      6751:     my ($symb,$thisurl)=@_;
                   6752:     my $thisfn=$thisurl;
1.439     www      6753:     $thisfn=&declutter($thisfn);
1.215     www      6754: # direct jump to resource in page or to a sequence - will construct own symbs
                   6755:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6756: # check URL part
1.409     www      6757:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6758: 
1.431     www      6759:     unless ($url eq $thisfn) { return 0; }
1.213     www      6760: 
1.216     www      6761:     $symb=&symbclean($symb);
1.510     www      6762:     $thisurl=&deversion($thisurl);
1.439     www      6763:     $thisfn=&deversion($thisfn);
1.213     www      6764: 
                   6765:     my %bighash;
                   6766:     my $okay=0;
1.431     www      6767: 
1.620     albertel 6768:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6769:                             &GDBM_READER(),0640)) {
1.510     www      6770:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6771:         unless ($ids) { 
1.510     www      6772:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6773:         }
                   6774:         if ($ids) {
                   6775: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6776: 	    foreach my $id (split(/\,/,$ids)) {
                   6777: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6778:                if (
                   6779:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6780:    eq $symb) { 
1.620     albertel 6781: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6782: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6783: 		       $okay=1; 
                   6784: 		   }
                   6785: 	       }
1.216     www      6786: 	   }
                   6787:         }
1.213     www      6788: 	untie(%bighash);
                   6789:     }
                   6790:     return $okay;
1.31      www      6791: }
                   6792: 
1.210     www      6793: # --------------------------------------------------------------- Clean-up symb
                   6794: 
                   6795: sub symbclean {
                   6796:     my $symb=shift;
1.568     albertel 6797:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6798: # remove version from map
                   6799:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6800: 
1.210     www      6801: # remove version from URL
                   6802:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6803: 
1.507     www      6804: # remove wrapper
                   6805: 
1.510     www      6806:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6807:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6808:     return $symb;
1.409     www      6809: }
                   6810: 
                   6811: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6812: 
                   6813: sub encode_symb {
                   6814:     my ($map,$resid,$url)=@_;
                   6815:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6816: }
1.409     www      6817: 
                   6818: sub decode_symb {
1.568     albertel 6819:     my $symb=shift;
                   6820:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6821:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6822:     return (&fixversion($map),$resid,&fixversion($url));
                   6823: }
                   6824: 
                   6825: sub fixversion {
                   6826:     my $fn=shift;
1.609     banghart 6827:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6828:     my %bighash;
                   6829:     my $uri=&clutter($fn);
1.620     albertel 6830:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6831: # is this cached?
1.599     albertel 6832:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6833:     if (defined($cached)) { return $result; }
                   6834: # unfortunately not cached, or expired
1.620     albertel 6835:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6836: 	    &GDBM_READER(),0640)) {
                   6837:  	if ($bighash{'version_'.$uri}) {
                   6838:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6839:  	    unless (($version eq 'mostrecent') || 
                   6840: 		    ($version==&getversion($uri))) {
1.440     www      6841:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6842:  	    }
                   6843:  	}
                   6844:  	untie %bighash;
1.413     www      6845:     }
1.599     albertel 6846:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6847: }
                   6848: 
                   6849: sub deversion {
                   6850:     my $url=shift;
                   6851:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6852:     return $url;
1.210     www      6853: }
                   6854: 
1.31      www      6855: # ------------------------------------------------------ Return symb list entry
                   6856: 
                   6857: sub symbread {
1.249     www      6858:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6859:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6860:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6861: # no filename provided? try from environment
1.44      www      6862:     unless ($thisfn) {
1.620     albertel 6863:         if ($env{'request.symb'}) {
                   6864: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6865: 	}
1.620     albertel 6866: 	$thisfn=$env{'request.filename'};
1.44      www      6867:     }
1.569     albertel 6868:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6869: # is that filename actually a symb? Verify, clean, and return
                   6870:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6871: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6872: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6873: 	}
1.242     www      6874:     }
1.44      www      6875:     $thisfn=declutter($thisfn);
1.31      www      6876:     my %hash;
1.37      www      6877:     my %bighash;
                   6878:     my $syval='';
1.620     albertel 6879:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6880:         my $targetfn = $thisfn;
1.609     banghart 6881:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6882:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6883:         }
1.687     albertel 6884: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6885: 	    $targetfn=$1;
                   6886: 	}
1.620     albertel 6887:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6888:                       &GDBM_READER(),0640)) {
1.481     raeburn  6889: 	    $syval=$hash{$targetfn};
1.37      www      6890:             untie(%hash);
                   6891:         }
                   6892: # ---------------------------------------------------------- There was an entry
                   6893:         if ($syval) {
1.601     albertel 6894: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6895: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6896: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6897: 		    #return $env{$cache_str}='';
1.601     albertel 6898: 		#}    
                   6899: 		#$syval.=$1;
                   6900: 	    #}
1.37      www      6901:         } else {
                   6902: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6903:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6904:                             &GDBM_READER(),0640)) {
1.37      www      6905: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6906:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6907:               unless ($ids) { 
                   6908:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6909:               }
                   6910:               unless ($ids) {
                   6911: # alias?
                   6912: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6913:               }
1.37      www      6914:               if ($ids) {
                   6915: # ------------------------------------------------------------------- Has ID(s)
                   6916:                  my @possibilities=split(/\,/,$ids);
1.39      www      6917:                  if ($#possibilities==0) {
                   6918: # ----------------------------------------------- There is only one possibility
1.37      www      6919: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6920: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6921: 						    $resid,$thisfn);
1.249     www      6922:                  } elsif (!$donotrecurse) {
1.39      www      6923: # ------------------------------------------ There is more than one possibility
                   6924:                      my $realpossible=0;
1.800     albertel 6925:                      foreach my $id (@possibilities) {
                   6926: 			 my $file=$bighash{'src_'.$id};
1.39      www      6927:                          if (&allowed('bre',$file)) {
1.800     albertel 6928:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6929:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6930: 				$realpossible++;
1.626     albertel 6931:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6932: 						    $resid,$thisfn);
1.39      www      6933:                             }
                   6934: 			 }
1.191     harris41 6935:                      }
1.39      www      6936: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6937:                  } else {
                   6938:                      $syval='';
1.37      www      6939:                  }
                   6940: 	      }
                   6941:               untie(%bighash)
1.481     raeburn  6942:            }
1.31      www      6943:         }
1.62      www      6944:         if ($syval) {
1.620     albertel 6945: 	    return $env{$cache_str}=$syval;
1.62      www      6946:         }
1.31      www      6947:     }
1.44      www      6948:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6949:     return $env{$cache_str}='';
1.31      www      6950: }
                   6951: 
                   6952: # ---------------------------------------------------------- Return random seed
                   6953: 
1.32      www      6954: sub numval {
                   6955:     my $txt=shift;
                   6956:     $txt=~tr/A-J/0-9/;
                   6957:     $txt=~tr/a-j/0-9/;
                   6958:     $txt=~tr/K-T/0-9/;
                   6959:     $txt=~tr/k-t/0-9/;
                   6960:     $txt=~tr/U-Z/0-5/;
                   6961:     $txt=~tr/u-z/0-5/;
                   6962:     $txt=~s/\D//g;
1.564     albertel 6963:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6964:     return int($txt);
1.368     albertel 6965: }
                   6966: 
1.484     albertel 6967: sub numval2 {
                   6968:     my $txt=shift;
                   6969:     $txt=~tr/A-J/0-9/;
                   6970:     $txt=~tr/a-j/0-9/;
                   6971:     $txt=~tr/K-T/0-9/;
                   6972:     $txt=~tr/k-t/0-9/;
                   6973:     $txt=~tr/U-Z/0-5/;
                   6974:     $txt=~tr/u-z/0-5/;
                   6975:     $txt=~s/\D//g;
                   6976:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6977:     my $total;
                   6978:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6979:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6980:     return int($total);
                   6981: }
                   6982: 
1.575     albertel 6983: sub numval3 {
                   6984:     use integer;
                   6985:     my $txt=shift;
                   6986:     $txt=~tr/A-J/0-9/;
                   6987:     $txt=~tr/a-j/0-9/;
                   6988:     $txt=~tr/K-T/0-9/;
                   6989:     $txt=~tr/k-t/0-9/;
                   6990:     $txt=~tr/U-Z/0-5/;
                   6991:     $txt=~tr/u-z/0-5/;
                   6992:     $txt=~s/\D//g;
                   6993:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6994:     my $total;
                   6995:     foreach my $val (@txts) { $total+=$val; }
                   6996:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6997:     return $total;
                   6998: }
                   6999: 
1.675     albertel 7000: sub digest {
                   7001:     my ($data)=@_;
                   7002:     my $digest=&Digest::MD5::md5($data);
                   7003:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7004:     my ($e,$f);
                   7005:     {
                   7006:         use integer;
                   7007:         $e=($a+$b);
                   7008:         $f=($c+$d);
                   7009:         if ($_64bit) {
                   7010:             $e=(($e<<32)>>32);
                   7011:             $f=(($f<<32)>>32);
                   7012:         }
                   7013:     }
                   7014:     if (wantarray) {
                   7015: 	return ($e,$f);
                   7016:     } else {
                   7017: 	my $g;
                   7018: 	{
                   7019: 	    use integer;
                   7020: 	    $g=($e+$f);
                   7021: 	    if ($_64bit) {
                   7022: 		$g=(($g<<32)>>32);
                   7023: 	    }
                   7024: 	}
                   7025: 	return $g;
                   7026:     }
                   7027: }
                   7028: 
1.368     albertel 7029: sub latest_rnd_algorithm_id {
1.675     albertel 7030:     return '64bit5';
1.366     albertel 7031: }
1.32      www      7032: 
1.503     albertel 7033: sub get_rand_alg {
                   7034:     my ($courseid)=@_;
1.790     albertel 7035:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7036:     if ($courseid) {
1.620     albertel 7037: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7038:     }
                   7039:     return &latest_rnd_algorithm_id();
                   7040: }
                   7041: 
1.562     albertel 7042: sub validCODE {
                   7043:     my ($CODE)=@_;
                   7044:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7045:     return 0;
                   7046: }
                   7047: 
1.491     albertel 7048: sub getCODE {
1.620     albertel 7049:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7050:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7051: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7052: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7053: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7054:     }
                   7055:     return undef;
                   7056: }
                   7057: 
1.31      www      7058: sub rndseed {
1.155     albertel 7059:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7060:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 7061:     if (!$symb) {
1.366     albertel 7062: 	unless ($symb=$wsymb) { return time; }
                   7063:     }
                   7064:     if (!$courseid) { $courseid=$wcourseid; }
                   7065:     if (!$domain) { $domain=$wdomain; }
                   7066:     if (!$username) { $username=$wusername }
1.503     albertel 7067:     my $which=&get_rand_alg();
1.803     albertel 7068: 
1.491     albertel 7069:     if (defined(&getCODE())) {
1.675     albertel 7070: 	if ($which eq '64bit5') {
                   7071: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7072: 	} elsif ($which eq '64bit4') {
1.575     albertel 7073: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7074: 	} else {
                   7075: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7076: 	}
1.675     albertel 7077:     } elsif ($which eq '64bit5') {
                   7078: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7079:     } elsif ($which eq '64bit4') {
                   7080: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7081:     } elsif ($which eq '64bit3') {
                   7082: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7083:     } elsif ($which eq '64bit2') {
                   7084: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7085:     } elsif ($which eq '64bit') {
                   7086: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7087:     }
                   7088:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7089: }
                   7090: 
                   7091: sub rndseed_32bit {
                   7092:     my ($symb,$courseid,$domain,$username)=@_;
                   7093:     {
                   7094: 	use integer;
                   7095: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7096: 	my $symbseed=numval($symb) << 22;
                   7097: 	my $namechck=unpack("%32C*",$username) << 17;
                   7098: 	my $nameseed=numval($username) << 12;
                   7099: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7100: 	my $courseseed=unpack("%32C*",$courseid);
                   7101: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7102: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7103: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7104: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7105: 	return $num;
                   7106:     }
                   7107: }
                   7108: 
                   7109: sub rndseed_64bit {
                   7110:     my ($symb,$courseid,$domain,$username)=@_;
                   7111:     {
                   7112: 	use integer;
                   7113: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7114: 	my $symbseed=numval($symb) << 10;
                   7115: 	my $namechck=unpack("%32S*",$username);
                   7116: 	
                   7117: 	my $nameseed=numval($username) << 21;
                   7118: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7119: 	my $courseseed=unpack("%32S*",$courseid);
                   7120: 	
                   7121: 	my $num1=$symbchck+$symbseed+$namechck;
                   7122: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7123: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7124: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7125: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7126: 	return "$num1,$num2";
1.155     albertel 7127:     }
1.366     albertel 7128: }
                   7129: 
1.443     albertel 7130: sub rndseed_64bit2 {
                   7131:     my ($symb,$courseid,$domain,$username)=@_;
                   7132:     {
                   7133: 	use integer;
                   7134: 	# strings need to be an even # of cahracters long, it it is odd the
                   7135:         # last characters gets thrown away
                   7136: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7137: 	my $symbseed=numval($symb) << 10;
                   7138: 	my $namechck=unpack("%32S*",$username.' ');
                   7139: 	
                   7140: 	my $nameseed=numval($username) << 21;
1.501     albertel 7141: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7142: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7143: 	
                   7144: 	my $num1=$symbchck+$symbseed+$namechck;
                   7145: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7146: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7147: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7148: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7149: 	return "$num1,$num2";
                   7150:     }
                   7151: }
                   7152: 
                   7153: sub rndseed_64bit3 {
                   7154:     my ($symb,$courseid,$domain,$username)=@_;
                   7155:     {
                   7156: 	use integer;
                   7157: 	# strings need to be an even # of cahracters long, it it is odd the
                   7158:         # last characters gets thrown away
                   7159: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7160: 	my $symbseed=numval2($symb) << 10;
                   7161: 	my $namechck=unpack("%32S*",$username.' ');
                   7162: 	
                   7163: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7164: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7165: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7166: 	
                   7167: 	my $num1=$symbchck+$symbseed+$namechck;
                   7168: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7169: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7170: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7171: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7172: 	
1.503     albertel 7173: 	return "$num1:$num2";
1.443     albertel 7174:     }
                   7175: }
                   7176: 
1.575     albertel 7177: sub rndseed_64bit4 {
                   7178:     my ($symb,$courseid,$domain,$username)=@_;
                   7179:     {
                   7180: 	use integer;
                   7181: 	# strings need to be an even # of cahracters long, it it is odd the
                   7182:         # last characters gets thrown away
                   7183: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7184: 	my $symbseed=numval3($symb) << 10;
                   7185: 	my $namechck=unpack("%32S*",$username.' ');
                   7186: 	
                   7187: 	my $nameseed=numval3($username) << 21;
                   7188: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7189: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7190: 	
                   7191: 	my $num1=$symbchck+$symbseed+$namechck;
                   7192: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7193: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7194: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7195: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7196: 	
                   7197: 	return "$num1:$num2";
                   7198:     }
                   7199: }
                   7200: 
1.675     albertel 7201: sub rndseed_64bit5 {
                   7202:     my ($symb,$courseid,$domain,$username)=@_;
                   7203:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7204:     return "$num1:$num2";
                   7205: }
                   7206: 
1.366     albertel 7207: sub rndseed_CODE_64bit {
                   7208:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7209:     {
1.366     albertel 7210: 	use integer;
1.443     albertel 7211: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7212: 	my $symbseed=numval2($symb);
1.491     albertel 7213: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7214: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7215: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7216: 	my $num1=$symbseed+$CODEchck;
                   7217: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7218: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7219: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7220: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7221: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7222: 	return "$num1:$num2";
1.366     albertel 7223:     }
                   7224: }
                   7225: 
1.575     albertel 7226: sub rndseed_CODE_64bit4 {
                   7227:     my ($symb,$courseid,$domain,$username)=@_;
                   7228:     {
                   7229: 	use integer;
                   7230: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7231: 	my $symbseed=numval3($symb);
                   7232: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7233: 	my $CODEseed=numval3(&getCODE());
                   7234: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7235: 	my $num1=$symbseed+$CODEchck;
                   7236: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7237: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7238: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7239: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7240: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7241: 	return "$num1:$num2";
                   7242:     }
                   7243: }
                   7244: 
1.675     albertel 7245: sub rndseed_CODE_64bit5 {
                   7246:     my ($symb,$courseid,$domain,$username)=@_;
                   7247:     my $code = &getCODE();
                   7248:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7249:     return "$num1:$num2";
                   7250: }
                   7251: 
1.366     albertel 7252: sub setup_random_from_rndseed {
                   7253:     my ($rndseed)=@_;
1.503     albertel 7254:     if ($rndseed =~/([,:])/) {
                   7255: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7256: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7257:     } else {
                   7258: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7259:     }
1.36      albertel 7260: }
                   7261: 
1.474     albertel 7262: sub latest_receipt_algorithm_id {
1.835     albertel 7263:     return 'receipt3';
1.474     albertel 7264: }
                   7265: 
1.480     www      7266: sub recunique {
                   7267:     my $fucourseid=shift;
                   7268:     my $unique;
1.835     albertel 7269:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7270: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7271: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7272:     } else {
                   7273: 	$unique=$perlvar{'lonReceipt'};
                   7274:     }
                   7275:     return unpack("%32C*",$unique);
                   7276: }
                   7277: 
                   7278: sub recprefix {
                   7279:     my $fucourseid=shift;
                   7280:     my $prefix;
1.835     albertel 7281:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7282: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7283: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7284:     } else {
                   7285: 	$prefix=$perlvar{'lonHostID'};
                   7286:     }
                   7287:     return unpack("%32C*",$prefix);
                   7288: }
                   7289: 
1.76      www      7290: sub ireceipt {
1.474     albertel 7291:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7292: 
                   7293:     my $return =&recprefix($fucourseid).'-';
                   7294: 
                   7295:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7296: 	$env{'request.state'} eq 'construct') {
                   7297: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7298: 	return $return;
                   7299:     }
                   7300: 
1.76      www      7301:     my $cuname=unpack("%32C*",$funame);
                   7302:     my $cudom=unpack("%32C*",$fudom);
                   7303:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7304:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7305:     my $cunique=&recunique($fucourseid);
1.474     albertel 7306:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7307:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7308: 
1.790     albertel 7309: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7310: 			       
                   7311: 	$return.= ($cunique%$cuname+
                   7312: 		   $cunique%$cudom+
                   7313: 		   $cusymb%$cuname+
                   7314: 		   $cusymb%$cudom+
                   7315: 		   $cucourseid%$cuname+
                   7316: 		   $cucourseid%$cudom+
                   7317: 		   $cpart%$cuname+
                   7318: 		   $cpart%$cudom);
                   7319:     } else {
                   7320: 	$return.= ($cunique%$cuname+
                   7321: 		   $cunique%$cudom+
                   7322: 		   $cusymb%$cuname+
                   7323: 		   $cusymb%$cudom+
                   7324: 		   $cucourseid%$cuname+
                   7325: 		   $cucourseid%$cudom);
                   7326:     }
                   7327:     return $return;
1.76      www      7328: }
                   7329: 
                   7330: sub receipt {
1.474     albertel 7331:     my ($part)=@_;
1.790     albertel 7332:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7333:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7334: }
1.260     ng       7335: 
1.790     albertel 7336: sub whichuser {
                   7337:     my ($passedsymb)=@_;
                   7338:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7339:     if (defined($env{'form.grade_symb'})) {
                   7340: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7341: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7342: 	if (!$allowed &&
                   7343: 	    exists($env{'request.course.sec'}) &&
                   7344: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7345: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7346: 			      '/'.$env{'request.course.sec'});
                   7347: 	}
                   7348: 	if ($allowed) {
                   7349: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7350: 	    $courseid=$tmp_courseid;
                   7351: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7352: 	    ($name)=&get_env_multiple('form.grade_username');
                   7353: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7354: 	}
                   7355:     }
                   7356:     if (!$passedsymb) {
                   7357: 	$symb=&symbread();
                   7358:     } else {
                   7359: 	$symb=$passedsymb;
                   7360:     }
                   7361:     $courseid=$env{'request.course.id'};
                   7362:     $domain=$env{'user.domain'};
                   7363:     $name=$env{'user.name'};
                   7364:     if ($name eq 'public' && $domain eq 'public') {
                   7365: 	if (!defined($env{'form.username'})) {
                   7366: 	    $env{'form.username'}.=time.rand(10000000);
                   7367: 	}
                   7368: 	$name.=$env{'form.username'};
                   7369:     }
                   7370:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7371: 
                   7372: }
                   7373: 
1.36      albertel 7374: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7375: # returns either the contents of the file or 
                   7376: # -1 if the file doesn't exist
1.481     raeburn  7377: #
                   7378: # if the target is a file that was uploaded via DOCS, 
                   7379: # a check will be made to see if a current copy exists on the local server,
                   7380: # if it does this will be served, otherwise a copy will be retrieved from
                   7381: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7382: # the local server.   
1.472     albertel 7383: 
1.36      albertel 7384: sub getfile {
1.538     albertel 7385:     my ($file) = @_;
1.609     banghart 7386:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7387:     &repcopy($file);
                   7388:     return &readfile($file);
                   7389: }
                   7390: 
                   7391: sub repcopy_userfile {
                   7392:     my ($file)=@_;
1.609     banghart 7393:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7394:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7395:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7396: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7397:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7398:     if (-e "$file") {
1.828     www      7399: # we already have a local copy, check it out
1.538     albertel 7400: 	my @fileinfo = stat($file);
1.828     www      7401: 	my $rtncode;
                   7402: 	my $info;
1.538     albertel 7403: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7404: 	if ($lwpresp ne 'ok') {
1.828     www      7405: # there is no such file anymore, even though we had a local copy
1.482     albertel 7406: 	    if ($rtncode eq '404') {
1.538     albertel 7407: 		unlink($file);
1.482     albertel 7408: 	    }
                   7409: 	    return -1;
                   7410: 	}
                   7411: 	if ($info < $fileinfo[9]) {
1.828     www      7412: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7413: 	    return 'ok';
1.828     www      7414: 	} else {
                   7415: # the file is outdated, get rid of it
                   7416: 	    unlink($file);
1.482     albertel 7417: 	}
1.828     www      7418:     }
                   7419: # one way or the other, at this point, we don't have the file
                   7420: # construct the correct path for the file
                   7421:     my @parts = ($cdom,$cnum); 
                   7422:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7423: 	push @parts, split(/\//,$1);
                   7424:     }
                   7425:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7426:     foreach my $part (@parts) {
                   7427: 	$path .= '/'.$part;
                   7428: 	if (!-e $path) {
                   7429: 	    mkdir($path,0770);
1.482     albertel 7430: 	}
                   7431:     }
1.828     www      7432: # now the path exists for sure
                   7433: # get a user agent
                   7434:     my $ua=new LWP::UserAgent;
                   7435:     my $transferfile=$file.'.in.transfer';
                   7436: # FIXME: this should flock
                   7437:     if (-e $transferfile) { return 'ok'; }
                   7438:     my $request;
                   7439:     $uri=~s/^\///;
1.838     albertel 7440:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7441:     my $response=$ua->request($request,$transferfile);
                   7442: # did it work?
                   7443:     if ($response->is_error()) {
                   7444: 	unlink($transferfile);
                   7445: 	&logthis("Userfile repcopy failed for $uri");
                   7446: 	return -1;
                   7447:     }
                   7448: # worked, rename the transfer file
                   7449:     rename($transferfile,$file);
1.607     raeburn  7450:     return 'ok';
1.481     raeburn  7451: }
                   7452: 
1.517     albertel 7453: sub tokenwrapper {
                   7454:     my $uri=shift;
1.552     albertel 7455:     $uri=~s|^http\://([^/]+)||;
                   7456:     $uri=~s|^/||;
1.620     albertel 7457:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7458:     my $token=$1;
1.552     albertel 7459:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7460:     if ($udom && $uname && $file) {
                   7461: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7462:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7463:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7464:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7465:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7466:     } else {
                   7467:         return '/adm/notfound.html';
                   7468:     }
                   7469: }
                   7470: 
1.828     www      7471: # call with reqtype HEAD: get last modification time
                   7472: # call with reqtype GET: get the file contents
                   7473: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7474: #
1.481     raeburn  7475: sub getuploaded {
                   7476:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7477:     $uri=~s/^\///;
1.838     albertel 7478:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7479:     my $ua=new LWP::UserAgent;
                   7480:     my $request=new HTTP::Request($reqtype,$uri);
                   7481:     my $response=$ua->request($request);
                   7482:     $$rtncode = $response->code;
1.482     albertel 7483:     if (! $response->is_success()) {
                   7484: 	return 'failed';
                   7485:     }      
                   7486:     if ($reqtype eq 'HEAD') {
1.486     www      7487: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7488:     } elsif ($reqtype eq 'GET') {
                   7489: 	$$info = $response->content;
1.472     albertel 7490:     }
1.482     albertel 7491:     return 'ok';
1.36      albertel 7492: }
                   7493: 
1.481     raeburn  7494: sub readfile {
                   7495:     my $file = shift;
                   7496:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7497:     my $fh;
                   7498:     open($fh,"<$file");
                   7499:     my $a='';
1.800     albertel 7500:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7501:     return $a;
                   7502: }
                   7503: 
1.36      albertel 7504: sub filelocation {
1.590     banghart 7505:     my ($dir,$file) = @_;
                   7506:     my $location;
                   7507:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7508: 
                   7509:     if ($file =~ m-^/adm/-) {
                   7510: 	$file=~s-^/adm/wrapper/-/-;
                   7511: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7512:     }
1.590     banghart 7513:     if ($file=~m:^/~:) { # is a contruction space reference
                   7514:         $location = $file;
                   7515:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7516:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7517: 	# is a correct contruction space reference
                   7518:         $location = $file;
1.609     banghart 7519:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7520:         my ($udom,$uname,$filename)=
1.811     albertel 7521:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7522:         my $home=&homeserver($uname,$udom);
                   7523:         my $is_me=0;
                   7524:         my @ids=&current_machine_ids();
                   7525:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7526:         if ($is_me) {
1.740     www      7527:   	    $location=&propath($udom,$uname).
1.590     banghart 7528:   	      '/userfiles/'.$filename;
                   7529:         } else {
                   7530:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7531:   	      $udom.'/'.$uname.'/'.$filename;
                   7532:         }
                   7533:     } else {
                   7534:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7535:         $file=~s:^/res/:/:;
                   7536:         if ( !( $file =~ m:^/:) ) {
                   7537:             $location = $dir. '/'.$file;
                   7538:         } else {
                   7539:             $location = '/home/httpd/html/res'.$file;
                   7540:         }
1.59      albertel 7541:     }
1.590     banghart 7542:     $location=~s://+:/:g; # remove duplicate /
                   7543:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7544:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7545:     return $location;
1.46      www      7546: }
1.36      albertel 7547: 
1.46      www      7548: sub hreflocation {
                   7549:     my ($dir,$file)=@_;
1.460     albertel 7550:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7551: 	$file=filelocation($dir,$file);
1.700     albertel 7552:     } elsif ($file=~m-^/adm/-) {
                   7553: 	$file=~s-^/adm/wrapper/-/-;
                   7554: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7555:     }
                   7556:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7557: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7558:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7559: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7560:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7561: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7562: 	    -/uploaded/$1/$2/-x;
1.46      www      7563:     }
1.462     albertel 7564:     return $file;
1.465     albertel 7565: }
                   7566: 
                   7567: sub current_machine_domains {
1.853     albertel 7568:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7569: }
                   7570: 
                   7571: sub machine_domains {
                   7572:     my ($hostname) = @_;
1.465     albertel 7573:     my @domains;
1.838     albertel 7574:     my %hostname = &all_hostnames();
1.465     albertel 7575:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7576: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7577: 	if ($hostname eq $name) {
1.844     albertel 7578: 	    push(@domains,&host_domain($id));
1.465     albertel 7579: 	}
                   7580:     }
                   7581:     return @domains;
                   7582: }
                   7583: 
                   7584: sub current_machine_ids {
1.853     albertel 7585:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7586: }
                   7587: 
                   7588: sub machine_ids {
                   7589:     my ($hostname) = @_;
                   7590:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7591:     my @ids;
1.838     albertel 7592:     my %hostname = &all_hostnames();
1.465     albertel 7593:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7594: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7595: 	if ($hostname eq $name) {
                   7596: 	    push(@ids,$id);
                   7597: 	}
                   7598:     }
                   7599:     return @ids;
1.31      www      7600: }
                   7601: 
1.824     raeburn  7602: sub additional_machine_domains {
                   7603:     my @domains;
                   7604:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7605:     while( my $line = <$fh>) {
                   7606:         $line =~ s/\s//g;
                   7607:         push(@domains,$line);
                   7608:     }
                   7609:     return @domains;
                   7610: }
                   7611: 
                   7612: sub default_login_domain {
                   7613:     my $domain = $perlvar{'lonDefDomain'};
                   7614:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7615:     foreach my $posdom (&current_machine_domains(),
                   7616:                         &additional_machine_domains()) {
                   7617:         if (lc($posdom) eq lc($testdomain)) {
                   7618:             $domain=$posdom;
                   7619:             last;
                   7620:         }
                   7621:     }
                   7622:     return $domain;
                   7623: }
                   7624: 
1.31      www      7625: # ------------------------------------------------------------- Declutters URLs
                   7626: 
                   7627: sub declutter {
                   7628:     my $thisfn=shift;
1.569     albertel 7629:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7630:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7631:     $thisfn=~s/^\///;
1.697     albertel 7632:     $thisfn=~s|^adm/wrapper/||;
                   7633:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7634:     $thisfn=~s/^res\///;
1.235     www      7635:     $thisfn=~s/\?.+$//;
1.268     www      7636:     return $thisfn;
                   7637: }
                   7638: 
                   7639: # ------------------------------------------------------------- Clutter up URLs
                   7640: 
                   7641: sub clutter {
                   7642:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7643:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7644:        $thisfn='/res'.$thisfn; 
                   7645:     }
1.694     albertel 7646:     if ($thisfn !~m|/adm|) {
1.695     albertel 7647: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7648: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7649: 	} else {
                   7650: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7651: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7652: 	    if ($embstyle eq 'ssi'
                   7653: 		|| ($embstyle eq 'hdn')
                   7654: 		|| ($embstyle eq 'rat')
                   7655: 		|| ($embstyle eq 'prv')
                   7656: 		|| ($embstyle eq 'ign')) {
                   7657: 		#do nothing with these
                   7658: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7659: 		|| ($embstyle eq 'emb')
                   7660: 		|| ($embstyle eq 'wrp')) {
                   7661: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7662: 	    } elsif ($embstyle eq 'unk'
                   7663: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7664: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7665: 	    } else {
1.718     www      7666: #		&logthis("Got a blank emb style");
1.695     albertel 7667: 	    }
1.694     albertel 7668: 	}
                   7669:     }
1.31      www      7670:     return $thisfn;
1.12      www      7671: }
                   7672: 
1.787     albertel 7673: sub clutter_with_no_wrapper {
                   7674:     my $uri = &clutter(shift);
                   7675:     if ($uri =~ m-^/adm/-) {
                   7676: 	$uri =~ s-^/adm/wrapper/-/-;
                   7677: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7678:     }
                   7679:     return $uri;
                   7680: }
                   7681: 
1.557     albertel 7682: sub freeze_escape {
                   7683:     my ($value)=@_;
                   7684:     if (ref($value)) {
                   7685: 	$value=&nfreeze($value);
                   7686: 	return '__FROZEN__'.&escape($value);
                   7687:     }
                   7688:     return &escape($value);
                   7689: }
                   7690: 
1.11      www      7691: 
1.557     albertel 7692: sub thaw_unescape {
                   7693:     my ($value)=@_;
                   7694:     if ($value =~ /^__FROZEN__/) {
                   7695: 	substr($value,0,10,undef);
                   7696: 	$value=&unescape($value);
                   7697: 	return &thaw($value);
                   7698:     }
                   7699:     return &unescape($value);
                   7700: }
                   7701: 
1.436     albertel 7702: sub correct_line_ends {
                   7703:     my ($result)=@_;
                   7704:     $$result =~s/\r\n/\n/mg;
                   7705:     $$result =~s/\r/\n/mg;
1.415     albertel 7706: }
1.1       albertel 7707: # ================================================================ Main Program
                   7708: 
1.184     www      7709: sub goodbye {
1.204     albertel 7710:    &logthis("Starting Shut down");
1.443     albertel 7711: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7712:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7713: #converted
1.599     albertel 7714: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7715:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7716: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7717: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7718: #1.1 only
1.870     albertel 7719: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7720: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7721: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7722: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7723:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7724:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7725:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7726:    &flushcourselogs();
                   7727:    &logthis("Shutting down");
                   7728: }
                   7729: 
1.852     albertel 7730: sub get_dns {
1.869     albertel 7731:     my ($url,$func,$ignore_cache) = @_;
                   7732:     if (!$ignore_cache) {
                   7733: 	my ($content,$cached)=
                   7734: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7735: 	if ($cached) {
                   7736: 	    &$func($content);
                   7737: 	    return;
                   7738: 	}
                   7739:     }
                   7740: 
                   7741:     my %alldns;
1.852     albertel 7742:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7743:     foreach my $dns (<$config>) {
                   7744: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7745: 	$alldns{$1} = 1;
                   7746:     }
                   7747:     while (%alldns) {
                   7748: 	my ($dns) = keys(%alldns);
                   7749: 	delete($alldns{$dns});
1.852     albertel 7750: 	my $ua=new LWP::UserAgent;
                   7751: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7752: 	my $response=$ua->request($request);
                   7753: 	next if ($response->is_error());
                   7754: 	my @content = split("\n",$response->content);
1.869     albertel 7755: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7756: 	&$func(\@content);
1.869     albertel 7757: 	return;
1.852     albertel 7758:     }
                   7759:     close($config);
1.871     albertel 7760:     my $which = (split('/',$url))[3];
                   7761:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7762:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7763:     my @content = <$config>;
                   7764:     &$func(\@content);
                   7765:     return;
1.852     albertel 7766: }
1.327     albertel 7767: # ------------------------------------------------------------ Read domain file
                   7768: {
1.852     albertel 7769:     my $loaded;
1.846     albertel 7770:     my %domain;
                   7771: 
1.852     albertel 7772:     sub parse_domain_tab {
                   7773: 	my ($lines) = @_;
                   7774: 	foreach my $line (@$lines) {
                   7775: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7776: 
1.846     albertel 7777: 	    chomp($line);
1.852     albertel 7778: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7779: 	    my %this_domain;
                   7780: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7781: 			       'lang_def', 'city', 'longi', 'lati',
                   7782: 			       'primary') {
                   7783: 		$this_domain{$field} = shift(@elements);
                   7784: 	    }
                   7785: 	    $domain{$name} = \%this_domain;
1.852     albertel 7786: 	}
                   7787:     }
1.864     albertel 7788: 
                   7789:     sub reset_domain_info {
                   7790: 	undef($loaded);
                   7791: 	undef(%domain);
                   7792:     }
                   7793: 
1.852     albertel 7794:     sub load_domain_tab {
1.869     albertel 7795: 	my ($ignore_cache) = @_;
                   7796: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7797: 	my $fh;
                   7798: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7799: 	    my @lines = <$fh>;
                   7800: 	    &parse_domain_tab(\@lines);
1.448     albertel 7801: 	}
1.852     albertel 7802: 	close($fh);
                   7803: 	$loaded = 1;
1.327     albertel 7804:     }
1.846     albertel 7805: 
                   7806:     sub domain {
1.852     albertel 7807: 	&load_domain_tab() if (!$loaded);
                   7808: 
1.846     albertel 7809: 	my ($name,$what) = @_;
                   7810: 	return if ( !exists($domain{$name}) );
                   7811: 
                   7812: 	if (!$what) {
                   7813: 	    return $domain{$name}{'description'};
                   7814: 	}
                   7815: 	return $domain{$name}{$what};
                   7816:     }
1.327     albertel 7817: }
                   7818: 
                   7819: 
1.1       albertel 7820: # ------------------------------------------------------------- Read hosts file
                   7821: {
1.838     albertel 7822:     my %hostname;
1.844     albertel 7823:     my %hostdom;
1.845     albertel 7824:     my %libserv;
1.852     albertel 7825:     my $loaded;
                   7826: 
                   7827:     sub parse_hosts_tab {
                   7828: 	my ($file) = @_;
                   7829: 	foreach my $configline (@$file) {
                   7830: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7831: 	    next if ($configline =~ /^\^/);
                   7832: 	    chomp($configline);
                   7833: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7834: 	    $name=~s/\s//g;
                   7835: 	    if ($id && $domain && $role && $name) {
                   7836: 		$hostname{$id}=$name;
                   7837: 		$hostdom{$id}=$domain;
                   7838: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   7839: 	    }
                   7840: 	}
                   7841:     }
1.864     albertel 7842:     
                   7843:     sub reset_hosts_info {
                   7844: 	&reset_domain_info();
                   7845: 	&reset_hosts_ip_info();
                   7846: 	undef(%hostname);
                   7847: 	undef(%hostdom);
                   7848: 	undef(%libserv);
                   7849: 	undef($loaded);
                   7850:     }
1.1       albertel 7851: 
1.852     albertel 7852:     sub load_hosts_tab {
1.869     albertel 7853: 	my ($ignore_cache) = @_;
                   7854: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 7855: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7856: 	my @config = <$config>;
                   7857: 	&parse_hosts_tab(\@config);
                   7858: 	close($config);
                   7859: 	$loaded=1;
1.1       albertel 7860:     }
1.852     albertel 7861: 
1.838     albertel 7862:     sub hostname {
1.852     albertel 7863: 	&load_hosts_tab() if (!$loaded);
                   7864: 
1.838     albertel 7865: 	my ($lonid) = @_;
                   7866: 	return $hostname{$lonid};
                   7867:     }
1.845     albertel 7868: 
1.838     albertel 7869:     sub all_hostnames {
1.852     albertel 7870: 	&load_hosts_tab() if (!$loaded);
                   7871: 
1.838     albertel 7872: 	return %hostname;
                   7873:     }
1.845     albertel 7874: 
                   7875:     sub is_library {
1.852     albertel 7876: 	&load_hosts_tab() if (!$loaded);
                   7877: 
1.845     albertel 7878: 	return exists($libserv{$_[0]});
                   7879:     }
                   7880: 
                   7881:     sub all_library {
1.852     albertel 7882: 	&load_hosts_tab() if (!$loaded);
                   7883: 
1.845     albertel 7884: 	return %libserv;
                   7885:     }
                   7886: 
1.841     albertel 7887:     sub get_servers {
1.852     albertel 7888: 	&load_hosts_tab() if (!$loaded);
                   7889: 
1.841     albertel 7890: 	my ($domain,$type) = @_;
                   7891: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7892: 	                                          : %hostname;
                   7893: 	my %result;
1.842     albertel 7894: 	if (ref($domain) eq 'ARRAY') {
                   7895: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7896: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7897: 		    $result{$host} = $hostname;
                   7898: 		}
                   7899: 	    }
                   7900: 	} else {
                   7901: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7902: 		if ($hostdom{$host} eq $domain) {
                   7903: 		    $result{$host} = $hostname;
                   7904: 		}
1.841     albertel 7905: 	    }
                   7906: 	}
                   7907: 	return %result;
                   7908:     }
1.845     albertel 7909: 
1.844     albertel 7910:     sub host_domain {
1.852     albertel 7911: 	&load_hosts_tab() if (!$loaded);
                   7912: 
1.844     albertel 7913: 	my ($lonid) = @_;
                   7914: 	return $hostdom{$lonid};
                   7915:     }
                   7916: 
1.841     albertel 7917:     sub all_domains {
1.852     albertel 7918: 	&load_hosts_tab() if (!$loaded);
                   7919: 
1.841     albertel 7920: 	my %seen;
                   7921: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7922: 	return @uniq;
                   7923:     }
1.1       albertel 7924: }
                   7925: 
1.847     albertel 7926: { 
                   7927:     my %iphost;
1.856     albertel 7928:     my %name_to_ip;
                   7929:     my %lonid_to_ip;
1.869     albertel 7930: 
                   7931:     my %valid_ip;
                   7932:     sub valid_ip {
                   7933: 	my ($ip) = @_;
                   7934: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
                   7935: 	    return 1;	
                   7936: 	}
                   7937: 	my $name = gethostbyip($ip);
                   7938: 	my $lonid = &hostname($name);
                   7939: 	if (defined($lonid)) {
                   7940: 	    $valid_ip{$ip} = $lonid;
                   7941: 	    return 1;
                   7942: 	}
                   7943: 	my %iphosts = &get_iphost();
                   7944: 	if (ref($iphost{$ip})) {
                   7945: 	    return 1;	
                   7946: 	}
                   7947:     }
                   7948: 
1.847     albertel 7949:     sub get_hosts_from_ip {
                   7950: 	my ($ip) = @_;
                   7951: 	my %iphosts = &get_iphost();
                   7952: 	if (ref($iphosts{$ip})) {
                   7953: 	    return @{$iphosts{$ip}};
                   7954: 	}
                   7955: 	return;
1.839     albertel 7956:     }
1.864     albertel 7957:     
                   7958:     sub reset_hosts_ip_info {
                   7959: 	undef(%iphost);
                   7960: 	undef(%name_to_ip);
                   7961: 	undef(%lonid_to_ip);
                   7962:     }
1.856     albertel 7963: 
                   7964:     sub get_host_ip {
                   7965: 	my ($lonid) = @_;
                   7966: 	if (exists($lonid_to_ip{$lonid})) {
                   7967: 	    return $lonid_to_ip{$lonid};
                   7968: 	}
                   7969: 	my $name=&hostname($lonid);
                   7970:    	my $ip = gethostbyname($name);
                   7971: 	return if (!$ip || length($ip) ne 4);
                   7972: 	$ip=inet_ntoa($ip);
                   7973: 	$name_to_ip{$name}   = $ip;
                   7974: 	$lonid_to_ip{$lonid} = $ip;
                   7975: 	return $ip;
                   7976:     }
1.847     albertel 7977:     
                   7978:     sub get_iphost {
1.869     albertel 7979: 	my ($ignore_cache) = @_;
                   7980: 	if (!$ignore_cache) {
                   7981: 	    if (%iphost) {
                   7982: 		return %iphost;
                   7983: 	    }
                   7984: 	    my ($ip_info,$cached)=
                   7985: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   7986: 	    if ($cached) {
                   7987: 		%iphost      = %{$ip_info->[0]};
                   7988: 		%name_to_ip  = %{$ip_info->[1]};
                   7989: 		%lonid_to_ip = %{$ip_info->[2]};
                   7990: 		return %iphost;
                   7991: 	    }
                   7992: 	}
1.847     albertel 7993: 	my %hostname = &all_hostnames();
                   7994: 	foreach my $id (keys(%hostname)) {
1.864     albertel 7995: 	    my $name=&hostname($id);
1.847     albertel 7996: 	    my $ip;
                   7997: 	    if (!exists($name_to_ip{$name})) {
                   7998: 		$ip = gethostbyname($name);
                   7999: 		if (!$ip || length($ip) ne 4) {
                   8000: 		    &logthis("Skipping host $id name $name no IP found");
                   8001: 		    next;
                   8002: 		}
                   8003: 		$ip=inet_ntoa($ip);
                   8004: 		$name_to_ip{$name} = $ip;
                   8005: 	    } else {
                   8006: 		$ip = $name_to_ip{$name};
1.653     albertel 8007: 	    }
1.856     albertel 8008: 	    $lonid_to_ip{$id} = $ip;
1.847     albertel 8009: 	    push(@{$iphost{$ip}},$id);
1.598     albertel 8010: 	}
1.869     albertel 8011: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8012: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   8013: 				      24*60*60);
                   8014: 
1.847     albertel 8015: 	return %iphost;
1.598     albertel 8016:     }
                   8017: }
                   8018: 
1.862     albertel 8019: BEGIN {
                   8020: 
                   8021: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8022:     unless ($readit) {
                   8023: {
                   8024:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8025:     %perlvar = (%perlvar,%{$configvars});
                   8026: }
                   8027: 
                   8028: 
1.1       albertel 8029: # ------------------------------------------------------ Read spare server file
                   8030: {
1.448     albertel 8031:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8032: 
                   8033:     while (my $configline=<$config>) {
                   8034:        chomp($configline);
1.284     matthew  8035:        if ($configline) {
1.784     albertel 8036: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8037: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8038: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8039:        }
                   8040:     }
1.448     albertel 8041:     close($config);
1.1       albertel 8042: }
1.11      www      8043: # ------------------------------------------------------------ Read permissions
                   8044: {
1.448     albertel 8045:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8046: 
                   8047:     while (my $configline=<$config>) {
1.448     albertel 8048: 	chomp($configline);
                   8049: 	if ($configline) {
                   8050: 	    my ($role,$perm)=split(/ /,$configline);
                   8051: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8052: 	}
1.11      www      8053:     }
1.448     albertel 8054:     close($config);
1.11      www      8055: }
                   8056: 
                   8057: # -------------------------------------------- Read plain texts for permissions
                   8058: {
1.448     albertel 8059:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8060: 
                   8061:     while (my $configline=<$config>) {
1.448     albertel 8062: 	chomp($configline);
                   8063: 	if ($configline) {
1.742     raeburn  8064: 	    my ($short,@plain)=split(/:/,$configline);
                   8065:             %{$prp{$short}} = ();
                   8066: 	    if (@plain > 0) {
                   8067:                 $prp{$short}{'std'} = $plain[0];
                   8068:                 for (my $i=1; $i<@plain; $i++) {
                   8069:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8070:                 }
                   8071:             }
1.448     albertel 8072: 	}
1.135     www      8073:     }
1.448     albertel 8074:     close($config);
1.135     www      8075: }
                   8076: 
                   8077: # ---------------------------------------------------------- Read package table
                   8078: {
1.448     albertel 8079:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8080: 
                   8081:     while (my $configline=<$config>) {
1.483     albertel 8082: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8083: 	chomp($configline);
                   8084: 	my ($short,$plain)=split(/:/,$configline);
                   8085: 	my ($pack,$name)=split(/\&/,$short);
                   8086: 	if ($plain ne '') {
                   8087: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8088: 	    $packagetab{$short}=$plain; 
                   8089: 	}
1.11      www      8090:     }
1.448     albertel 8091:     close($config);
1.329     matthew  8092: }
                   8093: 
                   8094: # ------------- set up temporary directory
                   8095: {
                   8096:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8097: 
1.11      www      8098: }
                   8099: 
1.794     albertel 8100: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8101: 				'compress_threshold'=> 20_000,
                   8102:  			        });
1.185     www      8103: 
1.281     www      8104: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8105: $dumpcount=0;
1.22      www      8106: 
1.163     harris41 8107: &logtouch();
1.672     albertel 8108: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8109: $readit=1;
1.564     albertel 8110:     {
                   8111: 	use integer;
                   8112: 	my $test=(2**32)+1;
1.568     albertel 8113: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8114: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8115:     }
1.195     www      8116: }
1.1       albertel 8117: }
1.179     www      8118: 
1.1       albertel 8119: 1;
1.191     harris41 8120: __END__
                   8121: 
1.243     albertel 8122: =pod
                   8123: 
1.191     harris41 8124: =head1 NAME
                   8125: 
1.243     albertel 8126: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8127: 
                   8128: =head1 SYNOPSIS
                   8129: 
1.243     albertel 8130: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8131: 
                   8132:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8133: 
1.243     albertel 8134: Common parameters:
                   8135: 
                   8136: =over 4
                   8137: 
                   8138: =item *
                   8139: 
                   8140: $uname : an internal username (if $cname expecting a course Id specifically)
                   8141: 
                   8142: =item *
                   8143: 
                   8144: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8145: 
                   8146: =item *
                   8147: 
                   8148: $symb : a resource instance identifier
                   8149: 
                   8150: =item *
                   8151: 
                   8152: $namespace : the name of a .db file that contains the data needed or
                   8153: being set.
                   8154: 
                   8155: =back
                   8156: 
1.394     bowersj2 8157: =head1 OVERVIEW
1.191     harris41 8158: 
1.394     bowersj2 8159: lonnet provides subroutines which interact with the
                   8160: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8161: about classes, users, and resources.
1.243     albertel 8162: 
                   8163: For many of these objects you can also use this to store data about
                   8164: them or modify them in various ways.
1.191     harris41 8165: 
1.394     bowersj2 8166: =head2 Symbs
1.191     harris41 8167: 
1.394     bowersj2 8168: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8169: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8170: map, the resource number of the resource in the map, and the URL of
                   8171: the resource itself. The latter is somewhat redundant, but might help
                   8172: if maps change.
                   8173: 
                   8174: An example is
                   8175: 
                   8176:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8177: 
                   8178: The respective map entry is
                   8179: 
                   8180:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8181:   title="Problem 2">
                   8182:  </resource>
                   8183: 
                   8184: Symbs are used by the random number generator, as well as to store and
                   8185: restore data specific to a certain instance of for example a problem.
                   8186: 
                   8187: =head2 Storing And Retrieving Data
                   8188: 
                   8189: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8190: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8191: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8192: is is the non-critical message twin of cstore. These functions are for
                   8193: handlers to store a perl hash to a user's permanent data space in an
                   8194: easy manner, and to retrieve it again on another call. It is expected
                   8195: that a handler would use this once at the beginning to retrieve data,
                   8196: and then again once at the end to send only the new data back.
                   8197: 
                   8198: The data is stored in the user's data directory on the user's
                   8199: homeserver under the ID of the course.
                   8200: 
                   8201: The hash that is returned by restore will have all of the previous
                   8202: value for all of the elements of the hash.
                   8203: 
                   8204: Example:
                   8205: 
                   8206:  #creating a hash
                   8207:  my %hash;
                   8208:  $hash{'foo'}='bar';
                   8209: 
                   8210:  #storing it
                   8211:  &Apache::lonnet::cstore(\%hash);
                   8212: 
                   8213:  #changing a value
                   8214:  $hash{'foo'}='notbar';
                   8215: 
                   8216:  #adding a new value
                   8217:  $hash{'bar'}='foo';
                   8218:  &Apache::lonnet::cstore(\%hash);
                   8219: 
                   8220:  #retrieving the hash
                   8221:  my %history=&Apache::lonnet::restore();
                   8222: 
                   8223:  #print the hash
                   8224:  foreach my $key (sort(keys(%history))) {
                   8225:    print("\%history{$key} = $history{$key}");
                   8226:  }
                   8227: 
                   8228: Will print out:
1.191     harris41 8229: 
1.394     bowersj2 8230:  %history{1:foo} = bar
                   8231:  %history{1:keys} = foo:timestamp
                   8232:  %history{1:timestamp} = 990455579
                   8233:  %history{2:bar} = foo
                   8234:  %history{2:foo} = notbar
                   8235:  %history{2:keys} = foo:bar:timestamp
                   8236:  %history{2:timestamp} = 990455580
                   8237:  %history{bar} = foo
                   8238:  %history{foo} = notbar
                   8239:  %history{timestamp} = 990455580
                   8240:  %history{version} = 2
                   8241: 
                   8242: Note that the special hash entries C<keys>, C<version> and
                   8243: C<timestamp> were added to the hash. C<version> will be equal to the
                   8244: total number of versions of the data that have been stored. The
                   8245: C<timestamp> attribute will be the UNIX time the hash was
                   8246: stored. C<keys> is available in every historical section to list which
                   8247: keys were added or changed at a specific historical revision of a
                   8248: hash.
                   8249: 
                   8250: B<Warning>: do not store the hash that restore returns directly. This
                   8251: will cause a mess since it will restore the historical keys as if the
                   8252: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8253: 
1.394     bowersj2 8254: Calling convention:
1.191     harris41 8255: 
1.394     bowersj2 8256:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8257:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8258: 
1.394     bowersj2 8259: For more detailed information, see lonnet specific documentation.
1.191     harris41 8260: 
1.394     bowersj2 8261: =head1 RETURN MESSAGES
1.191     harris41 8262: 
1.394     bowersj2 8263: =over 4
1.191     harris41 8264: 
1.394     bowersj2 8265: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8266: 
1.394     bowersj2 8267: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8268: when the connection is brought back up
1.191     harris41 8269: 
1.394     bowersj2 8270: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8271: for later delivery
1.191     harris41 8272: 
1.394     bowersj2 8273: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8274: 
1.394     bowersj2 8275: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8276: that was requested
1.191     harris41 8277: 
1.243     albertel 8278: =back
1.191     harris41 8279: 
1.243     albertel 8280: =head1 PUBLIC SUBROUTINES
1.191     harris41 8281: 
1.243     albertel 8282: =head2 Session Environment Functions
1.191     harris41 8283: 
1.243     albertel 8284: =over 4
1.191     harris41 8285: 
1.394     bowersj2 8286: =item * 
                   8287: X<appenv()>
                   8288: B<appenv(%hash)>: the value of %hash is written to
                   8289: the user envirnoment file, and will be restored for each access this
1.620     albertel 8290: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8291: process
1.191     harris41 8292: 
                   8293: =item *
1.394     bowersj2 8294: X<delenv()>
                   8295: B<delenv($regexp)>: removes all items from the session
                   8296: environment file that matches the regular expression in $regexp. The
1.620     albertel 8297: values are also delted from the current processes %env.
1.191     harris41 8298: 
1.795     albertel 8299: =item * get_env_multiple($name) 
                   8300: 
                   8301: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8302: values may be defined and end up as an array ref.
                   8303: 
                   8304: returns an array of values
                   8305: 
1.243     albertel 8306: =back
                   8307: 
                   8308: =head2 User Information
1.191     harris41 8309: 
1.243     albertel 8310: =over 4
1.191     harris41 8311: 
                   8312: =item *
1.394     bowersj2 8313: X<queryauthenticate()>
                   8314: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8315: authentication scheme
                   8316: 
                   8317: =item *
1.394     bowersj2 8318: X<authenticate()>
                   8319: B<authenticate($uname,$upass,$udom)>: try to
                   8320: authenticate user from domain's lib servers (first use the current
                   8321: one). C<$upass> should be the users password.
1.191     harris41 8322: 
                   8323: =item *
1.394     bowersj2 8324: X<homeserver()>
                   8325: B<homeserver($uname,$udom)>: find the server which has
                   8326: the user's directory and files (there must be only one), this caches
                   8327: the answer, and also caches if there is a borken connection.
1.191     harris41 8328: 
                   8329: =item *
1.394     bowersj2 8330: X<idget()>
                   8331: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8332: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8333: username, and only 1 username per ID in a specific domain) (returns
                   8334: hash: id=>name,id=>name)
1.191     harris41 8335: 
                   8336: =item *
1.394     bowersj2 8337: X<idrget()>
                   8338: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8339: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8340: 
                   8341: =item *
1.394     bowersj2 8342: X<idput()>
                   8343: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8344: 
                   8345: =item *
1.394     bowersj2 8346: X<rolesinit()>
                   8347: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8348: 
                   8349: =item *
1.551     albertel 8350: X<getsection()>
                   8351: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8352: course $cname, return section name/number or '' for "not in course"
                   8353: and '-1' for "no section"
                   8354: 
                   8355: =item *
1.394     bowersj2 8356: X<userenvironment()>
                   8357: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8358: passed in @what from the requested user's environment, returns a hash
                   8359: 
1.858     raeburn  8360: =item * 
                   8361: X<userlog_query()>
1.859     albertel 8362: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8363: activity.log file. %filters defines filters applied when parsing the
                   8364: log file. These can be start or end timestamps, or the type of action
                   8365: - log to look for Login or Logout events, check for Checkin or
                   8366: Checkout, role for role selection. The response is in the form
                   8367: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8368: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8369: 
1.243     albertel 8370: =back
                   8371: 
                   8372: =head2 User Roles
                   8373: 
                   8374: =over 4
                   8375: 
                   8376: =item *
                   8377: 
1.810     raeburn  8378: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8379:  F: full access
                   8380:  U,I,K: authentication modes (cxx only)
                   8381:  '': forbidden
                   8382:  1: user needs to choose course
                   8383:  2: browse allowed
1.766     albertel 8384:  A: passphrase authentication needed
1.243     albertel 8385: 
                   8386: =item *
                   8387: 
                   8388: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8389: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8390: and course level
                   8391: 
                   8392: =item *
                   8393: 
                   8394: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8395: explanation of a user role term
                   8396: 
1.832     raeburn  8397: =item *
                   8398: 
1.858     raeburn  8399: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8400: All arguments are optional. Returns a hash of a roles, either for
                   8401: co-author/assistant author roles for a user's Construction Space
                   8402: (default), or if $context is 'user', roles for the user himself,
                   8403: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8404: and value is set to colon-separated start and end times for the role.
                   8405: If no username and domain are specified, will default to current
                   8406: user/domain. Types, roles, and roledoms are references to arrays,
                   8407: of role statuses (active, future or previous), roles 
                   8408: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8409: to restrict the list of roles reported. If no array ref is 
                   8410: provided for types, will default to return only active roles.
1.834     albertel 8411: 
1.243     albertel 8412: =back
                   8413: 
                   8414: =head2 User Modification
                   8415: 
                   8416: =over 4
                   8417: 
                   8418: =item *
                   8419: 
                   8420: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8421: user for the level given by URL.  Optional start and end dates (leave empty
                   8422: string or zero for "no date")
1.191     harris41 8423: 
                   8424: =item *
                   8425: 
1.243     albertel 8426: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8427: change a users, password, possible return values are: ok,
                   8428: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8429: refused
1.191     harris41 8430: 
                   8431: =item *
                   8432: 
1.243     albertel 8433: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8434: 
                   8435: =item *
                   8436: 
1.243     albertel 8437: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8438: modify user
1.191     harris41 8439: 
                   8440: =item *
                   8441: 
1.286     matthew  8442: modifystudent
                   8443: 
                   8444: modify a students enrollment and identification information.
                   8445: The course id is resolved based on the current users environment.  
                   8446: This means the envoking user must be a course coordinator or otherwise
                   8447: associated with a course.
                   8448: 
1.297     matthew  8449: This call is essentially a wrapper for lonnet::modifyuser and
                   8450: lonnet::modify_student_enrollment
1.286     matthew  8451: 
                   8452: Inputs: 
                   8453: 
                   8454: =over 4
                   8455: 
                   8456: =item B<$udom> Students loncapa domain
                   8457: 
                   8458: =item B<$uname> Students loncapa login name
                   8459: 
                   8460: =item B<$uid> Students id/student number
                   8461: 
                   8462: =item B<$umode> Students authentication mode
                   8463: 
                   8464: =item B<$upass> Students password
                   8465: 
                   8466: =item B<$first> Students first name
                   8467: 
                   8468: =item B<$middle> Students middle name
                   8469: 
                   8470: =item B<$last> Students last name
                   8471: 
                   8472: =item B<$gene> Students generation
                   8473: 
                   8474: =item B<$usec> Students section in course
                   8475: 
                   8476: =item B<$end> Unix time of the roles expiration
                   8477: 
                   8478: =item B<$start> Unix time of the roles start date
                   8479: 
                   8480: =item B<$forceid> If defined, allow $uid to be changed
                   8481: 
                   8482: =item B<$desiredhome> server to use as home server for student
                   8483: 
                   8484: =back
1.297     matthew  8485: 
                   8486: =item *
                   8487: 
                   8488: modify_student_enrollment
                   8489: 
                   8490: Change a students enrollment status in a class.  The environment variable
                   8491: 'role.request.course' must be defined for this function to proceed.
                   8492: 
                   8493: Inputs:
                   8494: 
                   8495: =over 4
                   8496: 
                   8497: =item $udom, students domain
                   8498: 
                   8499: =item $uname, students name
                   8500: 
                   8501: =item $uid, students user id
                   8502: 
                   8503: =item $first, students first name
                   8504: 
                   8505: =item $middle
                   8506: 
                   8507: =item $last
                   8508: 
                   8509: =item $gene
                   8510: 
                   8511: =item $usec
                   8512: 
                   8513: =item $end
                   8514: 
                   8515: =item $start
                   8516: 
                   8517: =back
                   8518: 
1.191     harris41 8519: 
                   8520: =item *
                   8521: 
1.243     albertel 8522: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8523: custom role; give a custom role to a user for the level given by URL.  Specify
                   8524: name and domain of role author, and role name
1.191     harris41 8525: 
                   8526: =item *
                   8527: 
1.243     albertel 8528: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8529: 
                   8530: =item *
                   8531: 
1.243     albertel 8532: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8533: 
                   8534: =back
                   8535: 
                   8536: =head2 Course Infomation
                   8537: 
                   8538: =over 4
1.191     harris41 8539: 
                   8540: =item *
                   8541: 
1.631     albertel 8542: coursedescription($courseid) : returns a hash of information about the
                   8543: specified course id, including all environment settings for the
                   8544: course, the description of the course will be in the hash under the
                   8545: key 'description'
1.191     harris41 8546: 
                   8547: =item *
                   8548: 
1.624     albertel 8549: resdata($name,$domain,$type,@which) : request for current parameter
                   8550: setting for a specific $type, where $type is either 'course' or 'user',
                   8551: @what should be a list of parameters to ask about. This routine caches
                   8552: answers for 5 minutes.
1.243     albertel 8553: 
1.877     foxr     8554: =item *
                   8555: 
                   8556: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8557: data base, returning a hash that is keyed by the resource name and has
                   8558: values that are the resource value.  I believe that the timestamps and
                   8559: versions are also returned.
                   8560: 
                   8561: 
1.243     albertel 8562: =back
                   8563: 
                   8564: =head2 Course Modification
                   8565: 
                   8566: =over 4
1.191     harris41 8567: 
                   8568: =item *
                   8569: 
1.243     albertel 8570: writecoursepref($courseid,%prefs) : write preferences (environment
                   8571: database) for a course
1.191     harris41 8572: 
                   8573: =item *
                   8574: 
1.243     albertel 8575: createcourse($udom,$description,$url) : make/modify course
                   8576: 
                   8577: =back
                   8578: 
                   8579: =head2 Resource Subroutines
                   8580: 
                   8581: =over 4
1.191     harris41 8582: 
                   8583: =item *
                   8584: 
1.243     albertel 8585: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8586: 
                   8587: =item *
                   8588: 
1.243     albertel 8589: repcopy($filename) : subscribes to the requested file, and attempts to
                   8590: replicate from the owning library server, Might return
1.607     raeburn  8591: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8592: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8593: resource. Expects the local filesystem pathname
                   8594: (/home/httpd/html/res/....)
                   8595: 
                   8596: =back
                   8597: 
                   8598: =head2 Resource Information
                   8599: 
                   8600: =over 4
1.191     harris41 8601: 
                   8602: =item *
                   8603: 
1.243     albertel 8604: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8605: a vairety of different possible values, $varname should be a request
                   8606: string, and the other parameters can be used to specify who and what
                   8607: one is asking about.
                   8608: 
                   8609: Possible values for $varname are environment.lastname (or other item
                   8610: from the envirnment hash), user.name (or someother aspect about the
                   8611: user), resource.0.maxtries (or some other part and parameter of a
                   8612: resource)
1.204     albertel 8613: 
                   8614: =item *
                   8615: 
1.243     albertel 8616: directcondval($number) : get current value of a condition; reads from a state
                   8617: string
1.204     albertel 8618: 
                   8619: =item *
                   8620: 
1.243     albertel 8621: condval($condidx) : value of condition index based on state
1.204     albertel 8622: 
                   8623: =item *
                   8624: 
1.243     albertel 8625: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8626: resource's metadata, $what should be either a specific key, or either
                   8627: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8628: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8629: 
                   8630: this function automatically caches all requests
1.191     harris41 8631: 
                   8632: =item *
                   8633: 
1.243     albertel 8634: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8635: network of library servers; returns file handle of where SQL and regex results
                   8636: will be stored for query
1.191     harris41 8637: 
                   8638: =item *
                   8639: 
1.243     albertel 8640: symbread($filename) : return symbolic list entry (filename argument optional);
                   8641: returns the data handle
1.191     harris41 8642: 
                   8643: =item *
                   8644: 
1.243     albertel 8645: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8646: a possible symb for the URL in $thisfn, and if is an encryypted
                   8647: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8648: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8649: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8650: 
1.191     harris41 8651: 
                   8652: =item *
                   8653: 
1.243     albertel 8654: symbclean($symb) : removes versions numbers from a symb, returns the
                   8655: cleaned symb
1.191     harris41 8656: 
                   8657: =item *
                   8658: 
1.243     albertel 8659: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8660: course map, user must be in a course for it to work.
1.191     harris41 8661: 
                   8662: =item *
                   8663: 
1.243     albertel 8664: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8665: 
                   8666: =item *
                   8667: 
1.243     albertel 8668: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8669: a random seed, all arguments are optional, if they aren't sent it uses the
                   8670: environment to derive them. Note: if symb isn't sent and it can't get one
                   8671: from &symbread it will use the current time as its return value
1.191     harris41 8672: 
                   8673: =item *
                   8674: 
1.243     albertel 8675: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8676: unfakeable, receipt
1.191     harris41 8677: 
                   8678: =item *
                   8679: 
1.620     albertel 8680: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8681: 
                   8682: =item *
                   8683: 
1.243     albertel 8684: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8685: 
                   8686: =item *
                   8687: 
1.243     albertel 8688: 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 8689: 
                   8690: =item *
                   8691: 
1.243     albertel 8692: 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 8693: 
                   8694: =item *
                   8695: 
1.243     albertel 8696: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8697: 
                   8698: =item *
                   8699: 
1.243     albertel 8700: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8701: forcing spreadsheet to reevaluate the resource scores next time.
                   8702: 
                   8703: =back
                   8704: 
                   8705: =head2 Storing/Retreiving Data
                   8706: 
                   8707: =over 4
1.191     harris41 8708: 
                   8709: =item *
                   8710: 
1.243     albertel 8711: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8712: for this url; hashref needs to be given and should be a \%hashname; the
                   8713: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8714: be derived from the env
1.191     harris41 8715: 
                   8716: =item *
                   8717: 
1.243     albertel 8718: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8719: uses critical subroutine
1.191     harris41 8720: 
                   8721: =item *
                   8722: 
1.243     albertel 8723: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8724: all args are optional
1.191     harris41 8725: 
                   8726: =item *
                   8727: 
1.717     albertel 8728: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8729: dumps the complete (or key matching regexp) namespace into a hash
                   8730: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8731: normally &store()ed into
                   8732: 
                   8733: $range should be either an integer '100' (give me the first 100
                   8734:                                            matching records)
                   8735:               or be  two integers sperated by a - with no spaces
                   8736:                  '30-50' (give me the 30th through the 50th matching
                   8737:                           records)
                   8738: 
                   8739: 
                   8740: =item *
                   8741: 
                   8742: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8743: replaces a &store() version of data with a replacement set of data
                   8744: for a particular resource in a namespace passed in the $storehash hash 
                   8745: reference
                   8746: 
                   8747: =item *
                   8748: 
1.243     albertel 8749: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8750: works very similar to store/cstore, but all data is stored in a
                   8751: temporary location and can be reset using tmpreset, $storehash should
                   8752: be a hash reference, returns nothing on success
1.191     harris41 8753: 
                   8754: =item *
                   8755: 
1.243     albertel 8756: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8757: similar to restore, but all data is stored in a temporary location and
                   8758: can be reset using tmpreset. Returns a hash of values on success,
                   8759: error string otherwise.
1.191     harris41 8760: 
                   8761: =item *
                   8762: 
1.243     albertel 8763: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8764: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8765: 
                   8766: =item *
                   8767: 
1.243     albertel 8768: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8769: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8770: 
                   8771: =item *
                   8772: 
1.243     albertel 8773: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8774: namesp ($udom and $uname are optional)
1.191     harris41 8775: 
                   8776: =item *
                   8777: 
1.702     albertel 8778: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8779: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8780: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8781: 
1.702     albertel 8782: $range should be either an integer '100' (give me the first 100
                   8783:                                            matching records)
                   8784:               or be  two integers sperated by a - with no spaces
                   8785:                  '30-50' (give me the 30th through the 50th matching
                   8786:                           records)
1.449     matthew  8787: =item *
                   8788: 
                   8789: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8790: $store can be a scalar, an array reference, or if the amount to be 
                   8791: incremented is > 1, a hash reference.
                   8792: 
                   8793: ($udom and $uname are optional)
1.191     harris41 8794: 
                   8795: =item *
                   8796: 
1.243     albertel 8797: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8798: ($udom and $uname are optional)
1.191     harris41 8799: 
                   8800: =item *
                   8801: 
1.243     albertel 8802: cput($namespace,$storehash,$udom,$uname) : critical put
                   8803: ($udom and $uname are optional)
1.191     harris41 8804: 
                   8805: =item *
                   8806: 
1.748     albertel 8807: newput($namespace,$storehash,$udom,$uname) :
                   8808: 
                   8809: Attempts to store the items in the $storehash, but only if they don't
                   8810: currently exist, if this succeeds you can be certain that you have 
                   8811: successfully created a new key value pair in the $namespace db.
                   8812: 
                   8813: 
                   8814: Args:
                   8815:  $namespace: name of database to store values to
                   8816:  $storehash: hashref to store to the db
                   8817:  $udom: (optional) domain of user containing the db
                   8818:  $uname: (optional) name of user caontaining the db
                   8819: 
                   8820: Returns:
                   8821:  'ok' -> succeeded in storing all keys of $storehash
                   8822:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8823:                         least <key> already existed in the db (other
                   8824:                         requested keys may also already exist)
                   8825:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8826:  'con_lost' -> unable to contact request server
                   8827:  'refused' -> action was not allowed by remote machine
                   8828: 
                   8829: 
                   8830: =item *
                   8831: 
1.243     albertel 8832: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8833: reference filled in from namesp (encrypts the return communication)
                   8834: ($udom and $uname are optional)
1.191     harris41 8835: 
                   8836: =item *
                   8837: 
1.243     albertel 8838: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8839: critical subroutine
                   8840: 
1.806     raeburn  8841: =item *
                   8842: 
1.860     raeburn  8843: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   8844: array reference filled in from namespace found in domain level on either
                   8845: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  8846: 
                   8847: =item *
                   8848: 
1.860     raeburn  8849: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   8850: domain level either on specified domain server ($uhome) or primary domain 
                   8851: server ($udom and $uhome are optional)
1.806     raeburn  8852: 
1.243     albertel 8853: =back
                   8854: 
                   8855: =head2 Network Status Functions
                   8856: 
                   8857: =over 4
1.191     harris41 8858: 
                   8859: =item *
                   8860: 
                   8861: dirlist($uri) : return directory list based on URI
                   8862: 
                   8863: =item *
                   8864: 
1.243     albertel 8865: spareserver() : find server with least workload from spare.tab
                   8866: 
                   8867: =back
                   8868: 
                   8869: =head2 Apache Request
                   8870: 
                   8871: =over 4
1.191     harris41 8872: 
                   8873: =item *
                   8874: 
1.243     albertel 8875: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8876: localhost, posts hash
                   8877: 
                   8878: =back
                   8879: 
                   8880: =head2 Data to String to Data
                   8881: 
                   8882: =over 4
1.191     harris41 8883: 
                   8884: =item *
                   8885: 
1.243     albertel 8886: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8887: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8888: 
                   8889: =item *
                   8890: 
1.243     albertel 8891: hashref2str($hashref) : convert a hashref into a string complete with
                   8892: escaping and '=' and '&' separators, supports elements that are
                   8893: arrayrefs and hashrefs
1.191     harris41 8894: 
                   8895: =item *
                   8896: 
1.243     albertel 8897: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8898: with escaping and '&' separators, supports elements that are arrayrefs
                   8899: and hashrefs
1.191     harris41 8900: 
                   8901: =item *
                   8902: 
1.243     albertel 8903: str2hash($string) : convert string to hash using unescaping and
                   8904: splitting on '=' and '&', supports elements that are arrayrefs and
                   8905: hashrefs
1.191     harris41 8906: 
                   8907: =item *
                   8908: 
1.243     albertel 8909: str2array($string) : convert string to hash using unescaping and
                   8910: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8911: 
                   8912: =back
                   8913: 
                   8914: =head2 Logging Routines
                   8915: 
                   8916: =over 4
                   8917: 
                   8918: These routines allow one to make log messages in the lonnet.log and
                   8919: lonnet.perm logfiles.
1.191     harris41 8920: 
                   8921: =item *
                   8922: 
1.243     albertel 8923: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8924: 
                   8925: =item *
                   8926: 
1.243     albertel 8927: logthis() : append message to the normal lonnet.log file, it gets
                   8928: preiodically rolled over and deleted.
1.191     harris41 8929: 
                   8930: =item *
                   8931: 
1.243     albertel 8932: logperm() : append a permanent message to lonnet.perm.log, this log
                   8933: file never gets deleted by any automated portion of the system, only
                   8934: messages of critical importance should go in here.
                   8935: 
                   8936: =back
                   8937: 
                   8938: =head2 General File Helper Routines
                   8939: 
                   8940: =over 4
1.191     harris41 8941: 
                   8942: =item *
                   8943: 
1.481     raeburn  8944: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8945: (a) files in /uploaded
                   8946:   (i) If a local copy of the file exists - 
                   8947:       compares modification date of local copy with last-modified date for 
                   8948:       definitive version stored on home server for course. If local copy is 
                   8949:       stale, requests a new version from the home server and stores it. 
                   8950:       If the original has been removed from the home server, then local copy 
                   8951:       is unlinked.
                   8952:   (ii) If local copy does not exist -
                   8953:       requests the file from the home server and stores it. 
                   8954:   
                   8955:   If $caller is 'uploadrep':  
                   8956:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8957:     for request for files originally uploaded via DOCS. 
                   8958:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8959:   
                   8960:   Otherwise:
                   8961:      This indicates a call from the content generation phase of the request.
                   8962:      -  returns the entire contents of the file or -1.
                   8963:      
                   8964: (b) files in /res
                   8965:    - returns the entire contents of a file or -1; 
                   8966:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8967: 
1.712     albertel 8968: 
                   8969: =item *
                   8970: 
                   8971: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8972:                   reference
                   8973: 
                   8974: returns either a stat() list of data about the file or an empty list
                   8975: if the file doesn't exist or couldn't find out about it (connection
                   8976: problems or user unknown)
                   8977: 
1.191     harris41 8978: =item *
                   8979: 
1.243     albertel 8980: filelocation($dir,$file) : returns file system location of a file
                   8981: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8982: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8983: and a file of ../bob will become /a/bob)
1.191     harris41 8984: 
                   8985: =item *
                   8986: 
                   8987: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8988: filelocation except for hrefs
                   8989: 
                   8990: =item *
                   8991: 
                   8992: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8993: 
1.243     albertel 8994: =back
                   8995: 
1.608     albertel 8996: =head2 Usererfile file routines (/uploaded*)
                   8997: 
                   8998: =over 4
                   8999: 
                   9000: =item *
                   9001: 
                   9002: userfileupload(): main rotine for putting a file in a user or course's
                   9003:                   filespace, arguments are,
                   9004: 
1.620     albertel 9005:  formname - required - this is the name of the element in $env where the
1.608     albertel 9006:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9007:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9008:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9009:  coursedoc - if true, store the file in the course of the active role
                   9010:              of the current user
                   9011:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9012:          if undefined, it will be placed in "unknown"
                   9013: 
                   9014:  (This routine calls clean_filename() to remove any dangerous
                   9015:  characters from the filename, and then calls finuserfileupload() to
                   9016:  complete the transaction)
                   9017: 
                   9018:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9019:  and /adm/notfound.html if unsuccessful
                   9020: 
                   9021: =item *
                   9022: 
                   9023: clean_filename(): routine for cleaing a filename up for storage in
                   9024:                  userfile space, argument is:
                   9025: 
                   9026:  filename - proposed filename
                   9027: 
                   9028: returns: the new clean filename
                   9029: 
                   9030: =item *
                   9031: 
                   9032: finishuserfileupload(): routine that creaes and sends the file to
                   9033: userspace, probably shouldn't be called directly
                   9034: 
                   9035:   docuname: username or courseid of destination for the file
                   9036:   docudom: domain of user/course of destination for the file
                   9037:   formname: same as for userfileupload()
                   9038:   fname: filename (inculding subdirectories) for the file
                   9039: 
                   9040:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9041:  and /adm/notfound.html if unsuccessful
                   9042: 
                   9043: =item *
                   9044: 
                   9045: renameuserfile(): renames an existing userfile to a new name
                   9046: 
                   9047:   Args:
                   9048:    docuname: username or courseid of destination for the file
                   9049:    docudom: domain of user/course of destination for the file
                   9050:    old: current file name (including any subdirs under userfiles)
                   9051:    new: desired file name (including any subdirs under userfiles)
                   9052: 
                   9053: =item *
                   9054: 
                   9055: mkdiruserfile(): creates a directory is a userfiles dir
                   9056: 
                   9057:   Args:
                   9058:    docuname: username or courseid of destination for the file
                   9059:    docudom: domain of user/course of destination for the file
                   9060:    dir: dir to create (including any subdirs under userfiles)
                   9061: 
                   9062: =item *
                   9063: 
                   9064: removeuserfile(): removes a file that exists in userfiles
                   9065: 
                   9066:   Args:
                   9067:    docuname: username or courseid of destination for the file
                   9068:    docudom: domain of user/course of destination for the file
                   9069:    fname: filname to delete (including any subdirs under userfiles)
                   9070: 
                   9071: =item *
                   9072: 
                   9073: removeuploadedurl(): convience function for removeuserfile()
                   9074: 
                   9075:   Args:
                   9076:    url:  a full /uploaded/... url to delete
                   9077: 
1.747     albertel 9078: =item * 
                   9079: 
                   9080: get_portfile_permissions():
                   9081:   Args:
                   9082:     domain: domain of user or course contain the portfolio files
                   9083:     user: name of user or num of course contain the portfolio files
                   9084:   Returns:
                   9085:     hashref of a dump of the proper file_permissions.db
                   9086:    
                   9087: 
                   9088: =item * 
                   9089: 
                   9090: get_access_controls():
                   9091: 
                   9092: Args:
                   9093:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9094:   group: (optional) the group you want the files associated with
                   9095:   file: (optional) the file you want access info on
                   9096: 
                   9097: Returns:
1.749     raeburn  9098:     a hash (keys are file names) of hashes containing
                   9099:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9100:         values are XML containing access control settings (see below) 
1.747     albertel 9101: 
                   9102: Internal notes:
                   9103: 
1.749     raeburn  9104:  access controls are stored in file_permissions.db as key=value pairs.
                   9105:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9106:         where scope -> public,guest,course,group,domains or users.
                   9107:               end -> UNIX time for end of access (0 -> no end date)
                   9108:               start -> UNIX time for start of access
                   9109: 
                   9110:     value -> XML description of access control
                   9111:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9112:             <start></start>
                   9113:             <end></end>
                   9114: 
                   9115:             <password></password>  for scope type = guest
                   9116: 
                   9117:             <domain></domain>     for scope type = course or group
                   9118:             <number></number>
                   9119:             <roles id="">
                   9120:              <role></role>
                   9121:              <access></access>
                   9122:              <section></section>
                   9123:              <group></group>
                   9124:             </roles>
                   9125: 
                   9126:             <dom></dom>         for scope type = domains
                   9127: 
                   9128:             <users>             for scope type = users
                   9129:              <user>
                   9130:               <uname></uname>
                   9131:               <udom></udom>
                   9132:              </user>
                   9133:             </users>
                   9134:            </scope> 
                   9135:               
                   9136:  Access data is also aggregated for each file in an additional key=value pair:
                   9137:  key -> path to file/file_name\0accesscontrol 
                   9138:  value -> reference to hash
                   9139:           hash contains key = value pairs
                   9140:           where key = uniqueID:scope_end_start
                   9141:                 value = UNIX time record was last updated
                   9142: 
                   9143:           Used to improve speed of look-ups of access controls for each file.  
                   9144:  
                   9145:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9146: 
                   9147: modify_access_controls():
                   9148: 
                   9149: Modifies access controls for a portfolio file
                   9150: Args
                   9151: 1. file name
                   9152: 2. reference to hash of required changes,
                   9153: 3. domain
                   9154: 4. username
                   9155:   where domain,username are the domain of the portfolio owner 
                   9156:   (either a user or a course) 
                   9157: 
                   9158: Returns:
                   9159: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9160: 2. result of deletions ('ok' or 'error', with error message).
                   9161: 3. reference to hash of any new or updated access controls.
                   9162: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9163:    key = integer (inbound ID)
                   9164:    value = uniqueID  
1.747     albertel 9165: 
1.608     albertel 9166: =back
                   9167: 
1.243     albertel 9168: =head2 HTTP Helper Routines
                   9169: 
                   9170: =over 4
                   9171: 
1.191     harris41 9172: =item *
                   9173: 
                   9174: escape() : unpack non-word characters into CGI-compatible hex codes
                   9175: 
                   9176: =item *
                   9177: 
                   9178: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9179: 
1.243     albertel 9180: =back
                   9181: 
                   9182: =head1 PRIVATE SUBROUTINES
                   9183: 
                   9184: =head2 Underlying communication routines (Shouldn't call)
                   9185: 
                   9186: =over 4
                   9187: 
                   9188: =item *
                   9189: 
                   9190: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9191: 
                   9192: =item *
                   9193: 
                   9194: reply() : uses subreply to send a message to remote machine, logs all failures
                   9195: 
                   9196: =item *
                   9197: 
                   9198: critical() : passes a critical message to another server; if cannot
                   9199: get through then place message in connection buffer directory and
                   9200: returns con_delayed, if incapable of saving message, returns
                   9201: con_failed
                   9202: 
                   9203: =item *
                   9204: 
                   9205: reconlonc() : tries to reconnect lonc client processes.
                   9206: 
                   9207: =back
                   9208: 
                   9209: =head2 Resource Access Logging
                   9210: 
                   9211: =over 4
                   9212: 
                   9213: =item *
                   9214: 
                   9215: flushcourselogs() : flush (save) buffer logs and access logs
                   9216: 
                   9217: =item *
                   9218: 
                   9219: courselog($what) : save message for course in hash
                   9220: 
                   9221: =item *
                   9222: 
                   9223: courseacclog($what) : save message for course using &courselog().  Perform
                   9224: special processing for specific resource types (problems, exams, quizzes, etc).
                   9225: 
1.191     harris41 9226: =item *
                   9227: 
                   9228: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9229: as a PerlChildExitHandler
1.243     albertel 9230: 
                   9231: =back
                   9232: 
                   9233: =head2 Other
                   9234: 
                   9235: =over 4
                   9236: 
                   9237: =item *
                   9238: 
                   9239: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9240: 
                   9241: =back
                   9242: 
                   9243: =cut
1.877     foxr     9244: 

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