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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.885   ! albertel    4: # $Id: lonnet.pm,v 1.884 2007/06/07 18:08:39 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.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.885   ! albertel 6341: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 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.883     albertel 6558: 	$extension = lc($extension);
                   6559: 	if ($extension eq 'htm') { $extension='html'; }
                   6560: 
1.737     albertel 6561: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6562: 	    #no specific packages #how's our extension
                   6563: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6564: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6565: 					 \%metathesekeys);
                   6566: 	}
1.883     albertel 6567: 
                   6568: 	if (!exists($metaentry{':packages'})
                   6569: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6570: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6571: 		#no specific packages well let's get default then
                   6572: 		if ($key!~/^default&/) { next; }
1.488     albertel 6573: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6574: 					     \%metathesekeys);
                   6575: 	    }
                   6576: 	}
1.338     www      6577: # are there custom rights to evaluate
1.599     albertel 6578: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6579: 
1.338     www      6580:     #
                   6581:     # Importing a rights file here
1.339     albertel 6582:     #
                   6583: 	    unless ($depthcount) {
1.599     albertel 6584: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6585: 		my $dir=$filename;
                   6586: 		$dir=~s|[^/]*$||;
                   6587: 		$location=&filelocation($dir,$location);
1.736     albertel 6588: 		my $rights_metadata =
                   6589: 		    &metadata($uri,'keys',$location,'_rights',
                   6590: 			      $depthcount+1);
                   6591: 		foreach my $rights (split(',',$rights_metadata)) {
                   6592: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6593: 		    $metathesekeys{$rights}=1;
1.339     albertel 6594: 		}
                   6595: 	    }
                   6596: 	}
1.737     albertel 6597: 	# uniqifiy package listing
                   6598: 	my %seen;
                   6599: 	my @uniq_packages =
                   6600: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6601: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6602: 
                   6603: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6604: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6605: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6606: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6607: # this is the end of "was not already recently cached
1.71      www      6608:     }
1.599     albertel 6609:     return $metaentry{':'.$what};
1.261     albertel 6610: }
                   6611: 
1.488     albertel 6612: sub metadata_create_package_def {
1.483     albertel 6613:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6614:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6615:     if ($subp eq 'default') { next; }
                   6616:     
1.599     albertel 6617:     if (defined($metaentry{':packages'})) {
                   6618: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6619:     } else {
1.599     albertel 6620: 	$metaentry{':packages'}=$package;
1.483     albertel 6621:     }
                   6622:     my $value=$packagetab{$key};
                   6623:     my $unikey;
                   6624:     $unikey='parameter_0_'.$name;
1.599     albertel 6625:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6626:     $$metathesekeys{$unikey}=1;
1.599     albertel 6627:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6628: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6629:     }
1.599     albertel 6630:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6631: 	$metaentry{':'.$unikey}=
                   6632: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6633:     }
                   6634: }
                   6635: 
1.261     albertel 6636: sub metadata_generate_part0 {
                   6637:     my ($metadata,$metacache,$uri) = @_;
                   6638:     my %allnames;
1.737     albertel 6639:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6640: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6641: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6642: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6643: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6644: 	    $allnames{$name}=$part;
                   6645: 	  }
                   6646: 	}
                   6647:     }
                   6648:     foreach my $name (keys(%allnames)) {
                   6649:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6650:       my $key=":parameter_0_$name";
1.261     albertel 6651:       $$metacache{"$key.part"}='0';
                   6652:       $$metacache{"$key.name"}=$name;
1.428     albertel 6653:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6654: 					   $allnames{$name}.'_'.$name.
                   6655: 					   '.type'};
1.428     albertel 6656:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6657: 			     '.display'};
1.644     www      6658:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6659:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6660:       $$metacache{"$key.display"}=$olddis;
                   6661:     }
1.71      www      6662: }
                   6663: 
1.764     albertel 6664: # ------------------------------------------------------ Devalidate title cache
                   6665: 
                   6666: sub devalidate_title_cache {
                   6667:     my ($url)=@_;
                   6668:     if (!$env{'request.course.id'}) { return; }
                   6669:     my $symb=&symbread($url);
                   6670:     if (!$symb) { return; }
                   6671:     my $key=$env{'request.course.id'}."\0".$symb;
                   6672:     &devalidate_cache_new('title',$key);
                   6673: }
                   6674: 
1.301     www      6675: # ------------------------------------------------- Get the title of a resource
                   6676: 
                   6677: sub gettitle {
                   6678:     my $urlsymb=shift;
                   6679:     my $symb=&symbread($urlsymb);
1.534     albertel 6680:     if ($symb) {
1.620     albertel 6681: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6682: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6683: 	if (defined($cached)) { 
                   6684: 	    return $result;
                   6685: 	}
1.534     albertel 6686: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6687: 	my $title='';
                   6688: 	my %bighash;
1.620     albertel 6689: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6690: 		&GDBM_READER(),0640)) {
                   6691: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6692: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6693: 	    untie %bighash;
                   6694: 	}
                   6695: 	$title=~s/\&colon\;/\:/gs;
                   6696: 	if ($title) {
1.599     albertel 6697: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6698: 	}
                   6699: 	$urlsymb=$url;
                   6700:     }
                   6701:     my $title=&metadata($urlsymb,'title');
                   6702:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6703:     return $title;
1.301     www      6704: }
1.613     albertel 6705: 
1.614     albertel 6706: sub get_slot {
                   6707:     my ($which,$cnum,$cdom)=@_;
                   6708:     if (!$cnum || !$cdom) {
1.790     albertel 6709: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6710: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6711: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6712:     }
1.703     albertel 6713:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6714:     my %slotinfo;
                   6715:     if (exists($remembered{$key})) {
                   6716: 	$slotinfo{$which} = $remembered{$key};
                   6717:     } else {
                   6718: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6719: 	&Apache::lonhomework::showhash(%slotinfo);
                   6720: 	my ($tmp)=keys(%slotinfo);
                   6721: 	if ($tmp=~/^error:/) { return (); }
                   6722: 	$remembered{$key} = $slotinfo{$which};
                   6723:     }
1.616     albertel 6724:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6725: 	return %{$slotinfo{$which}};
                   6726:     }
                   6727:     return $slotinfo{$which};
1.614     albertel 6728: }
1.31      www      6729: # ------------------------------------------------- Update symbolic store links
                   6730: 
                   6731: sub symblist {
                   6732:     my ($mapname,%newhash)=@_;
1.438     www      6733:     $mapname=&deversion(&declutter($mapname));
1.31      www      6734:     my %hash;
1.620     albertel 6735:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6736:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6737:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6738: 	    foreach my $url (keys %newhash) {
                   6739: 		next if ($url eq 'last_known'
                   6740: 			 && $env{'form.no_update_last_known'});
                   6741: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6742: 						    $newhash{$url}->[1],
                   6743: 						    $newhash{$url}->[0]);
1.191     harris41 6744:             }
1.31      www      6745:             if (untie(%hash)) {
                   6746: 		return 'ok';
                   6747:             }
                   6748:         }
                   6749:     }
                   6750:     return 'error';
1.212     www      6751: }
                   6752: 
                   6753: # --------------------------------------------------------------- Verify a symb
                   6754: 
                   6755: sub symbverify {
1.510     www      6756:     my ($symb,$thisurl)=@_;
                   6757:     my $thisfn=$thisurl;
1.439     www      6758:     $thisfn=&declutter($thisfn);
1.215     www      6759: # direct jump to resource in page or to a sequence - will construct own symbs
                   6760:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6761: # check URL part
1.409     www      6762:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6763: 
1.431     www      6764:     unless ($url eq $thisfn) { return 0; }
1.213     www      6765: 
1.216     www      6766:     $symb=&symbclean($symb);
1.510     www      6767:     $thisurl=&deversion($thisurl);
1.439     www      6768:     $thisfn=&deversion($thisfn);
1.213     www      6769: 
                   6770:     my %bighash;
                   6771:     my $okay=0;
1.431     www      6772: 
1.620     albertel 6773:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6774:                             &GDBM_READER(),0640)) {
1.510     www      6775:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6776:         unless ($ids) { 
1.510     www      6777:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6778:         }
                   6779:         if ($ids) {
                   6780: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6781: 	    foreach my $id (split(/\,/,$ids)) {
                   6782: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6783:                if (
                   6784:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6785:    eq $symb) { 
1.620     albertel 6786: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6787: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6788: 		       $okay=1; 
                   6789: 		   }
                   6790: 	       }
1.216     www      6791: 	   }
                   6792:         }
1.213     www      6793: 	untie(%bighash);
                   6794:     }
                   6795:     return $okay;
1.31      www      6796: }
                   6797: 
1.210     www      6798: # --------------------------------------------------------------- Clean-up symb
                   6799: 
                   6800: sub symbclean {
                   6801:     my $symb=shift;
1.568     albertel 6802:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6803: # remove version from map
                   6804:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6805: 
1.210     www      6806: # remove version from URL
                   6807:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6808: 
1.507     www      6809: # remove wrapper
                   6810: 
1.510     www      6811:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6812:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6813:     return $symb;
1.409     www      6814: }
                   6815: 
                   6816: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6817: 
                   6818: sub encode_symb {
                   6819:     my ($map,$resid,$url)=@_;
                   6820:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6821: }
1.409     www      6822: 
                   6823: sub decode_symb {
1.568     albertel 6824:     my $symb=shift;
                   6825:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6826:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6827:     return (&fixversion($map),$resid,&fixversion($url));
                   6828: }
                   6829: 
                   6830: sub fixversion {
                   6831:     my $fn=shift;
1.609     banghart 6832:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6833:     my %bighash;
                   6834:     my $uri=&clutter($fn);
1.620     albertel 6835:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6836: # is this cached?
1.599     albertel 6837:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6838:     if (defined($cached)) { return $result; }
                   6839: # unfortunately not cached, or expired
1.620     albertel 6840:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6841: 	    &GDBM_READER(),0640)) {
                   6842:  	if ($bighash{'version_'.$uri}) {
                   6843:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6844:  	    unless (($version eq 'mostrecent') || 
                   6845: 		    ($version==&getversion($uri))) {
1.440     www      6846:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6847:  	    }
                   6848:  	}
                   6849:  	untie %bighash;
1.413     www      6850:     }
1.599     albertel 6851:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6852: }
                   6853: 
                   6854: sub deversion {
                   6855:     my $url=shift;
                   6856:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6857:     return $url;
1.210     www      6858: }
                   6859: 
1.31      www      6860: # ------------------------------------------------------ Return symb list entry
                   6861: 
                   6862: sub symbread {
1.249     www      6863:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6864:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6865:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6866: # no filename provided? try from environment
1.44      www      6867:     unless ($thisfn) {
1.620     albertel 6868:         if ($env{'request.symb'}) {
                   6869: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6870: 	}
1.620     albertel 6871: 	$thisfn=$env{'request.filename'};
1.44      www      6872:     }
1.569     albertel 6873:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6874: # is that filename actually a symb? Verify, clean, and return
                   6875:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6876: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6877: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6878: 	}
1.242     www      6879:     }
1.44      www      6880:     $thisfn=declutter($thisfn);
1.31      www      6881:     my %hash;
1.37      www      6882:     my %bighash;
                   6883:     my $syval='';
1.620     albertel 6884:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6885:         my $targetfn = $thisfn;
1.609     banghart 6886:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6887:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6888:         }
1.687     albertel 6889: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6890: 	    $targetfn=$1;
                   6891: 	}
1.620     albertel 6892:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6893:                       &GDBM_READER(),0640)) {
1.481     raeburn  6894: 	    $syval=$hash{$targetfn};
1.37      www      6895:             untie(%hash);
                   6896:         }
                   6897: # ---------------------------------------------------------- There was an entry
                   6898:         if ($syval) {
1.601     albertel 6899: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6900: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6901: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6902: 		    #return $env{$cache_str}='';
1.601     albertel 6903: 		#}    
                   6904: 		#$syval.=$1;
                   6905: 	    #}
1.37      www      6906:         } else {
                   6907: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6908:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6909:                             &GDBM_READER(),0640)) {
1.37      www      6910: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6911:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6912:               unless ($ids) { 
                   6913:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6914:               }
                   6915:               unless ($ids) {
                   6916: # alias?
                   6917: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6918:               }
1.37      www      6919:               if ($ids) {
                   6920: # ------------------------------------------------------------------- Has ID(s)
                   6921:                  my @possibilities=split(/\,/,$ids);
1.39      www      6922:                  if ($#possibilities==0) {
                   6923: # ----------------------------------------------- There is only one possibility
1.37      www      6924: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6925: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6926: 						    $resid,$thisfn);
1.249     www      6927:                  } elsif (!$donotrecurse) {
1.39      www      6928: # ------------------------------------------ There is more than one possibility
                   6929:                      my $realpossible=0;
1.800     albertel 6930:                      foreach my $id (@possibilities) {
                   6931: 			 my $file=$bighash{'src_'.$id};
1.39      www      6932:                          if (&allowed('bre',$file)) {
1.800     albertel 6933:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6934:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6935: 				$realpossible++;
1.626     albertel 6936:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6937: 						    $resid,$thisfn);
1.39      www      6938:                             }
                   6939: 			 }
1.191     harris41 6940:                      }
1.39      www      6941: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6942:                  } else {
                   6943:                      $syval='';
1.37      www      6944:                  }
                   6945: 	      }
                   6946:               untie(%bighash)
1.481     raeburn  6947:            }
1.31      www      6948:         }
1.62      www      6949:         if ($syval) {
1.620     albertel 6950: 	    return $env{$cache_str}=$syval;
1.62      www      6951:         }
1.31      www      6952:     }
1.44      www      6953:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6954:     return $env{$cache_str}='';
1.31      www      6955: }
                   6956: 
                   6957: # ---------------------------------------------------------- Return random seed
                   6958: 
1.32      www      6959: sub numval {
                   6960:     my $txt=shift;
                   6961:     $txt=~tr/A-J/0-9/;
                   6962:     $txt=~tr/a-j/0-9/;
                   6963:     $txt=~tr/K-T/0-9/;
                   6964:     $txt=~tr/k-t/0-9/;
                   6965:     $txt=~tr/U-Z/0-5/;
                   6966:     $txt=~tr/u-z/0-5/;
                   6967:     $txt=~s/\D//g;
1.564     albertel 6968:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6969:     return int($txt);
1.368     albertel 6970: }
                   6971: 
1.484     albertel 6972: sub numval2 {
                   6973:     my $txt=shift;
                   6974:     $txt=~tr/A-J/0-9/;
                   6975:     $txt=~tr/a-j/0-9/;
                   6976:     $txt=~tr/K-T/0-9/;
                   6977:     $txt=~tr/k-t/0-9/;
                   6978:     $txt=~tr/U-Z/0-5/;
                   6979:     $txt=~tr/u-z/0-5/;
                   6980:     $txt=~s/\D//g;
                   6981:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6982:     my $total;
                   6983:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6984:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6985:     return int($total);
                   6986: }
                   6987: 
1.575     albertel 6988: sub numval3 {
                   6989:     use integer;
                   6990:     my $txt=shift;
                   6991:     $txt=~tr/A-J/0-9/;
                   6992:     $txt=~tr/a-j/0-9/;
                   6993:     $txt=~tr/K-T/0-9/;
                   6994:     $txt=~tr/k-t/0-9/;
                   6995:     $txt=~tr/U-Z/0-5/;
                   6996:     $txt=~tr/u-z/0-5/;
                   6997:     $txt=~s/\D//g;
                   6998:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6999:     my $total;
                   7000:     foreach my $val (@txts) { $total+=$val; }
                   7001:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7002:     return $total;
                   7003: }
                   7004: 
1.675     albertel 7005: sub digest {
                   7006:     my ($data)=@_;
                   7007:     my $digest=&Digest::MD5::md5($data);
                   7008:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7009:     my ($e,$f);
                   7010:     {
                   7011:         use integer;
                   7012:         $e=($a+$b);
                   7013:         $f=($c+$d);
                   7014:         if ($_64bit) {
                   7015:             $e=(($e<<32)>>32);
                   7016:             $f=(($f<<32)>>32);
                   7017:         }
                   7018:     }
                   7019:     if (wantarray) {
                   7020: 	return ($e,$f);
                   7021:     } else {
                   7022: 	my $g;
                   7023: 	{
                   7024: 	    use integer;
                   7025: 	    $g=($e+$f);
                   7026: 	    if ($_64bit) {
                   7027: 		$g=(($g<<32)>>32);
                   7028: 	    }
                   7029: 	}
                   7030: 	return $g;
                   7031:     }
                   7032: }
                   7033: 
1.368     albertel 7034: sub latest_rnd_algorithm_id {
1.675     albertel 7035:     return '64bit5';
1.366     albertel 7036: }
1.32      www      7037: 
1.503     albertel 7038: sub get_rand_alg {
                   7039:     my ($courseid)=@_;
1.790     albertel 7040:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7041:     if ($courseid) {
1.620     albertel 7042: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7043:     }
                   7044:     return &latest_rnd_algorithm_id();
                   7045: }
                   7046: 
1.562     albertel 7047: sub validCODE {
                   7048:     my ($CODE)=@_;
                   7049:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7050:     return 0;
                   7051: }
                   7052: 
1.491     albertel 7053: sub getCODE {
1.620     albertel 7054:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7055:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7056: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7057: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7058: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7059:     }
                   7060:     return undef;
                   7061: }
                   7062: 
1.31      www      7063: sub rndseed {
1.155     albertel 7064:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7065:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 7066:     if (!$symb) {
1.366     albertel 7067: 	unless ($symb=$wsymb) { return time; }
                   7068:     }
                   7069:     if (!$courseid) { $courseid=$wcourseid; }
                   7070:     if (!$domain) { $domain=$wdomain; }
                   7071:     if (!$username) { $username=$wusername }
1.503     albertel 7072:     my $which=&get_rand_alg();
1.803     albertel 7073: 
1.491     albertel 7074:     if (defined(&getCODE())) {
1.675     albertel 7075: 	if ($which eq '64bit5') {
                   7076: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7077: 	} elsif ($which eq '64bit4') {
1.575     albertel 7078: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7079: 	} else {
                   7080: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7081: 	}
1.675     albertel 7082:     } elsif ($which eq '64bit5') {
                   7083: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7084:     } elsif ($which eq '64bit4') {
                   7085: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7086:     } elsif ($which eq '64bit3') {
                   7087: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7088:     } elsif ($which eq '64bit2') {
                   7089: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7090:     } elsif ($which eq '64bit') {
                   7091: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7092:     }
                   7093:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7094: }
                   7095: 
                   7096: sub rndseed_32bit {
                   7097:     my ($symb,$courseid,$domain,$username)=@_;
                   7098:     {
                   7099: 	use integer;
                   7100: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7101: 	my $symbseed=numval($symb) << 22;
                   7102: 	my $namechck=unpack("%32C*",$username) << 17;
                   7103: 	my $nameseed=numval($username) << 12;
                   7104: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7105: 	my $courseseed=unpack("%32C*",$courseid);
                   7106: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7107: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7108: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7109: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7110: 	return $num;
                   7111:     }
                   7112: }
                   7113: 
                   7114: sub rndseed_64bit {
                   7115:     my ($symb,$courseid,$domain,$username)=@_;
                   7116:     {
                   7117: 	use integer;
                   7118: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7119: 	my $symbseed=numval($symb) << 10;
                   7120: 	my $namechck=unpack("%32S*",$username);
                   7121: 	
                   7122: 	my $nameseed=numval($username) << 21;
                   7123: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7124: 	my $courseseed=unpack("%32S*",$courseid);
                   7125: 	
                   7126: 	my $num1=$symbchck+$symbseed+$namechck;
                   7127: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7128: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7129: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7130: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7131: 	return "$num1,$num2";
1.155     albertel 7132:     }
1.366     albertel 7133: }
                   7134: 
1.443     albertel 7135: sub rndseed_64bit2 {
                   7136:     my ($symb,$courseid,$domain,$username)=@_;
                   7137:     {
                   7138: 	use integer;
                   7139: 	# strings need to be an even # of cahracters long, it it is odd the
                   7140:         # last characters gets thrown away
                   7141: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7142: 	my $symbseed=numval($symb) << 10;
                   7143: 	my $namechck=unpack("%32S*",$username.' ');
                   7144: 	
                   7145: 	my $nameseed=numval($username) << 21;
1.501     albertel 7146: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7147: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7148: 	
                   7149: 	my $num1=$symbchck+$symbseed+$namechck;
                   7150: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7151: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7152: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7153: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7154: 	return "$num1,$num2";
                   7155:     }
                   7156: }
                   7157: 
                   7158: sub rndseed_64bit3 {
                   7159:     my ($symb,$courseid,$domain,$username)=@_;
                   7160:     {
                   7161: 	use integer;
                   7162: 	# strings need to be an even # of cahracters long, it it is odd the
                   7163:         # last characters gets thrown away
                   7164: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7165: 	my $symbseed=numval2($symb) << 10;
                   7166: 	my $namechck=unpack("%32S*",$username.' ');
                   7167: 	
                   7168: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7169: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7170: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7171: 	
                   7172: 	my $num1=$symbchck+$symbseed+$namechck;
                   7173: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7174: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7175: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7176: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7177: 	
1.503     albertel 7178: 	return "$num1:$num2";
1.443     albertel 7179:     }
                   7180: }
                   7181: 
1.575     albertel 7182: sub rndseed_64bit4 {
                   7183:     my ($symb,$courseid,$domain,$username)=@_;
                   7184:     {
                   7185: 	use integer;
                   7186: 	# strings need to be an even # of cahracters long, it it is odd the
                   7187:         # last characters gets thrown away
                   7188: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7189: 	my $symbseed=numval3($symb) << 10;
                   7190: 	my $namechck=unpack("%32S*",$username.' ');
                   7191: 	
                   7192: 	my $nameseed=numval3($username) << 21;
                   7193: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7194: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7195: 	
                   7196: 	my $num1=$symbchck+$symbseed+$namechck;
                   7197: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7198: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7199: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7200: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7201: 	
                   7202: 	return "$num1:$num2";
                   7203:     }
                   7204: }
                   7205: 
1.675     albertel 7206: sub rndseed_64bit5 {
                   7207:     my ($symb,$courseid,$domain,$username)=@_;
                   7208:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7209:     return "$num1:$num2";
                   7210: }
                   7211: 
1.366     albertel 7212: sub rndseed_CODE_64bit {
                   7213:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7214:     {
1.366     albertel 7215: 	use integer;
1.443     albertel 7216: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7217: 	my $symbseed=numval2($symb);
1.491     albertel 7218: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7219: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7220: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7221: 	my $num1=$symbseed+$CODEchck;
                   7222: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7223: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7224: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7225: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7226: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7227: 	return "$num1:$num2";
1.366     albertel 7228:     }
                   7229: }
                   7230: 
1.575     albertel 7231: sub rndseed_CODE_64bit4 {
                   7232:     my ($symb,$courseid,$domain,$username)=@_;
                   7233:     {
                   7234: 	use integer;
                   7235: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7236: 	my $symbseed=numval3($symb);
                   7237: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7238: 	my $CODEseed=numval3(&getCODE());
                   7239: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7240: 	my $num1=$symbseed+$CODEchck;
                   7241: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7242: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7243: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7244: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7245: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7246: 	return "$num1:$num2";
                   7247:     }
                   7248: }
                   7249: 
1.675     albertel 7250: sub rndseed_CODE_64bit5 {
                   7251:     my ($symb,$courseid,$domain,$username)=@_;
                   7252:     my $code = &getCODE();
                   7253:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7254:     return "$num1:$num2";
                   7255: }
                   7256: 
1.366     albertel 7257: sub setup_random_from_rndseed {
                   7258:     my ($rndseed)=@_;
1.503     albertel 7259:     if ($rndseed =~/([,:])/) {
                   7260: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7261: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7262:     } else {
                   7263: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7264:     }
1.36      albertel 7265: }
                   7266: 
1.474     albertel 7267: sub latest_receipt_algorithm_id {
1.835     albertel 7268:     return 'receipt3';
1.474     albertel 7269: }
                   7270: 
1.480     www      7271: sub recunique {
                   7272:     my $fucourseid=shift;
                   7273:     my $unique;
1.835     albertel 7274:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7275: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7276: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7277:     } else {
                   7278: 	$unique=$perlvar{'lonReceipt'};
                   7279:     }
                   7280:     return unpack("%32C*",$unique);
                   7281: }
                   7282: 
                   7283: sub recprefix {
                   7284:     my $fucourseid=shift;
                   7285:     my $prefix;
1.835     albertel 7286:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7287: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7288: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7289:     } else {
                   7290: 	$prefix=$perlvar{'lonHostID'};
                   7291:     }
                   7292:     return unpack("%32C*",$prefix);
                   7293: }
                   7294: 
1.76      www      7295: sub ireceipt {
1.474     albertel 7296:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7297: 
                   7298:     my $return =&recprefix($fucourseid).'-';
                   7299: 
                   7300:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7301: 	$env{'request.state'} eq 'construct') {
                   7302: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7303: 	return $return;
                   7304:     }
                   7305: 
1.76      www      7306:     my $cuname=unpack("%32C*",$funame);
                   7307:     my $cudom=unpack("%32C*",$fudom);
                   7308:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7309:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7310:     my $cunique=&recunique($fucourseid);
1.474     albertel 7311:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7312:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7313: 
1.790     albertel 7314: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7315: 			       
                   7316: 	$return.= ($cunique%$cuname+
                   7317: 		   $cunique%$cudom+
                   7318: 		   $cusymb%$cuname+
                   7319: 		   $cusymb%$cudom+
                   7320: 		   $cucourseid%$cuname+
                   7321: 		   $cucourseid%$cudom+
                   7322: 		   $cpart%$cuname+
                   7323: 		   $cpart%$cudom);
                   7324:     } else {
                   7325: 	$return.= ($cunique%$cuname+
                   7326: 		   $cunique%$cudom+
                   7327: 		   $cusymb%$cuname+
                   7328: 		   $cusymb%$cudom+
                   7329: 		   $cucourseid%$cuname+
                   7330: 		   $cucourseid%$cudom);
                   7331:     }
                   7332:     return $return;
1.76      www      7333: }
                   7334: 
                   7335: sub receipt {
1.474     albertel 7336:     my ($part)=@_;
1.790     albertel 7337:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7338:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7339: }
1.260     ng       7340: 
1.790     albertel 7341: sub whichuser {
                   7342:     my ($passedsymb)=@_;
                   7343:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7344:     if (defined($env{'form.grade_symb'})) {
                   7345: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7346: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7347: 	if (!$allowed &&
                   7348: 	    exists($env{'request.course.sec'}) &&
                   7349: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7350: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7351: 			      '/'.$env{'request.course.sec'});
                   7352: 	}
                   7353: 	if ($allowed) {
                   7354: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7355: 	    $courseid=$tmp_courseid;
                   7356: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7357: 	    ($name)=&get_env_multiple('form.grade_username');
                   7358: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7359: 	}
                   7360:     }
                   7361:     if (!$passedsymb) {
                   7362: 	$symb=&symbread();
                   7363:     } else {
                   7364: 	$symb=$passedsymb;
                   7365:     }
                   7366:     $courseid=$env{'request.course.id'};
                   7367:     $domain=$env{'user.domain'};
                   7368:     $name=$env{'user.name'};
                   7369:     if ($name eq 'public' && $domain eq 'public') {
                   7370: 	if (!defined($env{'form.username'})) {
                   7371: 	    $env{'form.username'}.=time.rand(10000000);
                   7372: 	}
                   7373: 	$name.=$env{'form.username'};
                   7374:     }
                   7375:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7376: 
                   7377: }
                   7378: 
1.36      albertel 7379: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7380: # returns either the contents of the file or 
                   7381: # -1 if the file doesn't exist
1.481     raeburn  7382: #
                   7383: # if the target is a file that was uploaded via DOCS, 
                   7384: # a check will be made to see if a current copy exists on the local server,
                   7385: # if it does this will be served, otherwise a copy will be retrieved from
                   7386: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7387: # the local server.   
1.472     albertel 7388: 
1.36      albertel 7389: sub getfile {
1.538     albertel 7390:     my ($file) = @_;
1.609     banghart 7391:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7392:     &repcopy($file);
                   7393:     return &readfile($file);
                   7394: }
                   7395: 
                   7396: sub repcopy_userfile {
                   7397:     my ($file)=@_;
1.609     banghart 7398:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7399:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7400:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7401: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7402:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7403:     if (-e "$file") {
1.828     www      7404: # we already have a local copy, check it out
1.538     albertel 7405: 	my @fileinfo = stat($file);
1.828     www      7406: 	my $rtncode;
                   7407: 	my $info;
1.538     albertel 7408: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7409: 	if ($lwpresp ne 'ok') {
1.828     www      7410: # there is no such file anymore, even though we had a local copy
1.482     albertel 7411: 	    if ($rtncode eq '404') {
1.538     albertel 7412: 		unlink($file);
1.482     albertel 7413: 	    }
                   7414: 	    return -1;
                   7415: 	}
                   7416: 	if ($info < $fileinfo[9]) {
1.828     www      7417: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7418: 	    return 'ok';
1.828     www      7419: 	} else {
                   7420: # the file is outdated, get rid of it
                   7421: 	    unlink($file);
1.482     albertel 7422: 	}
1.828     www      7423:     }
                   7424: # one way or the other, at this point, we don't have the file
                   7425: # construct the correct path for the file
                   7426:     my @parts = ($cdom,$cnum); 
                   7427:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7428: 	push @parts, split(/\//,$1);
                   7429:     }
                   7430:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7431:     foreach my $part (@parts) {
                   7432: 	$path .= '/'.$part;
                   7433: 	if (!-e $path) {
                   7434: 	    mkdir($path,0770);
1.482     albertel 7435: 	}
                   7436:     }
1.828     www      7437: # now the path exists for sure
                   7438: # get a user agent
                   7439:     my $ua=new LWP::UserAgent;
                   7440:     my $transferfile=$file.'.in.transfer';
                   7441: # FIXME: this should flock
                   7442:     if (-e $transferfile) { return 'ok'; }
                   7443:     my $request;
                   7444:     $uri=~s/^\///;
1.838     albertel 7445:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7446:     my $response=$ua->request($request,$transferfile);
                   7447: # did it work?
                   7448:     if ($response->is_error()) {
                   7449: 	unlink($transferfile);
                   7450: 	&logthis("Userfile repcopy failed for $uri");
                   7451: 	return -1;
                   7452:     }
                   7453: # worked, rename the transfer file
                   7454:     rename($transferfile,$file);
1.607     raeburn  7455:     return 'ok';
1.481     raeburn  7456: }
                   7457: 
1.517     albertel 7458: sub tokenwrapper {
                   7459:     my $uri=shift;
1.552     albertel 7460:     $uri=~s|^http\://([^/]+)||;
                   7461:     $uri=~s|^/||;
1.620     albertel 7462:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7463:     my $token=$1;
1.552     albertel 7464:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7465:     if ($udom && $uname && $file) {
                   7466: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7467:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7468:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7469:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7470:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7471:     } else {
                   7472:         return '/adm/notfound.html';
                   7473:     }
                   7474: }
                   7475: 
1.828     www      7476: # call with reqtype HEAD: get last modification time
                   7477: # call with reqtype GET: get the file contents
                   7478: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7479: #
1.481     raeburn  7480: sub getuploaded {
                   7481:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7482:     $uri=~s/^\///;
1.838     albertel 7483:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7484:     my $ua=new LWP::UserAgent;
                   7485:     my $request=new HTTP::Request($reqtype,$uri);
                   7486:     my $response=$ua->request($request);
                   7487:     $$rtncode = $response->code;
1.482     albertel 7488:     if (! $response->is_success()) {
                   7489: 	return 'failed';
                   7490:     }      
                   7491:     if ($reqtype eq 'HEAD') {
1.486     www      7492: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7493:     } elsif ($reqtype eq 'GET') {
                   7494: 	$$info = $response->content;
1.472     albertel 7495:     }
1.482     albertel 7496:     return 'ok';
1.36      albertel 7497: }
                   7498: 
1.481     raeburn  7499: sub readfile {
                   7500:     my $file = shift;
                   7501:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7502:     my $fh;
                   7503:     open($fh,"<$file");
                   7504:     my $a='';
1.800     albertel 7505:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7506:     return $a;
                   7507: }
                   7508: 
1.36      albertel 7509: sub filelocation {
1.590     banghart 7510:     my ($dir,$file) = @_;
                   7511:     my $location;
                   7512:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7513: 
                   7514:     if ($file =~ m-^/adm/-) {
                   7515: 	$file=~s-^/adm/wrapper/-/-;
                   7516: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7517:     }
1.882     albertel 7518: 
1.590     banghart 7519:     if ($file=~m:^/~:) { # is a contruction space reference
                   7520:         $location = $file;
                   7521:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7522:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7523: 	# is a correct contruction space reference
                   7524:         $location = $file;
1.609     banghart 7525:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7526:         my ($udom,$uname,$filename)=
1.811     albertel 7527:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7528:         my $home=&homeserver($uname,$udom);
                   7529:         my $is_me=0;
                   7530:         my @ids=&current_machine_ids();
                   7531:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7532:         if ($is_me) {
1.740     www      7533:   	    $location=&propath($udom,$uname).
1.590     banghart 7534:   	      '/userfiles/'.$filename;
                   7535:         } else {
                   7536:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7537:   	      $udom.'/'.$uname.'/'.$filename;
                   7538:         }
1.882     albertel 7539:     } elsif ($file =~ m-^/adm/-) {
                   7540: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7541:     } else {
                   7542:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7543:         $file=~s:^/res/:/:;
                   7544:         if ( !( $file =~ m:^/:) ) {
                   7545:             $location = $dir. '/'.$file;
                   7546:         } else {
                   7547:             $location = '/home/httpd/html/res'.$file;
                   7548:         }
1.59      albertel 7549:     }
1.590     banghart 7550:     $location=~s://+:/:g; # remove duplicate /
                   7551:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7552:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7553:     return $location;
1.46      www      7554: }
1.36      albertel 7555: 
1.46      www      7556: sub hreflocation {
                   7557:     my ($dir,$file)=@_;
1.460     albertel 7558:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7559: 	$file=filelocation($dir,$file);
1.700     albertel 7560:     } elsif ($file=~m-^/adm/-) {
                   7561: 	$file=~s-^/adm/wrapper/-/-;
                   7562: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7563:     }
                   7564:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7565: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7566:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7567: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7568:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7569: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7570: 	    -/uploaded/$1/$2/-x;
1.46      www      7571:     }
1.462     albertel 7572:     return $file;
1.465     albertel 7573: }
                   7574: 
                   7575: sub current_machine_domains {
1.853     albertel 7576:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7577: }
                   7578: 
                   7579: sub machine_domains {
                   7580:     my ($hostname) = @_;
1.465     albertel 7581:     my @domains;
1.838     albertel 7582:     my %hostname = &all_hostnames();
1.465     albertel 7583:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7584: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7585: 	if ($hostname eq $name) {
1.844     albertel 7586: 	    push(@domains,&host_domain($id));
1.465     albertel 7587: 	}
                   7588:     }
                   7589:     return @domains;
                   7590: }
                   7591: 
                   7592: sub current_machine_ids {
1.853     albertel 7593:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7594: }
                   7595: 
                   7596: sub machine_ids {
                   7597:     my ($hostname) = @_;
                   7598:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7599:     my @ids;
1.838     albertel 7600:     my %hostname = &all_hostnames();
1.465     albertel 7601:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7602: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7603: 	if ($hostname eq $name) {
                   7604: 	    push(@ids,$id);
                   7605: 	}
                   7606:     }
                   7607:     return @ids;
1.31      www      7608: }
                   7609: 
1.824     raeburn  7610: sub additional_machine_domains {
                   7611:     my @domains;
                   7612:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7613:     while( my $line = <$fh>) {
                   7614:         $line =~ s/\s//g;
                   7615:         push(@domains,$line);
                   7616:     }
                   7617:     return @domains;
                   7618: }
                   7619: 
                   7620: sub default_login_domain {
                   7621:     my $domain = $perlvar{'lonDefDomain'};
                   7622:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7623:     foreach my $posdom (&current_machine_domains(),
                   7624:                         &additional_machine_domains()) {
                   7625:         if (lc($posdom) eq lc($testdomain)) {
                   7626:             $domain=$posdom;
                   7627:             last;
                   7628:         }
                   7629:     }
                   7630:     return $domain;
                   7631: }
                   7632: 
1.31      www      7633: # ------------------------------------------------------------- Declutters URLs
                   7634: 
                   7635: sub declutter {
                   7636:     my $thisfn=shift;
1.569     albertel 7637:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7638:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7639:     $thisfn=~s/^\///;
1.697     albertel 7640:     $thisfn=~s|^adm/wrapper/||;
                   7641:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7642:     $thisfn=~s/^res\///;
1.235     www      7643:     $thisfn=~s/\?.+$//;
1.268     www      7644:     return $thisfn;
                   7645: }
                   7646: 
                   7647: # ------------------------------------------------------------- Clutter up URLs
                   7648: 
                   7649: sub clutter {
                   7650:     my $thisfn='/'.&declutter(shift);
1.884     albertel 7651:     if ($thisfn !~ m{^/(uploaded|editupload|userfiles|ext|raw|priv|public)/}
                   7652: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7653:        $thisfn='/res'.$thisfn; 
                   7654:     }
1.694     albertel 7655:     if ($thisfn !~m|/adm|) {
1.695     albertel 7656: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7657: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7658: 	} else {
                   7659: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7660: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7661: 	    if ($embstyle eq 'ssi'
                   7662: 		|| ($embstyle eq 'hdn')
                   7663: 		|| ($embstyle eq 'rat')
                   7664: 		|| ($embstyle eq 'prv')
                   7665: 		|| ($embstyle eq 'ign')) {
                   7666: 		#do nothing with these
                   7667: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7668: 		|| ($embstyle eq 'emb')
                   7669: 		|| ($embstyle eq 'wrp')) {
                   7670: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7671: 	    } elsif ($embstyle eq 'unk'
                   7672: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7673: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7674: 	    } else {
1.718     www      7675: #		&logthis("Got a blank emb style");
1.695     albertel 7676: 	    }
1.694     albertel 7677: 	}
                   7678:     }
1.31      www      7679:     return $thisfn;
1.12      www      7680: }
                   7681: 
1.787     albertel 7682: sub clutter_with_no_wrapper {
                   7683:     my $uri = &clutter(shift);
                   7684:     if ($uri =~ m-^/adm/-) {
                   7685: 	$uri =~ s-^/adm/wrapper/-/-;
                   7686: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7687:     }
                   7688:     return $uri;
                   7689: }
                   7690: 
1.557     albertel 7691: sub freeze_escape {
                   7692:     my ($value)=@_;
                   7693:     if (ref($value)) {
                   7694: 	$value=&nfreeze($value);
                   7695: 	return '__FROZEN__'.&escape($value);
                   7696:     }
                   7697:     return &escape($value);
                   7698: }
                   7699: 
1.11      www      7700: 
1.557     albertel 7701: sub thaw_unescape {
                   7702:     my ($value)=@_;
                   7703:     if ($value =~ /^__FROZEN__/) {
                   7704: 	substr($value,0,10,undef);
                   7705: 	$value=&unescape($value);
                   7706: 	return &thaw($value);
                   7707:     }
                   7708:     return &unescape($value);
                   7709: }
                   7710: 
1.436     albertel 7711: sub correct_line_ends {
                   7712:     my ($result)=@_;
                   7713:     $$result =~s/\r\n/\n/mg;
                   7714:     $$result =~s/\r/\n/mg;
1.415     albertel 7715: }
1.1       albertel 7716: # ================================================================ Main Program
                   7717: 
1.184     www      7718: sub goodbye {
1.204     albertel 7719:    &logthis("Starting Shut down");
1.443     albertel 7720: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7721:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7722: #converted
1.599     albertel 7723: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7724:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7725: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7726: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7727: #1.1 only
1.870     albertel 7728: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7729: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7730: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7731: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7732:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7733:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7734:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7735:    &flushcourselogs();
                   7736:    &logthis("Shutting down");
                   7737: }
                   7738: 
1.852     albertel 7739: sub get_dns {
1.869     albertel 7740:     my ($url,$func,$ignore_cache) = @_;
                   7741:     if (!$ignore_cache) {
                   7742: 	my ($content,$cached)=
                   7743: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7744: 	if ($cached) {
                   7745: 	    &$func($content);
                   7746: 	    return;
                   7747: 	}
                   7748:     }
                   7749: 
                   7750:     my %alldns;
1.852     albertel 7751:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7752:     foreach my $dns (<$config>) {
                   7753: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7754: 	$alldns{$1} = 1;
                   7755:     }
                   7756:     while (%alldns) {
                   7757: 	my ($dns) = keys(%alldns);
                   7758: 	delete($alldns{$dns});
1.852     albertel 7759: 	my $ua=new LWP::UserAgent;
                   7760: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7761: 	my $response=$ua->request($request);
                   7762: 	next if ($response->is_error());
                   7763: 	my @content = split("\n",$response->content);
1.869     albertel 7764: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7765: 	&$func(\@content);
1.869     albertel 7766: 	return;
1.852     albertel 7767:     }
                   7768:     close($config);
1.871     albertel 7769:     my $which = (split('/',$url))[3];
                   7770:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7771:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7772:     my @content = <$config>;
                   7773:     &$func(\@content);
                   7774:     return;
1.852     albertel 7775: }
1.327     albertel 7776: # ------------------------------------------------------------ Read domain file
                   7777: {
1.852     albertel 7778:     my $loaded;
1.846     albertel 7779:     my %domain;
                   7780: 
1.852     albertel 7781:     sub parse_domain_tab {
                   7782: 	my ($lines) = @_;
                   7783: 	foreach my $line (@$lines) {
                   7784: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7785: 
1.846     albertel 7786: 	    chomp($line);
1.852     albertel 7787: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7788: 	    my %this_domain;
                   7789: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7790: 			       'lang_def', 'city', 'longi', 'lati',
                   7791: 			       'primary') {
                   7792: 		$this_domain{$field} = shift(@elements);
                   7793: 	    }
                   7794: 	    $domain{$name} = \%this_domain;
1.852     albertel 7795: 	}
                   7796:     }
1.864     albertel 7797: 
                   7798:     sub reset_domain_info {
                   7799: 	undef($loaded);
                   7800: 	undef(%domain);
                   7801:     }
                   7802: 
1.852     albertel 7803:     sub load_domain_tab {
1.869     albertel 7804: 	my ($ignore_cache) = @_;
                   7805: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7806: 	my $fh;
                   7807: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7808: 	    my @lines = <$fh>;
                   7809: 	    &parse_domain_tab(\@lines);
1.448     albertel 7810: 	}
1.852     albertel 7811: 	close($fh);
                   7812: 	$loaded = 1;
1.327     albertel 7813:     }
1.846     albertel 7814: 
                   7815:     sub domain {
1.852     albertel 7816: 	&load_domain_tab() if (!$loaded);
                   7817: 
1.846     albertel 7818: 	my ($name,$what) = @_;
                   7819: 	return if ( !exists($domain{$name}) );
                   7820: 
                   7821: 	if (!$what) {
                   7822: 	    return $domain{$name}{'description'};
                   7823: 	}
                   7824: 	return $domain{$name}{$what};
                   7825:     }
1.327     albertel 7826: }
                   7827: 
                   7828: 
1.1       albertel 7829: # ------------------------------------------------------------- Read hosts file
                   7830: {
1.838     albertel 7831:     my %hostname;
1.844     albertel 7832:     my %hostdom;
1.845     albertel 7833:     my %libserv;
1.852     albertel 7834:     my $loaded;
                   7835: 
                   7836:     sub parse_hosts_tab {
                   7837: 	my ($file) = @_;
                   7838: 	foreach my $configline (@$file) {
                   7839: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7840: 	    next if ($configline =~ /^\^/);
                   7841: 	    chomp($configline);
                   7842: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7843: 	    $name=~s/\s//g;
                   7844: 	    if ($id && $domain && $role && $name) {
                   7845: 		$hostname{$id}=$name;
                   7846: 		$hostdom{$id}=$domain;
                   7847: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   7848: 	    }
                   7849: 	}
                   7850:     }
1.864     albertel 7851:     
                   7852:     sub reset_hosts_info {
                   7853: 	&reset_domain_info();
                   7854: 	&reset_hosts_ip_info();
                   7855: 	undef(%hostname);
                   7856: 	undef(%hostdom);
                   7857: 	undef(%libserv);
                   7858: 	undef($loaded);
                   7859:     }
1.1       albertel 7860: 
1.852     albertel 7861:     sub load_hosts_tab {
1.869     albertel 7862: 	my ($ignore_cache) = @_;
                   7863: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 7864: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7865: 	my @config = <$config>;
                   7866: 	&parse_hosts_tab(\@config);
                   7867: 	close($config);
                   7868: 	$loaded=1;
1.1       albertel 7869:     }
1.852     albertel 7870: 
1.838     albertel 7871:     sub hostname {
1.852     albertel 7872: 	&load_hosts_tab() if (!$loaded);
                   7873: 
1.838     albertel 7874: 	my ($lonid) = @_;
                   7875: 	return $hostname{$lonid};
                   7876:     }
1.845     albertel 7877: 
1.838     albertel 7878:     sub all_hostnames {
1.852     albertel 7879: 	&load_hosts_tab() if (!$loaded);
                   7880: 
1.838     albertel 7881: 	return %hostname;
                   7882:     }
1.845     albertel 7883: 
                   7884:     sub is_library {
1.852     albertel 7885: 	&load_hosts_tab() if (!$loaded);
                   7886: 
1.845     albertel 7887: 	return exists($libserv{$_[0]});
                   7888:     }
                   7889: 
                   7890:     sub all_library {
1.852     albertel 7891: 	&load_hosts_tab() if (!$loaded);
                   7892: 
1.845     albertel 7893: 	return %libserv;
                   7894:     }
                   7895: 
1.841     albertel 7896:     sub get_servers {
1.852     albertel 7897: 	&load_hosts_tab() if (!$loaded);
                   7898: 
1.841     albertel 7899: 	my ($domain,$type) = @_;
                   7900: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7901: 	                                          : %hostname;
                   7902: 	my %result;
1.842     albertel 7903: 	if (ref($domain) eq 'ARRAY') {
                   7904: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7905: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7906: 		    $result{$host} = $hostname;
                   7907: 		}
                   7908: 	    }
                   7909: 	} else {
                   7910: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7911: 		if ($hostdom{$host} eq $domain) {
                   7912: 		    $result{$host} = $hostname;
                   7913: 		}
1.841     albertel 7914: 	    }
                   7915: 	}
                   7916: 	return %result;
                   7917:     }
1.845     albertel 7918: 
1.844     albertel 7919:     sub host_domain {
1.852     albertel 7920: 	&load_hosts_tab() if (!$loaded);
                   7921: 
1.844     albertel 7922: 	my ($lonid) = @_;
                   7923: 	return $hostdom{$lonid};
                   7924:     }
                   7925: 
1.841     albertel 7926:     sub all_domains {
1.852     albertel 7927: 	&load_hosts_tab() if (!$loaded);
                   7928: 
1.841     albertel 7929: 	my %seen;
                   7930: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7931: 	return @uniq;
                   7932:     }
1.1       albertel 7933: }
                   7934: 
1.847     albertel 7935: { 
                   7936:     my %iphost;
1.856     albertel 7937:     my %name_to_ip;
                   7938:     my %lonid_to_ip;
1.869     albertel 7939: 
                   7940:     my %valid_ip;
                   7941:     sub valid_ip {
                   7942: 	my ($ip) = @_;
                   7943: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
                   7944: 	    return 1;	
                   7945: 	}
                   7946: 	my $name = gethostbyip($ip);
                   7947: 	my $lonid = &hostname($name);
                   7948: 	if (defined($lonid)) {
                   7949: 	    $valid_ip{$ip} = $lonid;
                   7950: 	    return 1;
                   7951: 	}
                   7952: 	my %iphosts = &get_iphost();
                   7953: 	if (ref($iphost{$ip})) {
                   7954: 	    return 1;	
                   7955: 	}
                   7956:     }
                   7957: 
1.847     albertel 7958:     sub get_hosts_from_ip {
                   7959: 	my ($ip) = @_;
                   7960: 	my %iphosts = &get_iphost();
                   7961: 	if (ref($iphosts{$ip})) {
                   7962: 	    return @{$iphosts{$ip}};
                   7963: 	}
                   7964: 	return;
1.839     albertel 7965:     }
1.864     albertel 7966:     
                   7967:     sub reset_hosts_ip_info {
                   7968: 	undef(%iphost);
                   7969: 	undef(%name_to_ip);
                   7970: 	undef(%lonid_to_ip);
                   7971:     }
1.856     albertel 7972: 
                   7973:     sub get_host_ip {
                   7974: 	my ($lonid) = @_;
                   7975: 	if (exists($lonid_to_ip{$lonid})) {
                   7976: 	    return $lonid_to_ip{$lonid};
                   7977: 	}
                   7978: 	my $name=&hostname($lonid);
                   7979:    	my $ip = gethostbyname($name);
                   7980: 	return if (!$ip || length($ip) ne 4);
                   7981: 	$ip=inet_ntoa($ip);
                   7982: 	$name_to_ip{$name}   = $ip;
                   7983: 	$lonid_to_ip{$lonid} = $ip;
                   7984: 	return $ip;
                   7985:     }
1.847     albertel 7986:     
                   7987:     sub get_iphost {
1.869     albertel 7988: 	my ($ignore_cache) = @_;
                   7989: 	if (!$ignore_cache) {
                   7990: 	    if (%iphost) {
                   7991: 		return %iphost;
                   7992: 	    }
                   7993: 	    my ($ip_info,$cached)=
                   7994: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   7995: 	    if ($cached) {
                   7996: 		%iphost      = %{$ip_info->[0]};
                   7997: 		%name_to_ip  = %{$ip_info->[1]};
                   7998: 		%lonid_to_ip = %{$ip_info->[2]};
                   7999: 		return %iphost;
                   8000: 	    }
                   8001: 	}
1.847     albertel 8002: 	my %hostname = &all_hostnames();
                   8003: 	foreach my $id (keys(%hostname)) {
1.864     albertel 8004: 	    my $name=&hostname($id);
1.847     albertel 8005: 	    my $ip;
                   8006: 	    if (!exists($name_to_ip{$name})) {
                   8007: 		$ip = gethostbyname($name);
                   8008: 		if (!$ip || length($ip) ne 4) {
                   8009: 		    &logthis("Skipping host $id name $name no IP found");
                   8010: 		    next;
                   8011: 		}
                   8012: 		$ip=inet_ntoa($ip);
                   8013: 		$name_to_ip{$name} = $ip;
                   8014: 	    } else {
                   8015: 		$ip = $name_to_ip{$name};
1.653     albertel 8016: 	    }
1.856     albertel 8017: 	    $lonid_to_ip{$id} = $ip;
1.847     albertel 8018: 	    push(@{$iphost{$ip}},$id);
1.598     albertel 8019: 	}
1.869     albertel 8020: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8021: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   8022: 				      24*60*60);
                   8023: 
1.847     albertel 8024: 	return %iphost;
1.598     albertel 8025:     }
                   8026: }
                   8027: 
1.862     albertel 8028: BEGIN {
                   8029: 
                   8030: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8031:     unless ($readit) {
                   8032: {
                   8033:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8034:     %perlvar = (%perlvar,%{$configvars});
                   8035: }
                   8036: 
                   8037: 
1.1       albertel 8038: # ------------------------------------------------------ Read spare server file
                   8039: {
1.448     albertel 8040:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8041: 
                   8042:     while (my $configline=<$config>) {
                   8043:        chomp($configline);
1.284     matthew  8044:        if ($configline) {
1.784     albertel 8045: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8046: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8047: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8048:        }
                   8049:     }
1.448     albertel 8050:     close($config);
1.1       albertel 8051: }
1.11      www      8052: # ------------------------------------------------------------ Read permissions
                   8053: {
1.448     albertel 8054:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8055: 
                   8056:     while (my $configline=<$config>) {
1.448     albertel 8057: 	chomp($configline);
                   8058: 	if ($configline) {
                   8059: 	    my ($role,$perm)=split(/ /,$configline);
                   8060: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8061: 	}
1.11      www      8062:     }
1.448     albertel 8063:     close($config);
1.11      www      8064: }
                   8065: 
                   8066: # -------------------------------------------- Read plain texts for permissions
                   8067: {
1.448     albertel 8068:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8069: 
                   8070:     while (my $configline=<$config>) {
1.448     albertel 8071: 	chomp($configline);
                   8072: 	if ($configline) {
1.742     raeburn  8073: 	    my ($short,@plain)=split(/:/,$configline);
                   8074:             %{$prp{$short}} = ();
                   8075: 	    if (@plain > 0) {
                   8076:                 $prp{$short}{'std'} = $plain[0];
                   8077:                 for (my $i=1; $i<@plain; $i++) {
                   8078:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8079:                 }
                   8080:             }
1.448     albertel 8081: 	}
1.135     www      8082:     }
1.448     albertel 8083:     close($config);
1.135     www      8084: }
                   8085: 
                   8086: # ---------------------------------------------------------- Read package table
                   8087: {
1.448     albertel 8088:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8089: 
                   8090:     while (my $configline=<$config>) {
1.483     albertel 8091: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8092: 	chomp($configline);
                   8093: 	my ($short,$plain)=split(/:/,$configline);
                   8094: 	my ($pack,$name)=split(/\&/,$short);
                   8095: 	if ($plain ne '') {
                   8096: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8097: 	    $packagetab{$short}=$plain; 
                   8098: 	}
1.11      www      8099:     }
1.448     albertel 8100:     close($config);
1.329     matthew  8101: }
                   8102: 
                   8103: # ------------- set up temporary directory
                   8104: {
                   8105:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8106: 
1.11      www      8107: }
                   8108: 
1.794     albertel 8109: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8110: 				'compress_threshold'=> 20_000,
                   8111:  			        });
1.185     www      8112: 
1.281     www      8113: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8114: $dumpcount=0;
1.22      www      8115: 
1.163     harris41 8116: &logtouch();
1.672     albertel 8117: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8118: $readit=1;
1.564     albertel 8119:     {
                   8120: 	use integer;
                   8121: 	my $test=(2**32)+1;
1.568     albertel 8122: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8123: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8124:     }
1.195     www      8125: }
1.1       albertel 8126: }
1.179     www      8127: 
1.1       albertel 8128: 1;
1.191     harris41 8129: __END__
                   8130: 
1.243     albertel 8131: =pod
                   8132: 
1.191     harris41 8133: =head1 NAME
                   8134: 
1.243     albertel 8135: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8136: 
                   8137: =head1 SYNOPSIS
                   8138: 
1.243     albertel 8139: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8140: 
                   8141:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8142: 
1.243     albertel 8143: Common parameters:
                   8144: 
                   8145: =over 4
                   8146: 
                   8147: =item *
                   8148: 
                   8149: $uname : an internal username (if $cname expecting a course Id specifically)
                   8150: 
                   8151: =item *
                   8152: 
                   8153: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8154: 
                   8155: =item *
                   8156: 
                   8157: $symb : a resource instance identifier
                   8158: 
                   8159: =item *
                   8160: 
                   8161: $namespace : the name of a .db file that contains the data needed or
                   8162: being set.
                   8163: 
                   8164: =back
                   8165: 
1.394     bowersj2 8166: =head1 OVERVIEW
1.191     harris41 8167: 
1.394     bowersj2 8168: lonnet provides subroutines which interact with the
                   8169: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8170: about classes, users, and resources.
1.243     albertel 8171: 
                   8172: For many of these objects you can also use this to store data about
                   8173: them or modify them in various ways.
1.191     harris41 8174: 
1.394     bowersj2 8175: =head2 Symbs
1.191     harris41 8176: 
1.394     bowersj2 8177: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8178: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8179: map, the resource number of the resource in the map, and the URL of
                   8180: the resource itself. The latter is somewhat redundant, but might help
                   8181: if maps change.
                   8182: 
                   8183: An example is
                   8184: 
                   8185:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8186: 
                   8187: The respective map entry is
                   8188: 
                   8189:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8190:   title="Problem 2">
                   8191:  </resource>
                   8192: 
                   8193: Symbs are used by the random number generator, as well as to store and
                   8194: restore data specific to a certain instance of for example a problem.
                   8195: 
                   8196: =head2 Storing And Retrieving Data
                   8197: 
                   8198: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8199: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8200: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8201: is is the non-critical message twin of cstore. These functions are for
                   8202: handlers to store a perl hash to a user's permanent data space in an
                   8203: easy manner, and to retrieve it again on another call. It is expected
                   8204: that a handler would use this once at the beginning to retrieve data,
                   8205: and then again once at the end to send only the new data back.
                   8206: 
                   8207: The data is stored in the user's data directory on the user's
                   8208: homeserver under the ID of the course.
                   8209: 
                   8210: The hash that is returned by restore will have all of the previous
                   8211: value for all of the elements of the hash.
                   8212: 
                   8213: Example:
                   8214: 
                   8215:  #creating a hash
                   8216:  my %hash;
                   8217:  $hash{'foo'}='bar';
                   8218: 
                   8219:  #storing it
                   8220:  &Apache::lonnet::cstore(\%hash);
                   8221: 
                   8222:  #changing a value
                   8223:  $hash{'foo'}='notbar';
                   8224: 
                   8225:  #adding a new value
                   8226:  $hash{'bar'}='foo';
                   8227:  &Apache::lonnet::cstore(\%hash);
                   8228: 
                   8229:  #retrieving the hash
                   8230:  my %history=&Apache::lonnet::restore();
                   8231: 
                   8232:  #print the hash
                   8233:  foreach my $key (sort(keys(%history))) {
                   8234:    print("\%history{$key} = $history{$key}");
                   8235:  }
                   8236: 
                   8237: Will print out:
1.191     harris41 8238: 
1.394     bowersj2 8239:  %history{1:foo} = bar
                   8240:  %history{1:keys} = foo:timestamp
                   8241:  %history{1:timestamp} = 990455579
                   8242:  %history{2:bar} = foo
                   8243:  %history{2:foo} = notbar
                   8244:  %history{2:keys} = foo:bar:timestamp
                   8245:  %history{2:timestamp} = 990455580
                   8246:  %history{bar} = foo
                   8247:  %history{foo} = notbar
                   8248:  %history{timestamp} = 990455580
                   8249:  %history{version} = 2
                   8250: 
                   8251: Note that the special hash entries C<keys>, C<version> and
                   8252: C<timestamp> were added to the hash. C<version> will be equal to the
                   8253: total number of versions of the data that have been stored. The
                   8254: C<timestamp> attribute will be the UNIX time the hash was
                   8255: stored. C<keys> is available in every historical section to list which
                   8256: keys were added or changed at a specific historical revision of a
                   8257: hash.
                   8258: 
                   8259: B<Warning>: do not store the hash that restore returns directly. This
                   8260: will cause a mess since it will restore the historical keys as if the
                   8261: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8262: 
1.394     bowersj2 8263: Calling convention:
1.191     harris41 8264: 
1.394     bowersj2 8265:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8266:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8267: 
1.394     bowersj2 8268: For more detailed information, see lonnet specific documentation.
1.191     harris41 8269: 
1.394     bowersj2 8270: =head1 RETURN MESSAGES
1.191     harris41 8271: 
1.394     bowersj2 8272: =over 4
1.191     harris41 8273: 
1.394     bowersj2 8274: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8275: 
1.394     bowersj2 8276: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8277: when the connection is brought back up
1.191     harris41 8278: 
1.394     bowersj2 8279: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8280: for later delivery
1.191     harris41 8281: 
1.394     bowersj2 8282: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8283: 
1.394     bowersj2 8284: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8285: that was requested
1.191     harris41 8286: 
1.243     albertel 8287: =back
1.191     harris41 8288: 
1.243     albertel 8289: =head1 PUBLIC SUBROUTINES
1.191     harris41 8290: 
1.243     albertel 8291: =head2 Session Environment Functions
1.191     harris41 8292: 
1.243     albertel 8293: =over 4
1.191     harris41 8294: 
1.394     bowersj2 8295: =item * 
                   8296: X<appenv()>
                   8297: B<appenv(%hash)>: the value of %hash is written to
                   8298: the user envirnoment file, and will be restored for each access this
1.620     albertel 8299: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8300: process
1.191     harris41 8301: 
                   8302: =item *
1.394     bowersj2 8303: X<delenv()>
                   8304: B<delenv($regexp)>: removes all items from the session
                   8305: environment file that matches the regular expression in $regexp. The
1.620     albertel 8306: values are also delted from the current processes %env.
1.191     harris41 8307: 
1.795     albertel 8308: =item * get_env_multiple($name) 
                   8309: 
                   8310: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8311: values may be defined and end up as an array ref.
                   8312: 
                   8313: returns an array of values
                   8314: 
1.243     albertel 8315: =back
                   8316: 
                   8317: =head2 User Information
1.191     harris41 8318: 
1.243     albertel 8319: =over 4
1.191     harris41 8320: 
                   8321: =item *
1.394     bowersj2 8322: X<queryauthenticate()>
                   8323: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8324: authentication scheme
                   8325: 
                   8326: =item *
1.394     bowersj2 8327: X<authenticate()>
                   8328: B<authenticate($uname,$upass,$udom)>: try to
                   8329: authenticate user from domain's lib servers (first use the current
                   8330: one). C<$upass> should be the users password.
1.191     harris41 8331: 
                   8332: =item *
1.394     bowersj2 8333: X<homeserver()>
                   8334: B<homeserver($uname,$udom)>: find the server which has
                   8335: the user's directory and files (there must be only one), this caches
                   8336: the answer, and also caches if there is a borken connection.
1.191     harris41 8337: 
                   8338: =item *
1.394     bowersj2 8339: X<idget()>
                   8340: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8341: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8342: username, and only 1 username per ID in a specific domain) (returns
                   8343: hash: id=>name,id=>name)
1.191     harris41 8344: 
                   8345: =item *
1.394     bowersj2 8346: X<idrget()>
                   8347: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8348: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8349: 
                   8350: =item *
1.394     bowersj2 8351: X<idput()>
                   8352: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8353: 
                   8354: =item *
1.394     bowersj2 8355: X<rolesinit()>
                   8356: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8357: 
                   8358: =item *
1.551     albertel 8359: X<getsection()>
                   8360: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8361: course $cname, return section name/number or '' for "not in course"
                   8362: and '-1' for "no section"
                   8363: 
                   8364: =item *
1.394     bowersj2 8365: X<userenvironment()>
                   8366: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8367: passed in @what from the requested user's environment, returns a hash
                   8368: 
1.858     raeburn  8369: =item * 
                   8370: X<userlog_query()>
1.859     albertel 8371: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8372: activity.log file. %filters defines filters applied when parsing the
                   8373: log file. These can be start or end timestamps, or the type of action
                   8374: - log to look for Login or Logout events, check for Checkin or
                   8375: Checkout, role for role selection. The response is in the form
                   8376: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8377: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8378: 
1.243     albertel 8379: =back
                   8380: 
                   8381: =head2 User Roles
                   8382: 
                   8383: =over 4
                   8384: 
                   8385: =item *
                   8386: 
1.810     raeburn  8387: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8388:  F: full access
                   8389:  U,I,K: authentication modes (cxx only)
                   8390:  '': forbidden
                   8391:  1: user needs to choose course
                   8392:  2: browse allowed
1.766     albertel 8393:  A: passphrase authentication needed
1.243     albertel 8394: 
                   8395: =item *
                   8396: 
                   8397: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8398: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8399: and course level
                   8400: 
                   8401: =item *
                   8402: 
                   8403: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8404: explanation of a user role term
                   8405: 
1.832     raeburn  8406: =item *
                   8407: 
1.858     raeburn  8408: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8409: All arguments are optional. Returns a hash of a roles, either for
                   8410: co-author/assistant author roles for a user's Construction Space
                   8411: (default), or if $context is 'user', roles for the user himself,
                   8412: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8413: and value is set to colon-separated start and end times for the role.
                   8414: If no username and domain are specified, will default to current
                   8415: user/domain. Types, roles, and roledoms are references to arrays,
                   8416: of role statuses (active, future or previous), roles 
                   8417: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8418: to restrict the list of roles reported. If no array ref is 
                   8419: provided for types, will default to return only active roles.
1.834     albertel 8420: 
1.243     albertel 8421: =back
                   8422: 
                   8423: =head2 User Modification
                   8424: 
                   8425: =over 4
                   8426: 
                   8427: =item *
                   8428: 
                   8429: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8430: user for the level given by URL.  Optional start and end dates (leave empty
                   8431: string or zero for "no date")
1.191     harris41 8432: 
                   8433: =item *
                   8434: 
1.243     albertel 8435: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8436: change a users, password, possible return values are: ok,
                   8437: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8438: refused
1.191     harris41 8439: 
                   8440: =item *
                   8441: 
1.243     albertel 8442: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8443: 
                   8444: =item *
                   8445: 
1.243     albertel 8446: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8447: modify user
1.191     harris41 8448: 
                   8449: =item *
                   8450: 
1.286     matthew  8451: modifystudent
                   8452: 
                   8453: modify a students enrollment and identification information.
                   8454: The course id is resolved based on the current users environment.  
                   8455: This means the envoking user must be a course coordinator or otherwise
                   8456: associated with a course.
                   8457: 
1.297     matthew  8458: This call is essentially a wrapper for lonnet::modifyuser and
                   8459: lonnet::modify_student_enrollment
1.286     matthew  8460: 
                   8461: Inputs: 
                   8462: 
                   8463: =over 4
                   8464: 
                   8465: =item B<$udom> Students loncapa domain
                   8466: 
                   8467: =item B<$uname> Students loncapa login name
                   8468: 
                   8469: =item B<$uid> Students id/student number
                   8470: 
                   8471: =item B<$umode> Students authentication mode
                   8472: 
                   8473: =item B<$upass> Students password
                   8474: 
                   8475: =item B<$first> Students first name
                   8476: 
                   8477: =item B<$middle> Students middle name
                   8478: 
                   8479: =item B<$last> Students last name
                   8480: 
                   8481: =item B<$gene> Students generation
                   8482: 
                   8483: =item B<$usec> Students section in course
                   8484: 
                   8485: =item B<$end> Unix time of the roles expiration
                   8486: 
                   8487: =item B<$start> Unix time of the roles start date
                   8488: 
                   8489: =item B<$forceid> If defined, allow $uid to be changed
                   8490: 
                   8491: =item B<$desiredhome> server to use as home server for student
                   8492: 
                   8493: =back
1.297     matthew  8494: 
                   8495: =item *
                   8496: 
                   8497: modify_student_enrollment
                   8498: 
                   8499: Change a students enrollment status in a class.  The environment variable
                   8500: 'role.request.course' must be defined for this function to proceed.
                   8501: 
                   8502: Inputs:
                   8503: 
                   8504: =over 4
                   8505: 
                   8506: =item $udom, students domain
                   8507: 
                   8508: =item $uname, students name
                   8509: 
                   8510: =item $uid, students user id
                   8511: 
                   8512: =item $first, students first name
                   8513: 
                   8514: =item $middle
                   8515: 
                   8516: =item $last
                   8517: 
                   8518: =item $gene
                   8519: 
                   8520: =item $usec
                   8521: 
                   8522: =item $end
                   8523: 
                   8524: =item $start
                   8525: 
                   8526: =back
                   8527: 
1.191     harris41 8528: 
                   8529: =item *
                   8530: 
1.243     albertel 8531: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8532: custom role; give a custom role to a user for the level given by URL.  Specify
                   8533: name and domain of role author, and role name
1.191     harris41 8534: 
                   8535: =item *
                   8536: 
1.243     albertel 8537: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8538: 
                   8539: =item *
                   8540: 
1.243     albertel 8541: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8542: 
                   8543: =back
                   8544: 
                   8545: =head2 Course Infomation
                   8546: 
                   8547: =over 4
1.191     harris41 8548: 
                   8549: =item *
                   8550: 
1.631     albertel 8551: coursedescription($courseid) : returns a hash of information about the
                   8552: specified course id, including all environment settings for the
                   8553: course, the description of the course will be in the hash under the
                   8554: key 'description'
1.191     harris41 8555: 
                   8556: =item *
                   8557: 
1.624     albertel 8558: resdata($name,$domain,$type,@which) : request for current parameter
                   8559: setting for a specific $type, where $type is either 'course' or 'user',
                   8560: @what should be a list of parameters to ask about. This routine caches
                   8561: answers for 5 minutes.
1.243     albertel 8562: 
1.877     foxr     8563: =item *
                   8564: 
                   8565: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8566: data base, returning a hash that is keyed by the resource name and has
                   8567: values that are the resource value.  I believe that the timestamps and
                   8568: versions are also returned.
                   8569: 
                   8570: 
1.243     albertel 8571: =back
                   8572: 
                   8573: =head2 Course Modification
                   8574: 
                   8575: =over 4
1.191     harris41 8576: 
                   8577: =item *
                   8578: 
1.243     albertel 8579: writecoursepref($courseid,%prefs) : write preferences (environment
                   8580: database) for a course
1.191     harris41 8581: 
                   8582: =item *
                   8583: 
1.243     albertel 8584: createcourse($udom,$description,$url) : make/modify course
                   8585: 
                   8586: =back
                   8587: 
                   8588: =head2 Resource Subroutines
                   8589: 
                   8590: =over 4
1.191     harris41 8591: 
                   8592: =item *
                   8593: 
1.243     albertel 8594: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8595: 
                   8596: =item *
                   8597: 
1.243     albertel 8598: repcopy($filename) : subscribes to the requested file, and attempts to
                   8599: replicate from the owning library server, Might return
1.607     raeburn  8600: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8601: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8602: resource. Expects the local filesystem pathname
                   8603: (/home/httpd/html/res/....)
                   8604: 
                   8605: =back
                   8606: 
                   8607: =head2 Resource Information
                   8608: 
                   8609: =over 4
1.191     harris41 8610: 
                   8611: =item *
                   8612: 
1.243     albertel 8613: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8614: a vairety of different possible values, $varname should be a request
                   8615: string, and the other parameters can be used to specify who and what
                   8616: one is asking about.
                   8617: 
                   8618: Possible values for $varname are environment.lastname (or other item
                   8619: from the envirnment hash), user.name (or someother aspect about the
                   8620: user), resource.0.maxtries (or some other part and parameter of a
                   8621: resource)
1.204     albertel 8622: 
                   8623: =item *
                   8624: 
1.243     albertel 8625: directcondval($number) : get current value of a condition; reads from a state
                   8626: string
1.204     albertel 8627: 
                   8628: =item *
                   8629: 
1.243     albertel 8630: condval($condidx) : value of condition index based on state
1.204     albertel 8631: 
                   8632: =item *
                   8633: 
1.243     albertel 8634: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8635: resource's metadata, $what should be either a specific key, or either
                   8636: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8637: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8638: 
                   8639: this function automatically caches all requests
1.191     harris41 8640: 
                   8641: =item *
                   8642: 
1.243     albertel 8643: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8644: network of library servers; returns file handle of where SQL and regex results
                   8645: will be stored for query
1.191     harris41 8646: 
                   8647: =item *
                   8648: 
1.243     albertel 8649: symbread($filename) : return symbolic list entry (filename argument optional);
                   8650: returns the data handle
1.191     harris41 8651: 
                   8652: =item *
                   8653: 
1.243     albertel 8654: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8655: a possible symb for the URL in $thisfn, and if is an encryypted
                   8656: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8657: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8658: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8659: 
1.191     harris41 8660: 
                   8661: =item *
                   8662: 
1.243     albertel 8663: symbclean($symb) : removes versions numbers from a symb, returns the
                   8664: cleaned symb
1.191     harris41 8665: 
                   8666: =item *
                   8667: 
1.243     albertel 8668: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8669: course map, user must be in a course for it to work.
1.191     harris41 8670: 
                   8671: =item *
                   8672: 
1.243     albertel 8673: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8674: 
                   8675: =item *
                   8676: 
1.243     albertel 8677: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8678: a random seed, all arguments are optional, if they aren't sent it uses the
                   8679: environment to derive them. Note: if symb isn't sent and it can't get one
                   8680: from &symbread it will use the current time as its return value
1.191     harris41 8681: 
                   8682: =item *
                   8683: 
1.243     albertel 8684: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8685: unfakeable, receipt
1.191     harris41 8686: 
                   8687: =item *
                   8688: 
1.620     albertel 8689: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8690: 
                   8691: =item *
                   8692: 
1.243     albertel 8693: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8694: 
                   8695: =item *
                   8696: 
1.243     albertel 8697: 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 8698: 
                   8699: =item *
                   8700: 
1.243     albertel 8701: 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 8702: 
                   8703: =item *
                   8704: 
1.243     albertel 8705: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8706: 
                   8707: =item *
                   8708: 
1.243     albertel 8709: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8710: forcing spreadsheet to reevaluate the resource scores next time.
                   8711: 
                   8712: =back
                   8713: 
                   8714: =head2 Storing/Retreiving Data
                   8715: 
                   8716: =over 4
1.191     harris41 8717: 
                   8718: =item *
                   8719: 
1.243     albertel 8720: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8721: for this url; hashref needs to be given and should be a \%hashname; the
                   8722: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8723: be derived from the env
1.191     harris41 8724: 
                   8725: =item *
                   8726: 
1.243     albertel 8727: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8728: uses critical subroutine
1.191     harris41 8729: 
                   8730: =item *
                   8731: 
1.243     albertel 8732: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8733: all args are optional
1.191     harris41 8734: 
                   8735: =item *
                   8736: 
1.717     albertel 8737: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8738: dumps the complete (or key matching regexp) namespace into a hash
                   8739: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8740: normally &store()ed into
                   8741: 
                   8742: $range should be either an integer '100' (give me the first 100
                   8743:                                            matching records)
                   8744:               or be  two integers sperated by a - with no spaces
                   8745:                  '30-50' (give me the 30th through the 50th matching
                   8746:                           records)
                   8747: 
                   8748: 
                   8749: =item *
                   8750: 
                   8751: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8752: replaces a &store() version of data with a replacement set of data
                   8753: for a particular resource in a namespace passed in the $storehash hash 
                   8754: reference
                   8755: 
                   8756: =item *
                   8757: 
1.243     albertel 8758: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8759: works very similar to store/cstore, but all data is stored in a
                   8760: temporary location and can be reset using tmpreset, $storehash should
                   8761: be a hash reference, returns nothing on success
1.191     harris41 8762: 
                   8763: =item *
                   8764: 
1.243     albertel 8765: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8766: similar to restore, but all data is stored in a temporary location and
                   8767: can be reset using tmpreset. Returns a hash of values on success,
                   8768: error string otherwise.
1.191     harris41 8769: 
                   8770: =item *
                   8771: 
1.243     albertel 8772: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8773: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8774: 
                   8775: =item *
                   8776: 
1.243     albertel 8777: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8778: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8779: 
                   8780: =item *
                   8781: 
1.243     albertel 8782: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8783: namesp ($udom and $uname are optional)
1.191     harris41 8784: 
                   8785: =item *
                   8786: 
1.702     albertel 8787: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8788: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8789: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8790: 
1.702     albertel 8791: $range should be either an integer '100' (give me the first 100
                   8792:                                            matching records)
                   8793:               or be  two integers sperated by a - with no spaces
                   8794:                  '30-50' (give me the 30th through the 50th matching
                   8795:                           records)
1.449     matthew  8796: =item *
                   8797: 
                   8798: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8799: $store can be a scalar, an array reference, or if the amount to be 
                   8800: incremented is > 1, a hash reference.
                   8801: 
                   8802: ($udom and $uname are optional)
1.191     harris41 8803: 
                   8804: =item *
                   8805: 
1.243     albertel 8806: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8807: ($udom and $uname are optional)
1.191     harris41 8808: 
                   8809: =item *
                   8810: 
1.243     albertel 8811: cput($namespace,$storehash,$udom,$uname) : critical put
                   8812: ($udom and $uname are optional)
1.191     harris41 8813: 
                   8814: =item *
                   8815: 
1.748     albertel 8816: newput($namespace,$storehash,$udom,$uname) :
                   8817: 
                   8818: Attempts to store the items in the $storehash, but only if they don't
                   8819: currently exist, if this succeeds you can be certain that you have 
                   8820: successfully created a new key value pair in the $namespace db.
                   8821: 
                   8822: 
                   8823: Args:
                   8824:  $namespace: name of database to store values to
                   8825:  $storehash: hashref to store to the db
                   8826:  $udom: (optional) domain of user containing the db
                   8827:  $uname: (optional) name of user caontaining the db
                   8828: 
                   8829: Returns:
                   8830:  'ok' -> succeeded in storing all keys of $storehash
                   8831:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8832:                         least <key> already existed in the db (other
                   8833:                         requested keys may also already exist)
                   8834:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8835:  'con_lost' -> unable to contact request server
                   8836:  'refused' -> action was not allowed by remote machine
                   8837: 
                   8838: 
                   8839: =item *
                   8840: 
1.243     albertel 8841: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8842: reference filled in from namesp (encrypts the return communication)
                   8843: ($udom and $uname are optional)
1.191     harris41 8844: 
                   8845: =item *
                   8846: 
1.243     albertel 8847: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8848: critical subroutine
                   8849: 
1.806     raeburn  8850: =item *
                   8851: 
1.860     raeburn  8852: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   8853: array reference filled in from namespace found in domain level on either
                   8854: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  8855: 
                   8856: =item *
                   8857: 
1.860     raeburn  8858: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   8859: domain level either on specified domain server ($uhome) or primary domain 
                   8860: server ($udom and $uhome are optional)
1.806     raeburn  8861: 
1.243     albertel 8862: =back
                   8863: 
                   8864: =head2 Network Status Functions
                   8865: 
                   8866: =over 4
1.191     harris41 8867: 
                   8868: =item *
                   8869: 
                   8870: dirlist($uri) : return directory list based on URI
                   8871: 
                   8872: =item *
                   8873: 
1.243     albertel 8874: spareserver() : find server with least workload from spare.tab
                   8875: 
                   8876: =back
                   8877: 
                   8878: =head2 Apache Request
                   8879: 
                   8880: =over 4
1.191     harris41 8881: 
                   8882: =item *
                   8883: 
1.243     albertel 8884: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8885: localhost, posts hash
                   8886: 
                   8887: =back
                   8888: 
                   8889: =head2 Data to String to Data
                   8890: 
                   8891: =over 4
1.191     harris41 8892: 
                   8893: =item *
                   8894: 
1.243     albertel 8895: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8896: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8897: 
                   8898: =item *
                   8899: 
1.243     albertel 8900: hashref2str($hashref) : convert a hashref into a string complete with
                   8901: escaping and '=' and '&' separators, supports elements that are
                   8902: arrayrefs and hashrefs
1.191     harris41 8903: 
                   8904: =item *
                   8905: 
1.243     albertel 8906: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8907: with escaping and '&' separators, supports elements that are arrayrefs
                   8908: and hashrefs
1.191     harris41 8909: 
                   8910: =item *
                   8911: 
1.243     albertel 8912: str2hash($string) : convert string to hash using unescaping and
                   8913: splitting on '=' and '&', supports elements that are arrayrefs and
                   8914: hashrefs
1.191     harris41 8915: 
                   8916: =item *
                   8917: 
1.243     albertel 8918: str2array($string) : convert string to hash using unescaping and
                   8919: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8920: 
                   8921: =back
                   8922: 
                   8923: =head2 Logging Routines
                   8924: 
                   8925: =over 4
                   8926: 
                   8927: These routines allow one to make log messages in the lonnet.log and
                   8928: lonnet.perm logfiles.
1.191     harris41 8929: 
                   8930: =item *
                   8931: 
1.243     albertel 8932: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8933: 
                   8934: =item *
                   8935: 
1.243     albertel 8936: logthis() : append message to the normal lonnet.log file, it gets
                   8937: preiodically rolled over and deleted.
1.191     harris41 8938: 
                   8939: =item *
                   8940: 
1.243     albertel 8941: logperm() : append a permanent message to lonnet.perm.log, this log
                   8942: file never gets deleted by any automated portion of the system, only
                   8943: messages of critical importance should go in here.
                   8944: 
                   8945: =back
                   8946: 
                   8947: =head2 General File Helper Routines
                   8948: 
                   8949: =over 4
1.191     harris41 8950: 
                   8951: =item *
                   8952: 
1.481     raeburn  8953: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8954: (a) files in /uploaded
                   8955:   (i) If a local copy of the file exists - 
                   8956:       compares modification date of local copy with last-modified date for 
                   8957:       definitive version stored on home server for course. If local copy is 
                   8958:       stale, requests a new version from the home server and stores it. 
                   8959:       If the original has been removed from the home server, then local copy 
                   8960:       is unlinked.
                   8961:   (ii) If local copy does not exist -
                   8962:       requests the file from the home server and stores it. 
                   8963:   
                   8964:   If $caller is 'uploadrep':  
                   8965:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8966:     for request for files originally uploaded via DOCS. 
                   8967:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8968:   
                   8969:   Otherwise:
                   8970:      This indicates a call from the content generation phase of the request.
                   8971:      -  returns the entire contents of the file or -1.
                   8972:      
                   8973: (b) files in /res
                   8974:    - returns the entire contents of a file or -1; 
                   8975:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8976: 
1.712     albertel 8977: 
                   8978: =item *
                   8979: 
                   8980: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8981:                   reference
                   8982: 
                   8983: returns either a stat() list of data about the file or an empty list
                   8984: if the file doesn't exist or couldn't find out about it (connection
                   8985: problems or user unknown)
                   8986: 
1.191     harris41 8987: =item *
                   8988: 
1.243     albertel 8989: filelocation($dir,$file) : returns file system location of a file
                   8990: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8991: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8992: and a file of ../bob will become /a/bob)
1.191     harris41 8993: 
                   8994: =item *
                   8995: 
                   8996: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8997: filelocation except for hrefs
                   8998: 
                   8999: =item *
                   9000: 
                   9001: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9002: 
1.243     albertel 9003: =back
                   9004: 
1.608     albertel 9005: =head2 Usererfile file routines (/uploaded*)
                   9006: 
                   9007: =over 4
                   9008: 
                   9009: =item *
                   9010: 
                   9011: userfileupload(): main rotine for putting a file in a user or course's
                   9012:                   filespace, arguments are,
                   9013: 
1.620     albertel 9014:  formname - required - this is the name of the element in $env where the
1.608     albertel 9015:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9016:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9017:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9018:  coursedoc - if true, store the file in the course of the active role
                   9019:              of the current user
                   9020:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9021:          if undefined, it will be placed in "unknown"
                   9022: 
                   9023:  (This routine calls clean_filename() to remove any dangerous
                   9024:  characters from the filename, and then calls finuserfileupload() to
                   9025:  complete the transaction)
                   9026: 
                   9027:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9028:  and /adm/notfound.html if unsuccessful
                   9029: 
                   9030: =item *
                   9031: 
                   9032: clean_filename(): routine for cleaing a filename up for storage in
                   9033:                  userfile space, argument is:
                   9034: 
                   9035:  filename - proposed filename
                   9036: 
                   9037: returns: the new clean filename
                   9038: 
                   9039: =item *
                   9040: 
                   9041: finishuserfileupload(): routine that creaes and sends the file to
                   9042: userspace, probably shouldn't be called directly
                   9043: 
                   9044:   docuname: username or courseid of destination for the file
                   9045:   docudom: domain of user/course of destination for the file
                   9046:   formname: same as for userfileupload()
                   9047:   fname: filename (inculding subdirectories) for the file
                   9048: 
                   9049:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9050:  and /adm/notfound.html if unsuccessful
                   9051: 
                   9052: =item *
                   9053: 
                   9054: renameuserfile(): renames an existing userfile to a new name
                   9055: 
                   9056:   Args:
                   9057:    docuname: username or courseid of destination for the file
                   9058:    docudom: domain of user/course of destination for the file
                   9059:    old: current file name (including any subdirs under userfiles)
                   9060:    new: desired file name (including any subdirs under userfiles)
                   9061: 
                   9062: =item *
                   9063: 
                   9064: mkdiruserfile(): creates a directory is a userfiles dir
                   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:    dir: dir to create (including any subdirs under userfiles)
                   9070: 
                   9071: =item *
                   9072: 
                   9073: removeuserfile(): removes a file that exists in userfiles
                   9074: 
                   9075:   Args:
                   9076:    docuname: username or courseid of destination for the file
                   9077:    docudom: domain of user/course of destination for the file
                   9078:    fname: filname to delete (including any subdirs under userfiles)
                   9079: 
                   9080: =item *
                   9081: 
                   9082: removeuploadedurl(): convience function for removeuserfile()
                   9083: 
                   9084:   Args:
                   9085:    url:  a full /uploaded/... url to delete
                   9086: 
1.747     albertel 9087: =item * 
                   9088: 
                   9089: get_portfile_permissions():
                   9090:   Args:
                   9091:     domain: domain of user or course contain the portfolio files
                   9092:     user: name of user or num of course contain the portfolio files
                   9093:   Returns:
                   9094:     hashref of a dump of the proper file_permissions.db
                   9095:    
                   9096: 
                   9097: =item * 
                   9098: 
                   9099: get_access_controls():
                   9100: 
                   9101: Args:
                   9102:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9103:   group: (optional) the group you want the files associated with
                   9104:   file: (optional) the file you want access info on
                   9105: 
                   9106: Returns:
1.749     raeburn  9107:     a hash (keys are file names) of hashes containing
                   9108:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9109:         values are XML containing access control settings (see below) 
1.747     albertel 9110: 
                   9111: Internal notes:
                   9112: 
1.749     raeburn  9113:  access controls are stored in file_permissions.db as key=value pairs.
                   9114:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9115:         where scope -> public,guest,course,group,domains or users.
                   9116:               end -> UNIX time for end of access (0 -> no end date)
                   9117:               start -> UNIX time for start of access
                   9118: 
                   9119:     value -> XML description of access control
                   9120:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9121:             <start></start>
                   9122:             <end></end>
                   9123: 
                   9124:             <password></password>  for scope type = guest
                   9125: 
                   9126:             <domain></domain>     for scope type = course or group
                   9127:             <number></number>
                   9128:             <roles id="">
                   9129:              <role></role>
                   9130:              <access></access>
                   9131:              <section></section>
                   9132:              <group></group>
                   9133:             </roles>
                   9134: 
                   9135:             <dom></dom>         for scope type = domains
                   9136: 
                   9137:             <users>             for scope type = users
                   9138:              <user>
                   9139:               <uname></uname>
                   9140:               <udom></udom>
                   9141:              </user>
                   9142:             </users>
                   9143:            </scope> 
                   9144:               
                   9145:  Access data is also aggregated for each file in an additional key=value pair:
                   9146:  key -> path to file/file_name\0accesscontrol 
                   9147:  value -> reference to hash
                   9148:           hash contains key = value pairs
                   9149:           where key = uniqueID:scope_end_start
                   9150:                 value = UNIX time record was last updated
                   9151: 
                   9152:           Used to improve speed of look-ups of access controls for each file.  
                   9153:  
                   9154:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9155: 
                   9156: modify_access_controls():
                   9157: 
                   9158: Modifies access controls for a portfolio file
                   9159: Args
                   9160: 1. file name
                   9161: 2. reference to hash of required changes,
                   9162: 3. domain
                   9163: 4. username
                   9164:   where domain,username are the domain of the portfolio owner 
                   9165:   (either a user or a course) 
                   9166: 
                   9167: Returns:
                   9168: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9169: 2. result of deletions ('ok' or 'error', with error message).
                   9170: 3. reference to hash of any new or updated access controls.
                   9171: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9172:    key = integer (inbound ID)
                   9173:    value = uniqueID  
1.747     albertel 9174: 
1.608     albertel 9175: =back
                   9176: 
1.243     albertel 9177: =head2 HTTP Helper Routines
                   9178: 
                   9179: =over 4
                   9180: 
1.191     harris41 9181: =item *
                   9182: 
                   9183: escape() : unpack non-word characters into CGI-compatible hex codes
                   9184: 
                   9185: =item *
                   9186: 
                   9187: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9188: 
1.243     albertel 9189: =back
                   9190: 
                   9191: =head1 PRIVATE SUBROUTINES
                   9192: 
                   9193: =head2 Underlying communication routines (Shouldn't call)
                   9194: 
                   9195: =over 4
                   9196: 
                   9197: =item *
                   9198: 
                   9199: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9200: 
                   9201: =item *
                   9202: 
                   9203: reply() : uses subreply to send a message to remote machine, logs all failures
                   9204: 
                   9205: =item *
                   9206: 
                   9207: critical() : passes a critical message to another server; if cannot
                   9208: get through then place message in connection buffer directory and
                   9209: returns con_delayed, if incapable of saving message, returns
                   9210: con_failed
                   9211: 
                   9212: =item *
                   9213: 
                   9214: reconlonc() : tries to reconnect lonc client processes.
                   9215: 
                   9216: =back
                   9217: 
                   9218: =head2 Resource Access Logging
                   9219: 
                   9220: =over 4
                   9221: 
                   9222: =item *
                   9223: 
                   9224: flushcourselogs() : flush (save) buffer logs and access logs
                   9225: 
                   9226: =item *
                   9227: 
                   9228: courselog($what) : save message for course in hash
                   9229: 
                   9230: =item *
                   9231: 
                   9232: courseacclog($what) : save message for course using &courselog().  Perform
                   9233: special processing for specific resource types (problems, exams, quizzes, etc).
                   9234: 
1.191     harris41 9235: =item *
                   9236: 
                   9237: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9238: as a PerlChildExitHandler
1.243     albertel 9239: 
                   9240: =back
                   9241: 
                   9242: =head2 Other
                   9243: 
                   9244: =over 4
                   9245: 
                   9246: =item *
                   9247: 
                   9248: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9249: 
                   9250: =back
                   9251: 
                   9252: =cut
1.877     foxr     9253: 

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