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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.915   ! albertel    4: # $Id: lonnet.pm,v 1.914 2007/09/29 04:03:51 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.891     albertel  217:     my ($lonid) = @_;
                    218:     my $hostname = &hostname($lonid);
                    219:     if ($lonid) {
                    220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    221: 	if ($hostname && -e $peerfile) {
                    222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    224: 					     Type    => SOCK_STREAM,
                    225: 					     Timeout => 10);
                    226: 	    if ($client) {
                    227: 		print $client ("reset_retries\n");
                    228: 		my $answer=<$client>;
                    229: 		#reset just this one.
                    230: 	    }
                    231: 	}
                    232: 	return;
                    233:     }
                    234: 
1.836     www       235:     &logthis("Trying to reconnect lonc");
1.1       albertel  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  237:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  238: 	my $loncpid=<$fh>;
                    239:         chomp($loncpid);
                    240:         if (kill 0 => $loncpid) {
                    241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    242:             kill USR1 => $loncpid;
                    243:             sleep 1;
1.836     www       244:          } else {
1.12      www       245: 	    &logthis(
1.672     albertel  246:                "<font color=\"blue\">WARNING:".
1.12      www       247:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  248:         }
                    249:     } else {
1.836     www       250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  251:     }
                    252: }
                    253: 
                    254: # ------------------------------------------------------ Critical communication
1.12      www       255: 
1.1       albertel  256: sub critical {
                    257:     my ($cmd,$server)=@_;
1.838     albertel  258:     unless (&hostname($server)) {
1.672     albertel  259:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       260:                " Critical message to unknown server ($server)</font>");
                    261:         return 'no_such_host';
                    262:     }
1.1       albertel  263:     my $answer=reply($cmd,$server);
                    264:     if ($answer eq 'con_lost') {
                    265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  266: 	my $answer=reply($cmd,$server);
1.1       albertel  267:         if ($answer eq 'con_lost') {
                    268:             my $now=time;
                    269:             my $middlename=$cmd;
1.5       www       270:             $middlename=substr($middlename,0,16);
1.1       albertel  271:             $middlename=~s/\W//g;
                    272:             my $dfilename=
1.305     www       273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    274:             $dumpcount++;
1.1       albertel  275:             {
1.448     albertel  276: 		my $dfh;
                    277: 		if (open($dfh,">$dfilename")) {
                    278: 		    print $dfh "$cmd\n"; 
                    279: 		    close($dfh);
                    280: 		}
1.1       albertel  281:             }
                    282:             sleep 2;
                    283:             my $wcmd='';
                    284:             {
1.448     albertel  285: 		my $dfh;
                    286: 		if (open($dfh,"<$dfilename")) {
                    287: 		    $wcmd=<$dfh>; 
                    288: 		    close($dfh);
                    289: 		}
1.1       albertel  290:             }
                    291:             chomp($wcmd);
1.7       www       292:             if ($wcmd eq $cmd) {
1.672     albertel  293: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       294:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  295:                 &logperm("D:$server:$cmd");
                    296: 	        return 'con_delayed';
                    297:             } else {
1.672     albertel  298:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       299:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  300:                 &logperm("F:$server:$cmd");
                    301:                 return 'con_failed';
                    302:             }
                    303:         }
                    304:     }
                    305:     return $answer;
1.405     albertel  306: }
                    307: 
1.755     albertel  308: # ------------------------------------------- check if return value is an error
                    309: 
                    310: sub error {
                    311:     my ($result) = @_;
1.756     albertel  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  313: 	if ($2 == 2) { return undef; }
                    314: 	return $1;
                    315:     }
                    316:     return undef;
                    317: }
                    318: 
1.783     albertel  319: sub convert_and_load_session_env {
                    320:     my ($lonidsdir,$handle)=@_;
                    321:     my @profile;
                    322:     {
1.915   ! albertel  323: 	open(my $idf,'+<',"$lonidsdir/$handle.id");
        !           324: 	if (!$idf) {
        !           325: 	    return 0;
        !           326: 	}
1.783     albertel  327: 	flock($idf,LOCK_SH);
                    328: 	@profile=<$idf>;
                    329: 	close($idf);
                    330:     }
                    331:     my %temp_env;
                    332:     foreach my $line (@profile) {
1.786     albertel  333: 	if ($line !~ m/=/) {
                    334: 	    return 0;
                    335: 	}
1.783     albertel  336: 	chomp($line);
                    337: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    338: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    339:     }
                    340:     unlink("$lonidsdir/$handle.id");
                    341:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    342: 	    0640)) {
                    343: 	%disk_env = %temp_env;
                    344: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    345: 	untie(%disk_env);
                    346:     }
1.786     albertel  347:     return 1;
1.783     albertel  348: }
                    349: 
1.374     www       350: # ------------------------------------------- Transfer profile into environment
1.780     albertel  351: my $env_loaded;
                    352: sub transfer_profile_to_env {
1.788     albertel  353:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    354:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       355: 
1.720     albertel  356:     if (!defined($lonidsdir)) {
                    357: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    358:     }
                    359:     if (!defined($handle)) {
                    360:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    361:     }
                    362: 
1.786     albertel  363:     my $convert;
                    364:     {
1.915   ! albertel  365:     	open(my $idf,'+<',"$lonidsdir/$handle.id");
        !           366: 	if (!$idf) {
        !           367: 	    return;
        !           368: 	}
1.786     albertel  369: 	flock($idf,LOCK_SH);
                    370: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    371: 		&GDBM_READER(),0640)) {
                    372: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    373: 	    untie(%disk_env);
                    374: 	} else {
                    375: 	    $convert = 1;
                    376: 	}
                    377:     }
                    378:     if ($convert) {
                    379: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    380: 	    &logthis("Failed to load session, or convert session.");
                    381: 	}
1.374     www       382:     }
1.783     albertel  383: 
1.786     albertel  384:     my %remove;
1.783     albertel  385:     while ( my $envname = each(%env) ) {
1.433     matthew   386:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    387:             if ($time < time-300) {
1.783     albertel  388:                 $remove{$key}++;
1.433     matthew   389:             }
                    390:         }
                    391:     }
1.783     albertel  392: 
1.619     albertel  393:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  394:     $env_loaded=1;
1.783     albertel  395:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   396:         &delenv($expired_key);
1.374     www       397:     }
1.1       albertel  398: }
                    399: 
1.830     albertel  400: sub timed_flock {
                    401:     my ($file,$lock_type) = @_;
                    402:     my $failed=0;
                    403:     eval {
                    404: 	local $SIG{__DIE__}='DEFAULT';
                    405: 	local $SIG{ALRM}=sub {
                    406: 	    $failed=1;
                    407: 	    die("failed lock");
                    408: 	};
                    409: 	alarm(13);
                    410: 	flock($file,$lock_type);
                    411: 	alarm(0);
                    412:     };
                    413:     if ($failed) {
                    414: 	return undef;
                    415:     } else {
                    416: 	return 1;
                    417:     }
                    418: }
                    419: 
1.5       www       420: # ---------------------------------------------------------- Append Environment
                    421: 
                    422: sub appenv {
1.6       www       423:     my %newenv=@_;
1.692     albertel  424:     foreach my $key (keys(%newenv)) {
                    425: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  426:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  427:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       428:                 .'</font>');
1.692     albertel  429: 	    delete($newenv{$key});
1.35      www       430:         } else {
1.692     albertel  431:             $env{$key}=$newenv{$key};
1.35      www       432:         }
1.191     harris41  433:     }
1.915   ! albertel  434:     open(my $env_file,'+<',$env{'user.environment'});
        !           435:     if ($env_file
        !           436: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  437: 	&&
                    438: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    439: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  440: 	while (my ($key,$value) = each(%newenv)) {
                    441: 	    $disk_env{$key} = $value;
1.448     albertel  442: 	}
1.783     albertel  443: 	untie(%disk_env);
1.56      www       444:     }
                    445:     return 'ok';
                    446: }
                    447: # ----------------------------------------------------- Delete from Environment
                    448: 
                    449: sub delenv {
                    450:     my $delthis=shift;
                    451:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  452:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       453:                 "Attempt to delete from environment ".$delthis);
                    454:         return 'error';
                    455:     }
1.915   ! albertel  456:     open(my $env_file,'+<',$env{'user.environment'});
        !           457:     if ($env_file
        !           458: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  459: 	&&
                    460: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    461: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  462: 	foreach my $key (keys(%disk_env)) {
                    463: 	    if ($key=~/^$delthis/) { 
1.915   ! albertel  464: 		delete($env{$key});
        !           465: 		delete($disk_env{$key});
        !           466: 	    }
1.448     albertel  467: 	}
1.783     albertel  468: 	untie(%disk_env);
1.5       www       469:     }
                    470:     return 'ok';
1.369     albertel  471: }
                    472: 
1.790     albertel  473: sub get_env_multiple {
                    474:     my ($name) = @_;
                    475:     my @values;
                    476:     if (defined($env{$name})) {
                    477:         # exists is it an array
                    478:         if (ref($env{$name})) {
                    479:             @values=@{ $env{$name} };
                    480:         } else {
                    481:             $values[0]=$env{$name};
                    482:         }
                    483:     }
                    484:     return(@values);
                    485: }
                    486: 
1.369     albertel  487: # ------------------------------------------ Find out current server userload
                    488: # there is a copy in lond
                    489: sub userload {
                    490:     my $numusers=0;
                    491:     {
                    492: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    493: 	my $filename;
                    494: 	my $curtime=time;
                    495: 	while ($filename=readdir(LONIDS)) {
                    496: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  497: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  498: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  499: 	}
                    500: 	closedir(LONIDS);
                    501:     }
                    502:     my $userloadpercent=0;
                    503:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    504:     if ($maxuserload) {
1.371     albertel  505: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  506:     }
1.372     albertel  507:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  508:     return $userloadpercent;
1.283     www       509: }
                    510: 
                    511: # ------------------------------------------ Fight off request when overloaded
                    512: 
                    513: sub overloaderror {
                    514:     my ($r,$checkserver)=@_;
                    515:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    516:     my $loadavg;
                    517:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  518:        open(my $loadfile,'/proc/loadavg');
1.283     www       519:        $loadavg=<$loadfile>;
                    520:        $loadavg =~ s/\s.*//g;
1.285     matthew   521:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  522:        close($loadfile);
1.283     www       523:     } else {
                    524:        $loadavg=&reply('load',$checkserver);
                    525:     }
1.285     matthew   526:     my $overload=$loadavg-100;
1.283     www       527:     if ($overload>0) {
1.285     matthew   528: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       529:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       530:         return 413;
1.283     www       531:     }    
                    532:     return '';
1.5       www       533: }
1.1       albertel  534: 
                    535: # ------------------------------ Find server with least workload from spare.tab
1.11      www       536: 
1.1       albertel  537: sub spareserver {
1.670     albertel  538:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  539:     my $spare_server;
1.370     albertel  540:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  541:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    542:                                                      :  $userloadpercent;
                    543:     
                    544:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    545: 	($spare_server, $lowest_load) =
                    546: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    547:     }
                    548: 
                    549:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    550: 
                    551:     if (!$found_server) {
                    552: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    553: 	    ($spare_server, $lowest_load) =
                    554: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    555: 	}
                    556:     }
                    557: 
                    558:     if (!$want_server_name) {
1.838     albertel  559: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  560:     }
                    561:     return $spare_server;
                    562: }
                    563: 
                    564: sub compare_server_load {
                    565:     my ($try_server, $spare_server, $lowest_load) = @_;
                    566: 
                    567:     my $loadans     = &reply('load',    $try_server);
                    568:     my $userloadans = &reply('userload',$try_server);
                    569: 
                    570:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    571: 	next; #didn't get a number from the server
                    572:     }
                    573: 
                    574:     my $load;
                    575:     if ($loadans =~ /\d/) {
                    576: 	if ($userloadans =~ /\d/) {
                    577: 	    #both are numbers, pick the bigger one
                    578: 	    $load = ($loadans > $userloadans) ? $loadans 
                    579: 		                              : $userloadans;
1.411     albertel  580: 	} else {
1.784     albertel  581: 	    $load = $loadans;
1.411     albertel  582: 	}
1.784     albertel  583:     } else {
                    584: 	$load = $userloadans;
                    585:     }
                    586: 
                    587:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    588: 	$spare_server = $try_server;
                    589: 	$lowest_load  = $load;
1.370     albertel  590:     }
1.784     albertel  591:     return ($spare_server,$lowest_load);
1.202     matthew   592: }
1.914     albertel  593: 
                    594: # --------------------------- ask offload servers if user already has a session
                    595: sub find_existing_session {
                    596:     my ($udom,$uname) = @_;
                    597:     foreach my $try_server (@{ $spareid{'primary'} },
                    598: 			    @{ $spareid{'default'} }) {
                    599: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    600:     }
                    601:     return;
                    602: }
                    603: 
                    604: # -------------------------------- ask if server already has a session for user
                    605: sub has_user_session {
                    606:     my ($lonid,$udom,$uname) = @_;
                    607:     my $result = &reply(join(':','userhassession',
                    608: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    609:     return 1 if ($result eq 'ok');
                    610: 
                    611:     return 0;
                    612: }
                    613: 
1.202     matthew   614: # --------------------------------------------- Try to change a user's password
                    615: 
                    616: sub changepass {
1.799     raeburn   617:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   618:     $currentpass = &escape($currentpass);
                    619:     $newpass     = &escape($newpass);
1.799     raeburn   620:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   621: 		       $server);
                    622:     if (! $answer) {
                    623: 	&logthis("No reply on password change request to $server ".
                    624: 		 "by $uname in domain $udom.");
                    625:     } elsif ($answer =~ "^ok") {
                    626:         &logthis("$uname in $udom successfully changed their password ".
                    627: 		 "on $server.");
                    628:     } elsif ($answer =~ "^pwchange_failure") {
                    629: 	&logthis("$uname in $udom was unable to change their password ".
                    630: 		 "on $server.  The action was blocked by either lcpasswd ".
                    631: 		 "or pwchange");
                    632:     } elsif ($answer =~ "^non_authorized") {
                    633:         &logthis("$uname in $udom did not get their password correct when ".
                    634: 		 "attempting to change it on $server.");
                    635:     } elsif ($answer =~ "^auth_mode_error") {
                    636:         &logthis("$uname in $udom attempted to change their password despite ".
                    637: 		 "not being locally or internally authenticated on $server.");
                    638:     } elsif ($answer =~ "^unknown_user") {
                    639:         &logthis("$uname in $udom attempted to change their password ".
                    640: 		 "on $server but were unable to because $server is not ".
                    641: 		 "their home server.");
                    642:     } elsif ($answer =~ "^refused") {
                    643: 	&logthis("$server refused to change $uname in $udom password because ".
                    644: 		 "it was sent an unencrypted request to change the password.");
                    645:     }
                    646:     return $answer;
1.1       albertel  647: }
                    648: 
1.169     harris41  649: # ----------------------- Try to determine user's current authentication scheme
                    650: 
                    651: sub queryauthenticate {
                    652:     my ($uname,$udom)=@_;
1.456     albertel  653:     my $uhome=&homeserver($uname,$udom);
                    654:     if (!$uhome) {
                    655: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    656: 	return 'no_host';
                    657:     }
                    658:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    659:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    660: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  661:     }
1.456     albertel  662:     return $answer;
1.169     harris41  663: }
                    664: 
1.1       albertel  665: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       666: 
1.1       albertel  667: sub authenticate {
                    668:     my ($uname,$upass,$udom)=@_;
1.807     albertel  669:     $upass=&escape($upass);
                    670:     $uname= &LONCAPA::clean_username($uname);
1.836     www       671:     my $uhome=&homeserver($uname,$udom,1);
                    672:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    673: # Maybe the machine was offline and only re-appeared again recently?
                    674:         &reconlonc();
                    675: # One more
                    676: 	my $uhome=&homeserver($uname,$udom,1);
                    677: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    678: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    679: 	}
1.471     albertel  680: 	return 'no_host';
1.1       albertel  681:     }
1.471     albertel  682:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    683:     if ($answer eq 'authorized') {
                    684: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    685: 	return $uhome; 
                    686:     }
                    687:     if ($answer eq 'non_authorized') {
                    688: 	&logthis("User $uname at $udom rejected by $uhome");
                    689: 	return 'no_host'; 
1.9       www       690:     }
1.471     albertel  691:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  692:     return 'no_host';
                    693: }
                    694: 
                    695: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       696: 
1.599     albertel  697: my %homecache;
1.1       albertel  698: sub homeserver {
1.230     stredwic  699:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  700:     my $index="$uname:$udom";
1.426     albertel  701: 
1.599     albertel  702:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  703: 
                    704:     my %servers = &get_servers($udom,'library');
                    705:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  706:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  707: 		 exists($badServerCache{$tryserver}));
1.841     albertel  708: 
                    709: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    710: 	if ($answer eq 'found') {
                    711: 	    delete($badServerCache{$tryserver}); 
                    712: 	    return $homecache{$index}=$tryserver;
                    713: 	} elsif ($answer eq 'no_host') {
                    714: 	    $badServerCache{$tryserver}=1;
                    715: 	}
1.1       albertel  716:     }    
                    717:     return 'no_host';
1.70      www       718: }
                    719: 
                    720: # ------------------------------------- Find the usernames behind a list of IDs
                    721: 
                    722: sub idget {
                    723:     my ($udom,@ids)=@_;
                    724:     my %returnhash=();
                    725:     
1.841     albertel  726:     my %servers = &get_servers($udom,'library');
                    727:     foreach my $tryserver (keys(%servers)) {
                    728: 	my $idlist=join('&',@ids);
                    729: 	$idlist=~tr/A-Z/a-z/; 
                    730: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    731: 	my @answer=();
                    732: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    733: 	    @answer=split(/\&/,$reply);
                    734: 	}                    ;
                    735: 	my $i;
                    736: 	for ($i=0;$i<=$#ids;$i++) {
                    737: 	    if ($answer[$i]) {
                    738: 		$returnhash{$ids[$i]}=$answer[$i];
                    739: 	    } 
                    740: 	}
                    741:     } 
1.70      www       742:     return %returnhash;
                    743: }
                    744: 
                    745: # ------------------------------------- Find the IDs behind a list of usernames
                    746: 
                    747: sub idrget {
                    748:     my ($udom,@unames)=@_;
                    749:     my %returnhash=();
1.800     albertel  750:     foreach my $uname (@unames) {
                    751:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  752:     }
1.70      www       753:     return %returnhash;
                    754: }
                    755: 
                    756: # ------------------------------- Store away a list of names and associated IDs
                    757: 
                    758: sub idput {
                    759:     my ($udom,%ids)=@_;
                    760:     my %servers=();
1.800     albertel  761:     foreach my $uname (keys(%ids)) {
                    762: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    763:         my $uhom=&homeserver($uname,$udom);
1.70      www       764:         if ($uhom ne 'no_host') {
1.800     albertel  765:             my $id=&escape($ids{$uname});
1.70      www       766:             $id=~tr/A-Z/a-z/;
1.800     albertel  767:             my $esc_unam=&escape($uname);
1.70      www       768: 	    if ($servers{$uhom}) {
1.800     albertel  769: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       770:             } else {
1.800     albertel  771:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       772:             }
                    773:         }
1.191     harris41  774:     }
1.800     albertel  775:     foreach my $server (keys(%servers)) {
                    776:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  777:     }
1.344     www       778: }
                    779: 
1.806     raeburn   780: # ------------------------------------------- get items from domain db files   
                    781: 
                    782: sub get_dom {
1.860     raeburn   783:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   784:     my $items='';
                    785:     foreach my $item (@$storearr) {
                    786:         $items.=&escape($item).'&';
                    787:     }
                    788:     $items=~s/\&$//;
1.860     raeburn   789:     if (!$udom) {
                    790:         $udom=$env{'user.domain'};
                    791:         if (defined(&domain($udom,'primary'))) {
                    792:             $uhome=&domain($udom,'primary');
                    793:         } else {
1.874     albertel  794:             undef($uhome);
1.860     raeburn   795:         }
                    796:     } else {
                    797:         if (!$uhome) {
                    798:             if (defined(&domain($udom,'primary'))) {
                    799:                 $uhome=&domain($udom,'primary');
                    800:             }
                    801:         }
                    802:     }
                    803:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   804:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   805:         my %returnhash;
1.875     albertel  806:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   807:             return %returnhash;
                    808:         }
1.806     raeburn   809:         my @pairs=split(/\&/,$rep);
                    810:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    811:             return @pairs;
                    812:         }
                    813:         my $i=0;
                    814:         foreach my $item (@$storearr) {
                    815:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    816:             $i++;
                    817:         }
                    818:         return %returnhash;
                    819:     } else {
1.880     banghart  820:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   821:     }
                    822: }
                    823: 
                    824: # -------------------------------------------- put items in domain db files 
                    825: 
                    826: sub put_dom {
1.860     raeburn   827:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    828:     if (!$udom) {
                    829:         $udom=$env{'user.domain'};
                    830:         if (defined(&domain($udom,'primary'))) {
                    831:             $uhome=&domain($udom,'primary');
                    832:         } else {
1.874     albertel  833:             undef($uhome);
1.860     raeburn   834:         }
                    835:     } else {
                    836:         if (!$uhome) {
                    837:             if (defined(&domain($udom,'primary'))) {
                    838:                 $uhome=&domain($udom,'primary');
                    839:             }
                    840:         }
                    841:     } 
                    842:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   843:         my $items='';
                    844:         foreach my $item (keys(%$storehash)) {
                    845:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    846:         }
                    847:         $items=~s/\&$//;
                    848:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    849:     } else {
1.860     raeburn   850:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   851:     }
                    852: }
                    853: 
1.837     raeburn   854: sub retrieve_inst_usertypes {
                    855:     my ($udom) = @_;
                    856:     my (%returnhash,@order);
1.846     albertel  857:     if (defined(&domain($udom,'primary'))) {
                    858:         my $uhome=&domain($udom,'primary');
1.837     raeburn   859:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    860:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    861:         my @pairs=split(/\&/,$hashitems);
                    862:         foreach my $item (@pairs) {
                    863:             my ($key,$value)=split(/=/,$item,2);
                    864:             $key = &unescape($key);
                    865:             next if ($key =~ /^error: 2 /);
                    866:             $returnhash{$key}=&thaw_unescape($value);
                    867:         }
                    868:         my @esc_order = split(/\&/,$orderitems);
                    869:         foreach my $item (@esc_order) {
                    870:             push(@order,&unescape($item));
                    871:         }
                    872:     } else {
                    873:         &logthis("get_dom failed - no primary domain server for $udom");
                    874:     }
                    875:     return (\%returnhash,\@order);
                    876: }
                    877: 
1.868     raeburn   878: sub is_domainimage {
                    879:     my ($url) = @_;
                    880:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    881:         if (&domain($1) ne '') {
                    882:             return '1';
                    883:         }
                    884:     }
                    885:     return;
                    886: }
                    887: 
1.899     raeburn   888: sub inst_directory_query {
                    889:     my ($srch) = @_;
                    890:     my $udom = $srch->{'srchdomain'};
                    891:     my %results;
                    892:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   893:     my $outcome;
1.899     raeburn   894:     if ($homeserver ne '') {
1.904     albertel  895: 	my $queryid=&reply("querysend:instdirsearch:".
                    896: 			   &escape($srch->{'srchby'}).':'.
                    897: 			   &escape($srch->{'srchterm'}).':'.
                    898: 			   &escape($srch->{'srchtype'}),$homeserver);
                    899: 	my $host=&hostname($homeserver);
                    900: 	if ($queryid !~/^\Q$host\E\_/) {
                    901: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    902: 	    return;
                    903: 	}
                    904: 	my $response = &get_query_reply($queryid);
                    905: 	my $maxtries = 5;
                    906: 	my $tries = 1;
                    907: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    908: 	    $response = &get_query_reply($queryid);
                    909: 	    $tries ++;
                    910: 	}
                    911: 
                    912:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn   913:             if ($response eq 'unavailable') {
                    914:                 $outcome = $response;
                    915:             } else {
                    916:                 $outcome = 'ok';
                    917:                 my @matches = split(/\n/,$response);
                    918:                 foreach my $match (@matches) {
                    919:                     my ($key,$value) = split(/=/,$match);
                    920:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                    921:                 }
1.899     raeburn   922:             }
                    923:         }
                    924:     }
1.909     raeburn   925:     return ($outcome,%results);
1.899     raeburn   926: }
                    927: 
                    928: sub usersearch {
                    929:     my ($srch) = @_;
                    930:     my $dom = $srch->{'srchdomain'};
                    931:     my %results;
                    932:     my %libserv = &all_library();
                    933:     my $query = 'usersearch';
                    934:     foreach my $tryserver (keys(%libserv)) {
                    935:         if (&host_domain($tryserver) eq $dom) {
                    936:             my $host=&hostname($tryserver);
                    937:             my $queryid=
1.911     raeburn   938:                 &reply("querysend:".&escape($query).':'.
                    939:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn   940:                        &escape($srch->{'srchtype'}).':'.
                    941:                        &escape($srch->{'srchterm'}),$tryserver);
                    942:             if ($queryid !~/^\Q$host\E\_/) {
                    943:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   944:                 next;
1.899     raeburn   945:             }
                    946:             my $reply = &get_query_reply($queryid);
                    947:             my $maxtries = 1;
                    948:             my $tries = 1;
                    949:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    950:                 $reply = &get_query_reply($queryid);
                    951:                 $tries ++;
                    952:             }
                    953:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    954:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    955:             } else {
1.911     raeburn   956:                 my @matches;
                    957:                 if ($reply =~ /\n/) {
                    958:                     @matches = split(/\n/,$reply);
                    959:                 } else {
                    960:                     @matches = split(/\&/,$reply);
                    961:                 }
1.899     raeburn   962:                 foreach my $match (@matches) {
                    963:                     my ($uname,$udom,%userhash);
1.911     raeburn   964:                     foreach my $entry (split(/:/,$match)) {
                    965:                         my ($key,$value) =
                    966:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn   967:                         $userhash{$key} = $value;
                    968:                         if ($key eq 'username') {
                    969:                             $uname = $value;
                    970:                         } elsif ($key eq 'domain') {
                    971:                             $udom = $value;
1.911     raeburn   972:                         }
1.899     raeburn   973:                     }
                    974:                     $results{$uname.':'.$udom} = \%userhash;
                    975:                 }
                    976:             }
                    977:         }
                    978:     }
                    979:     return %results;
                    980: }
                    981: 
1.912     raeburn   982: sub get_instuser {
                    983:     my ($udom,$uname,$id) = @_;
                    984:     my $homeserver = &domain($udom,'primary');
                    985:     my ($outcome,%results);
                    986:     if ($homeserver ne '') {
                    987:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                    988:                            &escape($id).':'.&escape($udom),$homeserver);
                    989:         my $host=&hostname($homeserver);
                    990:         if ($queryid !~/^\Q$host\E\_/) {
                    991:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    992:             return;
                    993:         }
                    994:         my $response = &get_query_reply($queryid);
                    995:         my $maxtries = 5;
                    996:         my $tries = 1;
                    997:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    998:             $response = &get_query_reply($queryid);
                    999:             $tries ++;
                   1000:         }
                   1001:         if (!&error($response) && $response ne 'refused') {
                   1002:             if ($response eq 'unavailable') {
                   1003:                 $outcome = $response;
                   1004:             } else {
                   1005:                 $outcome = 'ok';
                   1006:                 my @matches = split(/\n/,$response);
                   1007:                 foreach my $match (@matches) {
                   1008:                     my ($key,$value) = split(/=/,$match);
                   1009:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1010:                 }
                   1011:             }
                   1012:         }
                   1013:     }
                   1014:     my %userinfo;
                   1015:     if (ref($results{$uname}) eq 'HASH') {
                   1016:         %userinfo = %{$results{$uname}};
                   1017:     } 
                   1018:     return ($outcome,%userinfo);
                   1019: }
                   1020: 
                   1021: sub inst_rulecheck {
                   1022:     my ($udom,$uname,$rules) = @_;
                   1023:     my %returnhash;
                   1024:     if ($udom ne '') {
                   1025:         if (ref($rules) eq 'ARRAY') {
                   1026:             @{$rules} = map {&escape($_);} (@{$rules});
                   1027:             my $rulestr = join(':',@{$rules});
                   1028:             my $homeserver=&domain($udom,'primary');
                   1029:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
                   1030:                 my $response=&unescape(&reply('instrulecheck:'.&escape($udom).':'.
                   1031:                                               &escape($uname).':'.$rulestr,
                   1032:                                               $homeserver));
                   1033:                 if ($response ne 'refused') {
                   1034:                     my @pairs=split(/\&/,$response);
                   1035:                     foreach my $item (@pairs) {
                   1036:                         my ($key,$value)=split(/=/,$item,2);
                   1037:                         $key = &unescape($key);
                   1038:                         next if ($key =~ /^error: 2 /);
                   1039:                         $returnhash{$key}=&thaw_unescape($value);
                   1040:                     }
                   1041:                 }
                   1042:             }
                   1043:         }
                   1044:     }
                   1045:     return %returnhash;
                   1046: }
                   1047: 
                   1048: sub inst_userrules {
                   1049:     my ($udom) = @_;
                   1050:     my (%ruleshash,@ruleorder);
                   1051:     if ($udom ne '') {
                   1052:         my $homeserver=&domain($udom,'primary');
                   1053:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
                   1054:             my $response=&reply('instuserrules:'.&escape($udom),
                   1055:                                  $homeserver);
                   1056:             if (($response ne 'refused') && ($response ne 'error') && 
                   1057:                 ($response ne 'no_such_host')) {
                   1058:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1059:                 my @pairs=split(/\&/,$hashitems);
                   1060:                 foreach my $item (@pairs) {
                   1061:                     my ($key,$value)=split(/=/,$item,2);
                   1062:                     $key = &unescape($key);
                   1063:                     next if ($key =~ /^error: 2 /);
                   1064:                     $ruleshash{$key}=&thaw_unescape($value);
                   1065:                 }
                   1066:                 my @esc_order = split(/\&/,$orderitems);
                   1067:                 foreach my $item (@esc_order) {
                   1068:                     push(@ruleorder,&unescape($item));
                   1069:                 }
                   1070:             }
                   1071:         }
                   1072:     }
                   1073:     return (\%ruleshash,\@ruleorder);
                   1074: }
                   1075: 
1.344     www      1076: # --------------------------------------------------- Assign a key to a student
                   1077: 
                   1078: sub assign_access_key {
1.364     www      1079: #
                   1080: # a valid key looks like uname:udom#comments
                   1081: # comments are being appended
                   1082: #
1.498     www      1083:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1084:     $kdom=
1.620     albertel 1085:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1086:     $knum=
1.620     albertel 1087:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1088:     $cdom=
1.620     albertel 1089:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1090:     $cnum=
1.620     albertel 1091:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1092:     $udom=$env{'user.name'} unless (defined($udom));
                   1093:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1094:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1095:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1096:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1097:                                                   # assigned to this person
                   1098:                                                   # - this should not happen,
1.345     www      1099:                                                   # unless something went wrong
                   1100:                                                   # the first time around
                   1101: # ready to assign
1.364     www      1102:         $logentry=$1.'; '.$logentry;
1.496     www      1103:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1104:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1105: # key now belongs to user
1.346     www      1106: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1107:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                   1108:                 &appenv('environment.'.$envkey => $ckey);
                   1109:                 return 'ok';
                   1110:             } else {
                   1111:                 return 
                   1112:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1113: 	    }
                   1114:         } else {
                   1115:             return 'error: Could not assign key, try again later.';
                   1116:         }
1.364     www      1117:     } elsif (!$existing{$ckey}) {
1.345     www      1118: # the key does not exist
                   1119: 	return 'error: The key does not exist';
                   1120:     } else {
                   1121: # the key is somebody else's
                   1122: 	return 'error: The key is already in use';
                   1123:     }
1.344     www      1124: }
                   1125: 
1.364     www      1126: # ------------------------------------------ put an additional comment on a key
                   1127: 
                   1128: sub comment_access_key {
                   1129: #
                   1130: # a valid key looks like uname:udom#comments
                   1131: # comments are being appended
                   1132: #
                   1133:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1134:     $cdom=
1.620     albertel 1135:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1136:     $cnum=
1.620     albertel 1137:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1138:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1139:     if ($existing{$ckey}) {
                   1140:         $existing{$ckey}.='; '.$logentry;
                   1141: # ready to assign
1.367     www      1142:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1143:                                                  $cdom,$cnum) eq 'ok') {
                   1144: 	    return 'ok';
                   1145:         } else {
                   1146: 	    return 'error: Count not store comment.';
                   1147:         }
                   1148:     } else {
                   1149: # the key does not exist
                   1150: 	return 'error: The key does not exist';
                   1151:     }
                   1152: }
                   1153: 
1.344     www      1154: # ------------------------------------------------------ Generate a set of keys
                   1155: 
                   1156: sub generate_access_keys {
1.364     www      1157:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1158:     $cdom=
1.620     albertel 1159:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1160:     $cnum=
1.620     albertel 1161:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1162:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1163:     unless (($cdom) && ($cnum)) { return 0; }
                   1164:     if ($number>10000) { return 0; }
                   1165:     sleep(2); # make sure don't get same seed twice
                   1166:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1167:     my $total=0;
                   1168:     for (my $i=1;$i<=$number;$i++) {
                   1169:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1170:                   sprintf("%lx",int(100000*rand)).'-'.
                   1171:                   sprintf("%lx",int(100000*rand));
                   1172:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1173:        $newkey=~s/0/h/g; # and also 0 and O
                   1174:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1175:        if ($existing{$newkey}) {
                   1176:            $i--;
                   1177:        } else {
1.364     www      1178: 	  if (&put('accesskeys',
                   1179:               { $newkey => '# generated '.localtime().
1.620     albertel 1180:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1181:                            '; '.$logentry },
                   1182: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1183:               $total++;
                   1184: 	  }
                   1185:        }
                   1186:     }
1.620     albertel 1187:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1188:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1189:     return $total;
                   1190: }
                   1191: 
                   1192: # ------------------------------------------------------- Validate an accesskey
                   1193: 
                   1194: sub validate_access_key {
                   1195:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1196:     $cdom=
1.620     albertel 1197:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1198:     $cnum=
1.620     albertel 1199:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1200:     $udom=$env{'user.domain'} unless (defined($udom));
                   1201:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1202:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1203:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1204: }
                   1205: 
                   1206: # ------------------------------------- Find the section of student in a course
1.652     albertel 1207: sub devalidate_getsection_cache {
                   1208:     my ($udom,$unam,$courseid)=@_;
                   1209:     my $hashid="$udom:$unam:$courseid";
                   1210:     &devalidate_cache_new('getsection',$hashid);
                   1211: }
1.298     matthew  1212: 
1.815     albertel 1213: sub courseid_to_courseurl {
                   1214:     my ($courseid) = @_;
                   1215:     #already url style courseid
                   1216:     return $courseid if ($courseid =~ m{^/});
                   1217: 
                   1218:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1219: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1220: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1221: 	return "/$cdom/$cnum";
                   1222:     }
                   1223: 
                   1224:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1225:     if (exists($courseinfo{'num'})) {
                   1226: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1227:     }
                   1228: 
                   1229:     return undef;
                   1230: }
                   1231: 
1.298     matthew  1232: sub getsection {
                   1233:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1234:     my $cachetime=1800;
1.551     albertel 1235: 
                   1236:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1237:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1238:     if (defined($cached)) { return $result; }
                   1239: 
1.298     matthew  1240:     my %Pending; 
                   1241:     my %Expired;
                   1242:     #
                   1243:     # Each role can either have not started yet (pending), be active, 
                   1244:     #    or have expired.
                   1245:     #
                   1246:     # If there is an active role, we are done.
                   1247:     #
                   1248:     # If there is more than one role which has not started yet, 
                   1249:     #     choose the one which will start sooner
                   1250:     # If there is one role which has not started yet, return it.
                   1251:     #
                   1252:     # If there is more than one expired role, choose the one which ended last.
                   1253:     # If there is a role which has expired, return it.
                   1254:     #
1.815     albertel 1255:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1256:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1257:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1258:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1259:         my $section=$1;
                   1260:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1261:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1262:         my $now=time;
1.548     albertel 1263:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1264:             $Expired{$end}=$section;
                   1265:             next;
                   1266:         }
1.548     albertel 1267:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1268:             $Pending{$start}=$section;
                   1269:             next;
                   1270:         }
1.599     albertel 1271:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1272:     }
                   1273:     #
                   1274:     # Presumedly there will be few matching roles from the above
                   1275:     # loop and the sorting time will be negligible.
                   1276:     if (scalar(keys(%Pending))) {
                   1277:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1278:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1279:     } 
                   1280:     if (scalar(keys(%Expired))) {
                   1281:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1282:         my $time = pop(@sorted);
1.599     albertel 1283:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1284:     }
1.599     albertel 1285:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1286: }
1.70      www      1287: 
1.599     albertel 1288: sub save_cache {
                   1289:     &purge_remembered();
1.722     albertel 1290:     #&Apache::loncommon::validate_page();
1.620     albertel 1291:     undef(%env);
1.780     albertel 1292:     undef($env_loaded);
1.599     albertel 1293: }
1.452     albertel 1294: 
1.599     albertel 1295: my $to_remember=-1;
                   1296: my %remembered;
                   1297: my %accessed;
                   1298: my $kicks=0;
                   1299: my $hits=0;
1.849     albertel 1300: sub make_key {
                   1301:     my ($name,$id) = @_;
1.872     albertel 1302:     if (length($id) > 65 
                   1303: 	&& length(&escape($id)) > 200) {
                   1304: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1305:     }
1.849     albertel 1306:     return &escape($name.':'.$id);
                   1307: }
                   1308: 
1.599     albertel 1309: sub devalidate_cache_new {
                   1310:     my ($name,$id,$debug) = @_;
                   1311:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1312:     $id=&make_key($name,$id);
1.599     albertel 1313:     $memcache->delete($id);
                   1314:     delete($remembered{$id});
                   1315:     delete($accessed{$id});
                   1316: }
                   1317: 
                   1318: sub is_cached_new {
                   1319:     my ($name,$id,$debug) = @_;
1.849     albertel 1320:     $id=&make_key($name,$id);
1.599     albertel 1321:     if (exists($remembered{$id})) {
                   1322: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1323: 	$accessed{$id}=[&gettimeofday()];
                   1324: 	$hits++;
                   1325: 	return ($remembered{$id},1);
                   1326:     }
                   1327:     my $value = $memcache->get($id);
                   1328:     if (!(defined($value))) {
                   1329: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1330: 	return (undef,undef);
1.416     albertel 1331:     }
1.599     albertel 1332:     if ($value eq '__undef__') {
                   1333: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1334: 	$value=undef;
                   1335:     }
                   1336:     &make_room($id,$value,$debug);
                   1337:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1338:     return ($value,1);
                   1339: }
                   1340: 
                   1341: sub do_cache_new {
                   1342:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1343:     $id=&make_key($name,$id);
1.599     albertel 1344:     my $setvalue=$value;
                   1345:     if (!defined($setvalue)) {
                   1346: 	$setvalue='__undef__';
                   1347:     }
1.623     albertel 1348:     if (!defined($time) ) {
                   1349: 	$time=600;
                   1350:     }
1.599     albertel 1351:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1352:     my $result = $memcache->set($id,$setvalue,$time);
                   1353:     if (! $result) {
1.872     albertel 1354: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1355: 	$memcache->disconnect_all();
1.872     albertel 1356:     }
1.600     albertel 1357:     # need to make a copy of $value
                   1358:     #&make_room($id,$value,$debug);
1.599     albertel 1359:     return $value;
                   1360: }
                   1361: 
                   1362: sub make_room {
                   1363:     my ($id,$value,$debug)=@_;
                   1364:     $remembered{$id}=$value;
                   1365:     if ($to_remember<0) { return; }
                   1366:     $accessed{$id}=[&gettimeofday()];
                   1367:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1368:     my $to_kick;
                   1369:     my $max_time=0;
                   1370:     foreach my $other (keys(%accessed)) {
                   1371: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1372: 	    $to_kick=$other;
                   1373: 	    $max_time=&tv_interval($accessed{$other});
                   1374: 	}
                   1375:     }
                   1376:     delete($remembered{$to_kick});
                   1377:     delete($accessed{$to_kick});
                   1378:     $kicks++;
                   1379:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1380:     return;
                   1381: }
                   1382: 
1.599     albertel 1383: sub purge_remembered {
1.604     albertel 1384:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1385:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1386:     undef(%remembered);
                   1387:     undef(%accessed);
1.428     albertel 1388: }
1.70      www      1389: # ------------------------------------- Read an entry from a user's environment
                   1390: 
                   1391: sub userenvironment {
                   1392:     my ($udom,$unam,@what)=@_;
                   1393:     my %returnhash=();
                   1394:     my @answer=split(/\&/,
                   1395:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1396:                       &homeserver($unam,$udom)));
                   1397:     my $i;
                   1398:     for ($i=0;$i<=$#what;$i++) {
                   1399: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1400:     }
                   1401:     return %returnhash;
1.1       albertel 1402: }
                   1403: 
1.617     albertel 1404: # ---------------------------------------------------------- Get a studentphoto
                   1405: sub studentphoto {
                   1406:     my ($udom,$unam,$ext) = @_;
                   1407:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1408:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1409:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1410:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1411:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1412:             } else {
                   1413:                 my ($result,$perm_reqd)=
1.707     albertel 1414: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1415:                 if ($result eq 'ok') {
                   1416:                     if (!($perm_reqd eq 'yes')) {
                   1417:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1418:                     }
                   1419:                 }
                   1420:             }
                   1421:         }
                   1422:     } else {
                   1423:         my ($result,$perm_reqd) = 
1.707     albertel 1424: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1425:         if ($result eq 'ok') {
                   1426:             if (!($perm_reqd eq 'yes')) {
                   1427:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1428:             }
                   1429:         }
                   1430:     }
                   1431:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1432: }
                   1433: 
                   1434: sub retrievestudentphoto {
                   1435:     my ($udom,$unam,$ext,$type) = @_;
                   1436:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1437:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1438:     if ($ret eq 'ok') {
                   1439:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1440:         if ($type eq 'thumbnail') {
                   1441:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1442:         }
                   1443:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1444:         return $tokenurl;
                   1445:     } else {
                   1446:         if ($type eq 'thumbnail') {
                   1447:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1448:         } else { 
                   1449:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1450:         }
1.617     albertel 1451:     }
                   1452: }
                   1453: 
1.263     www      1454: # -------------------------------------------------------------------- New chat
                   1455: 
                   1456: sub chatsend {
1.724     raeburn  1457:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1458:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1459:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1460:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1461:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1462: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1463: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1464: }
                   1465: 
                   1466: # ------------------------------------------ Find current version of a resource
                   1467: 
                   1468: sub getversion {
                   1469:     my $fname=&clutter(shift);
                   1470:     unless ($fname=~/^\/res\//) { return -1; }
                   1471:     return &currentversion(&filelocation('',$fname));
                   1472: }
                   1473: 
                   1474: sub currentversion {
                   1475:     my $fname=shift;
1.599     albertel 1476:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1477:     if (defined($cached)) { return $result; }
1.292     www      1478:     my $author=$fname;
                   1479:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1480:     my ($udom,$uname)=split(/\//,$author);
                   1481:     my $home=homeserver($uname,$udom);
                   1482:     if ($home eq 'no_host') { 
                   1483:         return -1; 
                   1484:     }
                   1485:     my $answer=reply("currentversion:$fname",$home);
                   1486:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1487: 	return -1;
                   1488:     }
1.599     albertel 1489:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1490: }
                   1491: 
1.1       albertel 1492: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1493: 
1.1       albertel 1494: sub subscribe {
                   1495:     my $fname=shift;
1.761     raeburn  1496:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1497:     $fname=~s/[\n\r]//g;
1.1       albertel 1498:     my $author=$fname;
                   1499:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1500:     my ($udom,$uname)=split(/\//,$author);
                   1501:     my $home=homeserver($uname,$udom);
1.335     albertel 1502:     if ($home eq 'no_host') {
                   1503:         return 'not_found';
1.1       albertel 1504:     }
                   1505:     my $answer=reply("sub:$fname",$home);
1.64      www      1506:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1507: 	$answer.=' by '.$home;
                   1508:     }
1.1       albertel 1509:     return $answer;
                   1510: }
                   1511:     
1.8       www      1512: # -------------------------------------------------------------- Replicate file
                   1513: 
                   1514: sub repcopy {
                   1515:     my $filename=shift;
1.23      www      1516:     $filename=~s/\/+/\//g;
1.607     raeburn  1517:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1518:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1519:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1520: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1521: 	return &repcopy_userfile($filename);
                   1522:     }
1.532     albertel 1523:     $filename=~s/[\n\r]//g;
1.8       www      1524:     my $transname="$filename.in.transfer";
1.828     www      1525: # FIXME: this should flock
1.607     raeburn  1526:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1527:     my $remoteurl=subscribe($filename);
1.64      www      1528:     if ($remoteurl =~ /^con_lost by/) {
                   1529: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1530:            return 'unavailable';
1.8       www      1531:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1532: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1533: 	   return 'not_found';
1.64      www      1534:     } elsif ($remoteurl =~ /^rejected by/) {
                   1535: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1536:            return 'forbidden';
1.20      www      1537:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1538:            return 'ok';
1.8       www      1539:     } else {
1.290     www      1540:         my $author=$filename;
                   1541:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1542:         my ($udom,$uname)=split(/\//,$author);
                   1543:         my $home=homeserver($uname,$udom);
                   1544:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1545:            my @parts=split(/\//,$filename);
                   1546:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1547:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1548:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1549: 	       return 'bad_request';
1.8       www      1550:            }
                   1551:            my $count;
                   1552:            for ($count=5;$count<$#parts;$count++) {
                   1553:                $path.="/$parts[$count]";
                   1554:                if ((-e $path)!=1) {
                   1555: 		   mkdir($path,0777);
                   1556:                }
                   1557:            }
                   1558:            my $ua=new LWP::UserAgent;
                   1559:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1560:            my $response=$ua->request($request,$transname);
                   1561:            if ($response->is_error()) {
                   1562: 	       unlink($transname);
                   1563:                my $message=$response->status_line;
1.672     albertel 1564:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1565:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1566:                return 'unavailable';
1.8       www      1567:            } else {
1.16      www      1568: 	       if ($remoteurl!~/\.meta$/) {
                   1569:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1570:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1571:                   if ($mresponse->is_error()) {
                   1572: 		      unlink($filename.'.meta');
                   1573:                       &logthis(
1.672     albertel 1574:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1575:                   }
                   1576: 	       }
1.8       www      1577:                rename($transname,$filename);
1.607     raeburn  1578:                return 'ok';
1.8       www      1579:            }
1.290     www      1580:        }
1.8       www      1581:     }
1.330     www      1582: }
                   1583: 
                   1584: # ------------------------------------------------ Get server side include body
                   1585: sub ssi_body {
1.381     albertel 1586:     my ($filelink,%form)=@_;
1.606     matthew  1587:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1588:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1589:     }
1.330     www      1590:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1591:                                      &ssi($filelink,%form));
1.778     albertel 1592:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1593:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1594:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1595:     return $output;
1.8       www      1596: }
                   1597: 
1.15      www      1598: # --------------------------------------------------------- Server Side Include
                   1599: 
1.782     albertel 1600: sub absolute_url {
                   1601:     my ($host_name) = @_;
                   1602:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1603:     if ($host_name eq '') {
                   1604: 	$host_name = $ENV{'SERVER_NAME'};
                   1605:     }
                   1606:     return $protocol.$host_name;
                   1607: }
                   1608: 
1.15      www      1609: sub ssi {
                   1610: 
1.23      www      1611:     my ($fn,%form)=@_;
1.15      www      1612: 
                   1613:     my $ua=new LWP::UserAgent;
1.23      www      1614:     
                   1615:     my $request;
1.711     albertel 1616: 
                   1617:     $form{'no_update_last_known'}=1;
1.895     albertel 1618:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1619:     if (%form) {
1.782     albertel 1620:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1621:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1622:     } else {
1.782     albertel 1623:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1624:     }
                   1625: 
1.15      www      1626:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1627:     my $response=$ua->request($request);
                   1628: 
1.324     www      1629:     return $response->content;
                   1630: }
                   1631: 
                   1632: sub externalssi {
                   1633:     my ($url)=@_;
                   1634:     my $ua=new LWP::UserAgent;
                   1635:     my $request=new HTTP::Request('GET',$url);
                   1636:     my $response=$ua->request($request);
1.15      www      1637:     return $response->content;
                   1638: }
1.254     www      1639: 
1.492     albertel 1640: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1641: 
                   1642: sub allowuploaded {
                   1643:     my ($srcurl,$url)=@_;
                   1644:     $url=&clutter(&declutter($url));
                   1645:     my $dir=$url;
                   1646:     $dir=~s/\/[^\/]+$//;
                   1647:     my %httpref=();
                   1648:     my $httpurl=&hreflocation('',$url);
                   1649:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1650:     &Apache::lonnet::appenv(%httpref);
1.254     www      1651: }
1.477     raeburn  1652: 
1.478     albertel 1653: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1654: # input: action, courseID, current domain, intended
1.637     raeburn  1655: #        path to file, source of file, instruction to parse file for objects,
                   1656: #        ref to hash for embedded objects,
                   1657: #        ref to hash for codebase of java objects.
                   1658: #
1.485     raeburn  1659: # output: url to file (if action was uploaddoc), 
                   1660: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1661: #
1.478     albertel 1662: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1663: # course.
1.477     raeburn  1664: #
1.478     albertel 1665: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1666: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1667: #          course's home server.
1.477     raeburn  1668: #
1.478     albertel 1669: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1670: #          be copied from $source (current location) to 
                   1671: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1672: #         and will then be copied to
                   1673: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1674: #         course's home server.
1.485     raeburn  1675: #
1.481     raeburn  1676: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1677: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1678: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1679: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1680: #         in course's home server.
1.637     raeburn  1681: #
1.477     raeburn  1682: 
                   1683: sub process_coursefile {
1.638     albertel 1684:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1685:     my $fetchresult;
1.638     albertel 1686:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1687:     if ($action eq 'propagate') {
1.638     albertel 1688:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1689: 			     $home);
1.481     raeburn  1690:     } else {
1.477     raeburn  1691:         my $fpath = '';
                   1692:         my $fname = $file;
1.478     albertel 1693:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1694:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1695:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1696:         if ($action eq 'copy') {
                   1697:             if ($source eq '') {
                   1698:                 $fetchresult = 'no source file';
                   1699:                 return $fetchresult;
                   1700:             } else {
                   1701:                 my $destination = $filepath.'/'.$fname;
                   1702:                 rename($source,$destination);
                   1703:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1704:                                  $home);
1.481     raeburn  1705:             }
                   1706:         } elsif ($action eq 'uploaddoc') {
                   1707:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1708:             print $fh $env{'form.'.$source};
1.481     raeburn  1709:             close($fh);
1.637     raeburn  1710:             if ($parser eq 'parse') {
                   1711:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1712:                 unless ($parse_result eq 'ok') {
                   1713:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1714:                 }
                   1715:             }
1.477     raeburn  1716:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1717:                                  $home);
1.481     raeburn  1718:             if ($fetchresult eq 'ok') {
                   1719:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1720:             } else {
                   1721:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1722:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1723:                 return '/adm/notfound.html';
                   1724:             }
1.477     raeburn  1725:         }
                   1726:     }
1.485     raeburn  1727:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1728:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1729:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1730:     }
                   1731:     return $fetchresult;
                   1732: }
                   1733: 
1.637     raeburn  1734: sub build_filepath {
                   1735:     my ($fpath) = @_;
                   1736:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1737:     unless ($fpath eq '') {
                   1738:         my @parts=split('/',$fpath);
                   1739:         foreach my $part (@parts) {
                   1740:             $filepath.= '/'.$part;
                   1741:             if ((-e $filepath)!=1) {
                   1742:                 mkdir($filepath,0777);
                   1743:             }
                   1744:         }
                   1745:     }
                   1746:     return $filepath;
                   1747: }
                   1748: 
                   1749: sub store_edited_file {
1.638     albertel 1750:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1751:     my $file = $primary_url;
                   1752:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1753:     my $fpath = '';
                   1754:     my $fname = $file;
                   1755:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1756:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1757:     my $filepath = &build_filepath($fpath);
                   1758:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1759:     print $fh $content;
                   1760:     close($fh);
1.638     albertel 1761:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1762:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1763: 			  $home);
1.637     raeburn  1764:     if ($$fetchresult eq 'ok') {
                   1765:         return '/uploaded/'.$fpath.'/'.$fname;
                   1766:     } else {
1.638     albertel 1767:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1768: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1769:         return '/adm/notfound.html';
                   1770:     }
                   1771: }
                   1772: 
1.531     albertel 1773: sub clean_filename {
1.831     albertel 1774:     my ($fname,$args)=@_;
1.315     www      1775: # Replace Windows backslashes by forward slashes
1.257     www      1776:     $fname=~s/\\/\//g;
1.831     albertel 1777:     if (!$args->{'keep_path'}) {
                   1778:         # Get rid of everything but the actual filename
                   1779: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1780:     }
1.315     www      1781: # Replace spaces by underscores
                   1782:     $fname=~s/\s+/\_/g;
                   1783: # Replace all other weird characters by nothing
1.831     albertel 1784:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1785: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1786: # numbers
                   1787:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1788:     return $fname;
                   1789: }
                   1790: 
1.608     albertel 1791: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1792: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1793: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1794: #        $coursedoc - if true up to the current course
                   1795: #                     if false
                   1796: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1797: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1798: #        $allfiles - reference to hash for embedded objects
                   1799: #        $codebase - reference to hash for codebase of java objects
                   1800: #        $desuname - username for permanent storage of uploaded file
                   1801: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1802: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1803: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1804: # 
1.686     albertel 1805: # output: url of file in userspace, or error: <message> 
                   1806: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1807: 
                   1808: 
1.531     albertel 1809: sub userfileupload {
1.860     raeburn  1810:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1811:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1812:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1813:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1814:     $fname=&clean_filename($fname);
1.315     www      1815: # See if there is anything left
1.257     www      1816:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1817:     chop($env{'form.'.$formname});
1.523     raeburn  1818:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1819:         my $now = time;
                   1820:         my $filepath = 'tmp/helprequests/'.$now;
                   1821:         my @parts=split(/\//,$filepath);
                   1822:         my $fullpath = $perlvar{'lonDaemons'};
                   1823:         for (my $i=0;$i<@parts;$i++) {
                   1824:             $fullpath .= '/'.$parts[$i];
                   1825:             if ((-e $fullpath)!=1) {
                   1826:                 mkdir($fullpath,0777);
                   1827:             }
                   1828:         }
                   1829:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1830:         print $fh $env{'form.'.$formname};
1.523     raeburn  1831:         close($fh);
1.741     raeburn  1832:         return $fullpath.'/'.$fname;
                   1833:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1834:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1835:                        '_'.$env{'user.domain'}.'/pending';
                   1836:         my @parts=split(/\//,$filepath);
                   1837:         my $fullpath = $perlvar{'lonDaemons'};
                   1838:         for (my $i=0;$i<@parts;$i++) {
                   1839:             $fullpath .= '/'.$parts[$i];
                   1840:             if ((-e $fullpath)!=1) {
                   1841:                 mkdir($fullpath,0777);
                   1842:             }
                   1843:         }
                   1844:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1845:         print $fh $env{'form.'.$formname};
                   1846:         close($fh);
                   1847:         return $fullpath.'/'.$fname;
1.523     raeburn  1848:     }
1.719     banghart 1849:     
1.258     www      1850: # Create the directory if not present
1.493     albertel 1851:     $fname="$subdir/$fname";
1.259     www      1852:     if ($coursedoc) {
1.638     albertel 1853: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1854: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1855:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1856:             return &finishuserfileupload($docuname,$docudom,
                   1857: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1858: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1859:         } else {
1.620     albertel 1860:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1861:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1862: 				       $fname,$formname,$parser,
                   1863: 				       $allfiles,$codebase);
1.481     raeburn  1864:         }
1.719     banghart 1865:     } elsif (defined($destuname)) {
                   1866:         my $docuname=$destuname;
                   1867:         my $docudom=$destudom;
1.860     raeburn  1868: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1869: 				     $parser,$allfiles,$codebase,
                   1870:                                      $thumbwidth,$thumbheight);
1.719     banghart 1871:         
1.259     www      1872:     } else {
1.638     albertel 1873:         my $docuname=$env{'user.name'};
                   1874:         my $docudom=$env{'user.domain'};
1.714     raeburn  1875:         if (exists($env{'form.group'})) {
                   1876:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1877:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1878:         }
1.860     raeburn  1879: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1880: 				     $parser,$allfiles,$codebase,
                   1881:                                      $thumbwidth,$thumbheight);
1.259     www      1882:     }
1.271     www      1883: }
                   1884: 
                   1885: sub finishuserfileupload {
1.860     raeburn  1886:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1887:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1888:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1889:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1890:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1891:     $file=$fname;
                   1892:     if ($fname=~m|/|) {
                   1893:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1894: 	$path.=$fnamepath.'/';
                   1895:     }
1.259     www      1896:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1897:     my $count;
                   1898:     for ($count=4;$count<=$#parts;$count++) {
                   1899:         $filepath.="/$parts[$count]";
                   1900:         if ((-e $filepath)!=1) {
                   1901: 	    mkdir($filepath,0777);
                   1902:         }
                   1903:     }
                   1904: # Save the file
                   1905:     {
1.701     albertel 1906: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1907: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1908: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1909: 	    return '/adm/notfound.html';
                   1910: 	}
                   1911: 	if (!print FH ($env{'form.'.$formname})) {
                   1912: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1913: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1914: 	    return '/adm/notfound.html';
                   1915: 	}
1.570     albertel 1916: 	close(FH);
1.258     www      1917:     }
1.637     raeburn  1918:     if ($parser eq 'parse') {
1.638     albertel 1919:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1920: 						   $codebase);
1.637     raeburn  1921:         unless ($parse_result eq 'ok') {
1.638     albertel 1922:             &logthis('Failed to parse '.$filepath.$file.
                   1923: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1924:         }
                   1925:     }
1.860     raeburn  1926:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1927:         my $input = $filepath.'/'.$file;
                   1928:         my $output = $filepath.'/'.'tn-'.$file;
                   1929:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1930:         system("convert -sample $thumbsize $input $output");
                   1931:         if (-e $filepath.'/'.'tn-'.$file) {
                   1932:             $fetchthumb  = 1; 
                   1933:         }
                   1934:     }
1.858     raeburn  1935:  
1.259     www      1936: # Notify homeserver to grep it
                   1937: #
1.638     albertel 1938:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1939:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1940:     if ($fetchresult eq 'ok') {
1.860     raeburn  1941:         if ($fetchthumb) {
                   1942:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1943:             if ($thumbresult ne 'ok') {
                   1944:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1945:                          $docuhome.': '.$thumbresult);
                   1946:             }
                   1947:         }
1.259     www      1948: #
1.258     www      1949: # Return the URL to it
1.494     albertel 1950:         return '/uploaded/'.$path.$file;
1.263     www      1951:     } else {
1.494     albertel 1952:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1953: 		 ': '.$fetchresult);
1.263     www      1954:         return '/adm/notfound.html';
1.858     raeburn  1955:     }
1.493     albertel 1956: }
                   1957: 
1.637     raeburn  1958: sub extract_embedded_items {
1.648     raeburn  1959:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1960:     my @state = ();
                   1961:     my %javafiles = (
                   1962:                       codebase => '',
                   1963:                       code => '',
                   1964:                       archive => ''
                   1965:                     );
                   1966:     my %mediafiles = (
                   1967:                       src => '',
                   1968:                       movie => '',
                   1969:                      );
1.648     raeburn  1970:     my $p;
                   1971:     if ($content) {
                   1972:         $p = HTML::LCParser->new($content);
                   1973:     } else {
                   1974:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1975:     }
1.641     albertel 1976:     while (my $t=$p->get_token()) {
1.640     albertel 1977: 	if ($t->[0] eq 'S') {
                   1978: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1979: 	    push(@state, $tagname);
1.648     raeburn  1980:             if (lc($tagname) eq 'allow') {
                   1981:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1982:             }
1.640     albertel 1983: 	    if (lc($tagname) eq 'img') {
                   1984: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1985: 	    }
1.886     albertel 1986: 	    if (lc($tagname) eq 'a') {
                   1987: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1988: 	    }
1.645     raeburn  1989:             if (lc($tagname) eq 'script') {
                   1990:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1991:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1992:                 } else {
                   1993:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1994:                 }
                   1995:             }
                   1996:             if (lc($tagname) eq 'link') {
                   1997:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1998:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1999:                 }
                   2000:             }
1.640     albertel 2001: 	    if (lc($tagname) eq 'object' ||
                   2002: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2003: 		foreach my $item (keys(%javafiles)) {
                   2004: 		    $javafiles{$item} = '';
                   2005: 		}
                   2006: 	    }
                   2007: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2008: 		my $name = lc($attr->{'name'});
                   2009: 		foreach my $item (keys(%javafiles)) {
                   2010: 		    if ($name eq $item) {
                   2011: 			$javafiles{$item} = $attr->{'value'};
                   2012: 			last;
                   2013: 		    }
                   2014: 		}
                   2015: 		foreach my $item (keys(%mediafiles)) {
                   2016: 		    if ($name eq $item) {
                   2017: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2018: 			last;
                   2019: 		    }
                   2020: 		}
                   2021: 	    }
                   2022: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2023: 		foreach my $item (keys(%javafiles)) {
                   2024: 		    if ($attr->{$item}) {
                   2025: 			$javafiles{$item} = $attr->{$item};
                   2026: 			last;
                   2027: 		    }
                   2028: 		}
                   2029: 		foreach my $item (keys(%mediafiles)) {
                   2030: 		    if ($attr->{$item}) {
                   2031: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2032: 			last;
                   2033: 		    }
                   2034: 		}
                   2035: 	    }
                   2036: 	} elsif ($t->[0] eq 'E') {
                   2037: 	    my ($tagname) = ($t->[1]);
                   2038: 	    if ($javafiles{'codebase'} ne '') {
                   2039: 		$javafiles{'codebase'} .= '/';
                   2040: 	    }  
                   2041: 	    if (lc($tagname) eq 'applet' ||
                   2042: 		lc($tagname) eq 'object' ||
                   2043: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2044: 		) {
                   2045: 		foreach my $item (keys(%javafiles)) {
                   2046: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2047: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2048: 			&add_filetype($allfiles,$file,$item);
                   2049: 		    }
                   2050: 		}
                   2051: 	    } 
                   2052: 	    pop @state;
                   2053: 	}
                   2054:     }
1.637     raeburn  2055:     return 'ok';
                   2056: }
                   2057: 
1.639     albertel 2058: sub add_filetype {
                   2059:     my ($allfiles,$file,$type)=@_;
                   2060:     if (exists($allfiles->{$file})) {
                   2061: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2062: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2063: 	}
                   2064:     } else {
                   2065: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2066:     }
                   2067: }
                   2068: 
1.493     albertel 2069: sub removeuploadedurl {
                   2070:     my ($url)=@_;
                   2071:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2072:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2073: }
                   2074: 
                   2075: sub removeuserfile {
                   2076:     my ($docuname,$docudom,$fname)=@_;
                   2077:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2078:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2079:     if ($result eq 'ok') {
                   2080:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2081:             my $metafile = $fname.'.meta';
                   2082:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2083: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2084:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2085:             my $sqlresult = 
1.823     albertel 2086:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2087:                                         'portfolio_metadata',$group,
                   2088:                                         'delete');
1.798     raeburn  2089:         }
                   2090:     }
                   2091:     return $result;
1.257     www      2092: }
1.15      www      2093: 
1.530     albertel 2094: sub mkdiruserfile {
                   2095:     my ($docuname,$docudom,$dir)=@_;
                   2096:     my $home=&homeserver($docuname,$docudom);
                   2097:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2098: }
                   2099: 
1.531     albertel 2100: sub renameuserfile {
                   2101:     my ($docuname,$docudom,$old,$new)=@_;
                   2102:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2103:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2104:                         &escape("$old").':'.&escape("$new"),$home);
                   2105:     if ($result eq 'ok') {
                   2106:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2107:             my $oldmeta = $old.'.meta';
                   2108:             my $newmeta = $new.'.meta';
                   2109:             my $metaresult = 
                   2110:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2111: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2112:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2113:             my $sqlresult = 
1.823     albertel 2114:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2115:                                         'portfolio_metadata',$group,
                   2116:                                         'delete');
1.798     raeburn  2117:         }
                   2118:     }
                   2119:     return $result;
1.531     albertel 2120: }
                   2121: 
1.14      www      2122: # ------------------------------------------------------------------------- Log
                   2123: 
                   2124: sub log {
                   2125:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2126:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2127: }
                   2128: 
                   2129: # ------------------------------------------------------------------ Course Log
1.352     www      2130: #
                   2131: # This routine flushes several buffers of non-mission-critical nature
                   2132: #
1.157     www      2133: 
                   2134: sub flushcourselogs {
1.352     www      2135:     &logthis('Flushing log buffers');
                   2136: #
                   2137: # course logs
                   2138: # This is a log of all transactions in a course, which can be used
                   2139: # for data mining purposes
                   2140: #
                   2141: # It also collects the courseid database, which lists last transaction
                   2142: # times and course titles for all courseids
                   2143: #
                   2144:     my %courseidbuffer=();
1.800     albertel 2145:     foreach my $crsid (keys %courselogs) {
1.352     www      2146:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2147: 		          &escape($courselogs{$crsid}),
                   2148: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2149: 	    delete $courselogs{$crsid};
                   2150:         } else {
                   2151:             &logthis('Failed to flush log buffer for '.$crsid);
                   2152:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2153:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2154:                         " exceeded maximum size, deleting.</font>");
                   2155:                delete $courselogs{$crsid};
                   2156:             }
1.352     www      2157:         }
                   2158:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2159:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2160: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2161:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2162:         } else {
                   2163:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2164: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2165:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2166:         }
1.191     harris41 2167:     }
1.352     www      2168: #
                   2169: # Write course id database (reverse lookup) to homeserver of courses 
                   2170: # Is used in pickcourse
                   2171: #
1.840     albertel 2172:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2173:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2174: 		     $crs_home);
1.352     www      2175:     }
                   2176: #
                   2177: # File accesses
                   2178: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2179: #
1.449     matthew  2180:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2181:         if ($entry =~ /___count$/) {
                   2182:             my ($dom,$name);
1.807     albertel 2183:             ($dom,$name,undef)=
1.811     albertel 2184: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2185:             if (! defined($dom) || $dom eq '' || 
                   2186:                 ! defined($name) || $name eq '') {
1.620     albertel 2187:                 my $cid = $env{'request.course.id'};
                   2188:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2189:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2190:             }
1.450     matthew  2191:             my $value = $accesshash{$entry};
                   2192:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2193:             my %temphash=($url => $value);
1.449     matthew  2194:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2195:             if ($result eq 'ok') {
                   2196:                 delete $accesshash{$entry};
                   2197:             } elsif ($result eq 'unknown_cmd') {
                   2198:                 # Target server has old code running on it.
1.450     matthew  2199:                 my %temphash=($entry => $value);
1.449     matthew  2200:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2201:                     delete $accesshash{$entry};
                   2202:                 }
                   2203:             }
                   2204:         } else {
1.811     albertel 2205:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2206:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2207:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2208:                 delete $accesshash{$entry};
                   2209:             }
1.185     www      2210:         }
1.191     harris41 2211:     }
1.352     www      2212: #
                   2213: # Roles
                   2214: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2215: #
1.800     albertel 2216:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2217:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2218: 	    split(/\:/,$entry);
                   2219:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2220:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2221:                 $rudom,$runame) eq 'ok') {
                   2222: 	    delete $userrolehash{$entry};
                   2223:         }
                   2224:     }
1.662     raeburn  2225: #
                   2226: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2227: #
                   2228:     my %domrolebuffer = ();
                   2229:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2230:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2231:         if ($domrolebuffer{$rudom}) {
                   2232:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2233:                       '='.&escape($domainrolehash{$entry});
                   2234:         } else {
                   2235:             $domrolebuffer{$rudom}.=&escape($entry).
                   2236:                       '='.&escape($domainrolehash{$entry});
                   2237:         }
                   2238:         delete $domainrolehash{$entry};
                   2239:     }
                   2240:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2241: 	my %servers = &get_servers($dom,'library');
                   2242: 	foreach my $tryserver (keys(%servers)) {
                   2243: 	    unless (&reply('domroleput:'.$dom.':'.
                   2244: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2245: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2246: 	    }
1.662     raeburn  2247:         }
                   2248:     }
1.186     www      2249:     $dumpcount++;
1.157     www      2250: }
                   2251: 
                   2252: sub courselog {
                   2253:     my $what=shift;
1.158     www      2254:     $what=time.':'.$what;
1.620     albertel 2255:     unless ($env{'request.course.id'}) { return ''; }
                   2256:     $coursedombuf{$env{'request.course.id'}}=
                   2257:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2258:     $coursenumbuf{$env{'request.course.id'}}=
                   2259:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2260:     $coursehombuf{$env{'request.course.id'}}=
                   2261:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2262:     $coursedescrbuf{$env{'request.course.id'}}=
                   2263:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2264:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2265:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2266:     $courseownerbuf{$env{'request.course.id'}}=
                   2267:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2268:     $coursetypebuf{$env{'request.course.id'}}=
                   2269:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2270:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2271: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2272:     } else {
1.620     albertel 2273: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2274:     }
1.620     albertel 2275:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2276: 	&flushcourselogs();
                   2277:     }
1.158     www      2278: }
                   2279: 
                   2280: sub courseacclog {
                   2281:     my $fnsymb=shift;
1.620     albertel 2282:     unless ($env{'request.course.id'}) { return ''; }
                   2283:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2284:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2285:         $what.=':POST';
1.583     matthew  2286:         # FIXME: Probably ought to escape things....
1.800     albertel 2287: 	foreach my $key (keys(%env)) {
                   2288:             if ($key=~/^form\.(.*)/) {
                   2289: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2290:             }
1.191     harris41 2291:         }
1.583     matthew  2292:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2293:         # FIXME: We should not be depending on a form parameter that someone
                   2294:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2295:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2296:             $what.= ':POST';
                   2297:             # FIXME: Probably ought to escape things....
                   2298:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2299:                                  'crsdiscuss') {
1.620     albertel 2300:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2301:             }
                   2302:         }
1.158     www      2303:     }
                   2304:     &courselog($what);
1.149     www      2305: }
                   2306: 
1.185     www      2307: sub countacc {
                   2308:     my $url=&declutter(shift);
1.458     matthew  2309:     return if (! defined($url) || $url eq '');
1.620     albertel 2310:     unless ($env{'request.course.id'}) { return ''; }
                   2311:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2312:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2313:     $accesshash{$key}++;
1.185     www      2314: }
1.349     www      2315: 
1.361     www      2316: sub linklog {
                   2317:     my ($from,$to)=@_;
                   2318:     $from=&declutter($from);
                   2319:     $to=&declutter($to);
                   2320:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2321:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2322: }
                   2323:   
1.349     www      2324: sub userrolelog {
                   2325:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2326:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2327:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2328:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2329:         ($trole=~/^ta/)) {
1.350     www      2330:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2331:        $userrolehash
                   2332:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2333:                     =$tend.':'.$tstart;
1.662     raeburn  2334:     }
1.898     albertel 2335:     if (($env{'request.role'} =~ /dc\./) &&
                   2336: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2337: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2338: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2339:        $userrolehash
                   2340:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2341:                     =$tend.':'.$tstart;
                   2342:     }
1.662     raeburn  2343:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2344:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2345:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2346:         ($trole=~/^sc/)) {
                   2347:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2348:        $domainrolehash
                   2349:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2350:                     = $tend.':'.$tstart;
                   2351:     }
1.351     www      2352: }
                   2353: 
                   2354: sub get_course_adv_roles {
                   2355:     my $cid=shift;
1.620     albertel 2356:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2357:     my %coursehash=&coursedescription($cid);
1.470     www      2358:     my %nothide=();
1.800     albertel 2359:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2360: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2361:     }
1.351     www      2362:     my %returnhash=();
                   2363:     my %dumphash=
                   2364:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2365:     my $now=time;
1.800     albertel 2366:     foreach my $entry (keys %dumphash) {
                   2367: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2368:         if (($tstart) && ($tstart<0)) { next; }
                   2369:         if (($tend) && ($tend<$now)) { next; }
                   2370:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2371:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2372: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2373: 	if ((&privileged($username,$domain)) && 
                   2374: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2375: 	if ($role eq 'cr') { next; }
1.351     www      2376:         my $key=&plaintext($role);
                   2377:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2378:         if ($returnhash{$key}) {
                   2379: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2380:         } else {
                   2381:             $returnhash{$key}=$username.':'.$domain;
                   2382:         }
1.400     www      2383:      }
                   2384:     return %returnhash;
                   2385: }
                   2386: 
                   2387: sub get_my_roles {
1.858     raeburn  2388:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2389:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2390:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2391:     my %dumphash;
                   2392:     if ($context eq 'userroles') { 
                   2393:         %dumphash = &dump('roles',$udom,$uname);
                   2394:     } else {
                   2395:         %dumphash=
1.400     www      2396:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2397:     }
1.400     www      2398:     my %returnhash=();
                   2399:     my $now=time;
1.800     albertel 2400:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2401:         my ($role,$tend,$tstart);
                   2402:         if ($context eq 'userroles') {
                   2403: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2404:         } else {
                   2405:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2406:         }
1.400     www      2407:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2408:         my $status = 'active';
                   2409:         if (($tend) && ($tend<$now)) {
                   2410:             $status = 'previous';
                   2411:         } 
                   2412:         if (($tstart) && ($now<$tstart)) {
                   2413:             $status = 'future';
                   2414:         }
                   2415:         if (ref($types) eq 'ARRAY') {
                   2416:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2417:                 next;
                   2418:             } 
                   2419:         } else {
                   2420:             if ($status ne 'active') {
                   2421:                 next;
                   2422:             }
                   2423:         }
1.867     raeburn  2424:         my ($rolecode,$username,$domain,$section,$area);
                   2425:         if ($context eq 'userroles') {
                   2426:             ($area,$rolecode) = split(/_/,$entry);
                   2427:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2428:         } else {
                   2429:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2430:         }
1.832     raeburn  2431:         if (ref($roledoms) eq 'ARRAY') {
                   2432:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2433:                 next;
                   2434:             }
                   2435:         }
                   2436:         if (ref($roles) eq 'ARRAY') {
                   2437:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2438:                 next;
                   2439:             }
1.867     raeburn  2440:         }
1.400     www      2441: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2442:     }
1.373     www      2443:     return %returnhash;
1.399     www      2444: }
                   2445: 
                   2446: # ----------------------------------------------------- Frontpage Announcements
                   2447: #
                   2448: #
                   2449: 
                   2450: sub postannounce {
                   2451:     my ($server,$text)=@_;
1.844     albertel 2452:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2453:     unless ($text=~/\w/) { $text=''; }
                   2454:     return &reply('setannounce:'.&escape($text),$server);
                   2455: }
                   2456: 
                   2457: sub getannounce {
1.448     albertel 2458: 
                   2459:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2460: 	my $announcement='';
1.800     albertel 2461: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2462: 	close($fh);
1.399     www      2463: 	if ($announcement=~/\w/) { 
                   2464: 	    return 
                   2465:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2466:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2467: 	} else {
                   2468: 	    return '';
                   2469: 	}
                   2470:     } else {
                   2471: 	return '';
                   2472:     }
1.351     www      2473: }
1.353     www      2474: 
                   2475: # ---------------------------------------------------------- Course ID routines
                   2476: # Deal with domain's nohist_courseid.db files
                   2477: #
                   2478: 
                   2479: sub courseidput {
                   2480:     my ($domain,$what,$coursehome)=@_;
                   2481:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2482: }
                   2483: 
                   2484: sub courseiddump {
1.791     raeburn  2485:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2486:     my %returnhash=();
1.355     www      2487:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2488:     my %libserv = &all_library();
                   2489:     foreach my $tryserver (keys(%libserv)) {
                   2490:         if ( (  $hostidflag == 1 
                   2491: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2492: 	     || (!defined($hostidflag)) ) {
                   2493: 
                   2494: 	    if ($domfilter eq ''
                   2495: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2496: 	        foreach my $line (
1.844     albertel 2497:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2498: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2499:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2500:                                $tryserver))) {
1.800     albertel 2501: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2502:                     if (($key) && ($value)) {
1.516     raeburn  2503: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2504:                     }
1.353     www      2505:                 }
                   2506:             }
                   2507:         }
                   2508:     }
                   2509:     return %returnhash;
                   2510: }
                   2511: 
1.658     raeburn  2512: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2513: 
                   2514: sub dcmailput {
1.685     raeburn  2515:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2516:     my $status = &Apache::lonnet::critical(
1.740     www      2517:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2518:        &escape($message),$server);
1.662     raeburn  2519:     return $status;
                   2520: }
                   2521: 
1.658     raeburn  2522: sub dcmaildump {
                   2523:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2524:     my %returnhash=();
1.846     albertel 2525: 
                   2526:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2527:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2528:                                                          &escape($enddate).':';
                   2529: 	my @esc_senders=map { &escape($_)} @$senders;
                   2530: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2531: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2532:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2533:             if (($key) && ($value)) {
                   2534:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2535:             }
                   2536:         }
                   2537:     }
                   2538:     return %returnhash;
                   2539: }
1.662     raeburn  2540: # ---------------------------------------------------------- Domain roles
                   2541: 
                   2542: sub get_domain_roles {
                   2543:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2544:     if (undef($startdate) || $startdate eq '') {
                   2545:         $startdate = '.';
                   2546:     }
                   2547:     if (undef($enddate) || $enddate eq '') {
                   2548:         $enddate = '.';
                   2549:     }
                   2550:     my $rolelist = join(':',@{$roles});
                   2551:     my %personnel = ();
1.841     albertel 2552: 
                   2553:     my %servers = &get_servers($dom,'library');
                   2554:     foreach my $tryserver (keys(%servers)) {
                   2555: 	%{$personnel{$tryserver}}=();
                   2556: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2557: 					    &escape($startdate).':'.
                   2558: 					    &escape($enddate).':'.
                   2559: 					    &escape($rolelist), $tryserver))) {
                   2560: 	    my ($key,$value) = split(/\=/,$line,2);
                   2561: 	    if (($key) && ($value)) {
                   2562: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2563: 	    }
                   2564: 	}
1.662     raeburn  2565:     }
                   2566:     return %personnel;
                   2567: }
1.658     raeburn  2568: 
1.149     www      2569: # ----------------------------------------------------------- Check out an item
                   2570: 
1.504     albertel 2571: sub get_first_access {
                   2572:     my ($type,$argsymb)=@_;
1.790     albertel 2573:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2574:     if ($argsymb) { $symb=$argsymb; }
                   2575:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2576:     if ($type eq 'map') {
                   2577: 	$res=&symbread($map);
                   2578:     } else {
                   2579: 	$res=$symb;
                   2580:     }
                   2581:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2582:     return $times{"$courseid\0$res"};
1.504     albertel 2583: }
                   2584: 
                   2585: sub set_first_access {
                   2586:     my ($type)=@_;
1.790     albertel 2587:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2588:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2589:     if ($type eq 'map') {
                   2590: 	$res=&symbread($map);
                   2591:     } else {
                   2592: 	$res=$symb;
                   2593:     }
                   2594:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2595:     if (!$firstaccess) {
1.588     albertel 2596: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2597:     }
                   2598:     return 'already_set';
1.504     albertel 2599: }
                   2600: 
1.149     www      2601: sub checkout {
                   2602:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2603:     my $now=time;
                   2604:     my $lonhost=$perlvar{'lonHostID'};
                   2605:     my $infostr=&escape(
1.234     www      2606:                  'CHECKOUTTOKEN&'.
1.149     www      2607:                  $tuname.'&'.
                   2608:                  $tudom.'&'.
                   2609:                  $tcrsid.'&'.
                   2610:                  $symb.'&'.
                   2611: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2612:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2613:     if ($token=~/^error\:/) { 
1.672     albertel 2614:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2615:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2616:                  "</font>");
                   2617:         return ''; 
                   2618:     }
                   2619: 
1.149     www      2620:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2621:     $token=~tr/a-z/A-Z/;
                   2622: 
1.153     www      2623:     my %infohash=('resource.0.outtoken' => $token,
                   2624:                   'resource.0.checkouttime' => $now,
                   2625:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2626: 
                   2627:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2628:        return '';
1.151     www      2629:     } else {
1.672     albertel 2630:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2631:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2632:                  "</font>");
1.149     www      2633:     }    
                   2634: 
                   2635:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2636:                          &escape('Checkout '.$infostr.' - '.
                   2637:                                                  $token)) ne 'ok') {
                   2638: 	return '';
1.151     www      2639:     } else {
1.672     albertel 2640:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2641:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2642:                  "</font>");
1.149     www      2643:     }
1.151     www      2644:     return $token;
1.149     www      2645: }
                   2646: 
                   2647: # ------------------------------------------------------------ Check in an item
                   2648: 
                   2649: sub checkin {
                   2650:     my $token=shift;
1.150     www      2651:     my $now=time;
                   2652:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2653:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2654:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2655:     $dtoken=~s/\W/\_/g;
1.234     www      2656:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2657:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2658: 
1.154     www      2659:     unless (($tuname) && ($tudom)) {
                   2660:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2661:         return '';
                   2662:     }
                   2663:     
                   2664:     unless (&allowed('mgr',$tcrsid)) {
                   2665:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2666:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2667:         return '';
                   2668:     }
                   2669: 
1.153     www      2670:     my %infohash=('resource.0.intoken' => $token,
                   2671:                   'resource.0.checkintime' => $now,
                   2672:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2673: 
                   2674:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2675:        return '';
                   2676:     }    
                   2677: 
                   2678:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2679:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2680: 	return '';
                   2681:     }
                   2682: 
                   2683:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2684: }
                   2685: 
                   2686: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2687: 
                   2688: sub expirespread {
                   2689:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2690:     my $cid=$env{'request.course.id'}; 
1.110     www      2691:     if ($cid) {
                   2692:        my $now=time;
                   2693:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2694:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2695:                             $env{'course.'.$cid.'.num'}.
1.110     www      2696: 	        	    ':nohist_expirationdates:'.
                   2697:                             &escape($key).'='.$now,
1.620     albertel 2698:                             $env{'course.'.$cid.'.home'})
1.110     www      2699:     }
                   2700:     return 'ok';
1.14      www      2701: }
                   2702: 
1.109     www      2703: # ----------------------------------------------------- Devalidate Spreadsheets
                   2704: 
                   2705: sub devalidate {
1.325     www      2706:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2707:     my $cid=$env{'request.course.id'}; 
1.109     www      2708:     if ($cid) {
1.391     matthew  2709:         # delete the stored spreadsheets for
                   2710:         # - the student level sheet of this user in course's homespace
                   2711:         # - the assessment level sheet for this resource 
                   2712:         #   for this user in user's homespace
1.553     albertel 2713: 	# - current conditional state info
1.325     www      2714: 	my $key=$uname.':'.$udom.':';
1.109     www      2715:         my $status=
1.299     matthew  2716: 	    &del('nohist_calculatedsheets',
1.391     matthew  2717: 		 [$key.'studentcalc:'],
1.620     albertel 2718: 		 $env{'course.'.$cid.'.domain'},
                   2719: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2720: 		.' '.
                   2721: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2722: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2723:         unless ($status eq 'ok ok') {
                   2724:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2725:                     $uname.' at '.$udom.' for '.
1.109     www      2726: 		    $symb.': '.$status);
1.133     albertel 2727:         }
1.553     albertel 2728: 	&delenv('user.state.'.$cid);
1.109     www      2729:     }
                   2730: }
                   2731: 
1.265     albertel 2732: sub get_scalar {
                   2733:     my ($string,$end) = @_;
                   2734:     my $value;
                   2735:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2736: 	$value = $1;
                   2737:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2738: 	$value = $1;
                   2739:     }
                   2740:     return &unescape($value);
                   2741: }
                   2742: 
                   2743: sub array2str {
                   2744:   my (@array) = @_;
                   2745:   my $result=&arrayref2str(\@array);
                   2746:   $result=~s/^__ARRAY_REF__//;
                   2747:   $result=~s/__END_ARRAY_REF__$//;
                   2748:   return $result;
                   2749: }
                   2750: 
1.204     albertel 2751: sub arrayref2str {
                   2752:   my ($arrayref) = @_;
1.265     albertel 2753:   my $result='__ARRAY_REF__';
1.204     albertel 2754:   foreach my $elem (@$arrayref) {
1.265     albertel 2755:     if(ref($elem) eq 'ARRAY') {
                   2756:       $result.=&arrayref2str($elem).'&';
                   2757:     } elsif(ref($elem) eq 'HASH') {
                   2758:       $result.=&hashref2str($elem).'&';
                   2759:     } elsif(ref($elem)) {
                   2760:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2761:     } else {
                   2762:       $result.=&escape($elem).'&';
                   2763:     }
                   2764:   }
                   2765:   $result=~s/\&$//;
1.265     albertel 2766:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2767:   return $result;
                   2768: }
                   2769: 
1.168     albertel 2770: sub hash2str {
1.204     albertel 2771:   my (%hash) = @_;
                   2772:   my $result=&hashref2str(\%hash);
1.265     albertel 2773:   $result=~s/^__HASH_REF__//;
                   2774:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2775:   return $result;
                   2776: }
                   2777: 
                   2778: sub hashref2str {
                   2779:   my ($hashref)=@_;
1.265     albertel 2780:   my $result='__HASH_REF__';
1.800     albertel 2781:   foreach my $key (sort(keys(%$hashref))) {
                   2782:     if (ref($key) eq 'ARRAY') {
                   2783:       $result.=&arrayref2str($key).'=';
                   2784:     } elsif (ref($key) eq 'HASH') {
                   2785:       $result.=&hashref2str($key).'=';
                   2786:     } elsif (ref($key)) {
1.265     albertel 2787:       $result.='=';
1.800     albertel 2788:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2789:     } else {
1.800     albertel 2790: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2791:     }
                   2792: 
1.800     albertel 2793:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2794:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2795:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2796:       $result.=&hashref2str($hashref->{$key}).'&';
                   2797:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2798:        $result.='&';
1.800     albertel 2799:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2800:     } else {
1.800     albertel 2801:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2802:     }
                   2803:   }
1.168     albertel 2804:   $result=~s/\&$//;
1.265     albertel 2805:   $result .= '__END_HASH_REF__';
1.168     albertel 2806:   return $result;
                   2807: }
                   2808: 
                   2809: sub str2hash {
1.265     albertel 2810:     my ($string)=@_;
                   2811:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2812:     return %$hash;
                   2813: }
                   2814: 
                   2815: sub str2hashref {
1.168     albertel 2816:   my ($string) = @_;
1.265     albertel 2817: 
                   2818:   my %hash;
                   2819: 
                   2820:   if($string !~ /^__HASH_REF__/) {
                   2821:       if (! ($string eq '' || !defined($string))) {
                   2822: 	  $hash{'error'}='Not hash reference';
                   2823:       }
                   2824:       return (\%hash, $string);
                   2825:   }
                   2826: 
                   2827:   $string =~ s/^__HASH_REF__//;
                   2828: 
                   2829:   while($string !~ /^__END_HASH_REF__/) {
                   2830:       #key
                   2831:       my $key='';
                   2832:       if($string =~ /^__HASH_REF__/) {
                   2833:           ($key, $string)=&str2hashref($string);
                   2834:           if(defined($key->{'error'})) {
                   2835:               $hash{'error'}='Bad data';
                   2836:               return (\%hash, $string);
                   2837:           }
                   2838:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2839:           ($key, $string)=&str2arrayref($string);
                   2840:           if($key->[0] eq 'Array reference error') {
                   2841:               $hash{'error'}='Bad data';
                   2842:               return (\%hash, $string);
                   2843:           }
                   2844:       } else {
                   2845:           $string =~ s/^(.*?)=//;
1.267     albertel 2846: 	  $key=&unescape($1);
1.265     albertel 2847:       }
                   2848:       $string =~ s/^=//;
                   2849: 
                   2850:       #value
                   2851:       my $value='';
                   2852:       if($string =~ /^__HASH_REF__/) {
                   2853:           ($value, $string)=&str2hashref($string);
                   2854:           if(defined($value->{'error'})) {
                   2855:               $hash{'error'}='Bad data';
                   2856:               return (\%hash, $string);
                   2857:           }
                   2858:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2859:           ($value, $string)=&str2arrayref($string);
                   2860:           if($value->[0] eq 'Array reference error') {
                   2861:               $hash{'error'}='Bad data';
                   2862:               return (\%hash, $string);
                   2863:           }
                   2864:       } else {
                   2865: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2866:       }
                   2867:       $string =~ s/^&//;
                   2868: 
                   2869:       $hash{$key}=$value;
1.204     albertel 2870:   }
1.265     albertel 2871: 
                   2872:   $string =~ s/^__END_HASH_REF__//;
                   2873: 
                   2874:   return (\%hash, $string);
1.204     albertel 2875: }
                   2876: 
                   2877: sub str2array {
1.265     albertel 2878:     my ($string)=@_;
                   2879:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2880:     return @$array;
                   2881: }
                   2882: 
                   2883: sub str2arrayref {
1.204     albertel 2884:   my ($string) = @_;
1.265     albertel 2885:   my @array;
                   2886: 
                   2887:   if($string !~ /^__ARRAY_REF__/) {
                   2888:       if (! ($string eq '' || !defined($string))) {
                   2889: 	  $array[0]='Array reference error';
                   2890:       }
                   2891:       return (\@array, $string);
                   2892:   }
                   2893: 
                   2894:   $string =~ s/^__ARRAY_REF__//;
                   2895: 
                   2896:   while($string !~ /^__END_ARRAY_REF__/) {
                   2897:       my $value='';
                   2898:       if($string =~ /^__HASH_REF__/) {
                   2899:           ($value, $string)=&str2hashref($string);
                   2900:           if(defined($value->{'error'})) {
                   2901:               $array[0] ='Array reference error';
                   2902:               return (\@array, $string);
                   2903:           }
                   2904:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2905:           ($value, $string)=&str2arrayref($string);
                   2906:           if($value->[0] eq 'Array reference error') {
                   2907:               $array[0] ='Array reference error';
                   2908:               return (\@array, $string);
                   2909:           }
                   2910:       } else {
                   2911: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2912:       }
                   2913:       $string =~ s/^&//;
                   2914: 
                   2915:       push(@array, $value);
1.191     harris41 2916:   }
1.265     albertel 2917: 
                   2918:   $string =~ s/^__END_ARRAY_REF__//;
                   2919: 
                   2920:   return (\@array, $string);
1.168     albertel 2921: }
                   2922: 
1.167     albertel 2923: # -------------------------------------------------------------------Temp Store
                   2924: 
1.168     albertel 2925: sub tmpreset {
                   2926:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2927:   if (!$symb) {
                   2928:     $symb=&symbread();
1.620     albertel 2929:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2930:   }
                   2931:   $symb=escape($symb);
                   2932: 
1.620     albertel 2933:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2934:   $namespace=~s/\//\_/g;
                   2935:   $namespace=~s/\W//g;
                   2936: 
1.620     albertel 2937:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2938:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2939:   if ($domain eq 'public' && $stuname eq 'public') {
                   2940:       $stuname=$ENV{'REMOTE_ADDR'};
                   2941:   }
1.168     albertel 2942:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2943:   my %hash;
                   2944:   if (tie(%hash,'GDBM_File',
                   2945: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2946: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2947:     foreach my $key (keys %hash) {
1.180     albertel 2948:       if ($key=~ /:$symb/) {
1.168     albertel 2949: 	delete($hash{$key});
                   2950:       }
                   2951:     }
                   2952:   }
                   2953: }
                   2954: 
1.167     albertel 2955: sub tmpstore {
1.168     albertel 2956:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2957: 
                   2958:   if (!$symb) {
                   2959:     $symb=&symbread();
1.620     albertel 2960:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2961:   }
                   2962:   $symb=escape($symb);
                   2963: 
                   2964:   if (!$namespace) {
                   2965:     # I don't think we would ever want to store this for a course.
                   2966:     # it seems this will only be used if we don't have a course.
1.620     albertel 2967:     #$namespace=$env{'request.course.id'};
1.168     albertel 2968:     #if (!$namespace) {
1.620     albertel 2969:       $namespace=$env{'request.state'};
1.168     albertel 2970:     #}
                   2971:   }
                   2972:   $namespace=~s/\//\_/g;
                   2973:   $namespace=~s/\W//g;
1.620     albertel 2974:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2975:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2976:   if ($domain eq 'public' && $stuname eq 'public') {
                   2977:       $stuname=$ENV{'REMOTE_ADDR'};
                   2978:   }
1.168     albertel 2979:   my $now=time;
                   2980:   my %hash;
                   2981:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2982:   if (tie(%hash,'GDBM_File',
                   2983: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2984: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2985:     $hash{"version:$symb"}++;
                   2986:     my $version=$hash{"version:$symb"};
                   2987:     my $allkeys=''; 
                   2988:     foreach my $key (keys(%$storehash)) {
                   2989:       $allkeys.=$key.':';
1.591     albertel 2990:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2991:     }
                   2992:     $hash{"$version:$symb:timestamp"}=$now;
                   2993:     $allkeys.='timestamp';
                   2994:     $hash{"$version:keys:$symb"}=$allkeys;
                   2995:     if (untie(%hash)) {
                   2996:       return 'ok';
                   2997:     } else {
                   2998:       return "error:$!";
                   2999:     }
                   3000:   } else {
                   3001:     return "error:$!";
                   3002:   }
                   3003: }
1.167     albertel 3004: 
1.168     albertel 3005: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3006: 
1.168     albertel 3007: sub tmprestore {
                   3008:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3009: 
1.168     albertel 3010:   if (!$symb) {
                   3011:     $symb=&symbread();
1.620     albertel 3012:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3013:   }
                   3014:   $symb=escape($symb);
                   3015: 
1.620     albertel 3016:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3017: 
1.620     albertel 3018:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3019:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3020:   if ($domain eq 'public' && $stuname eq 'public') {
                   3021:       $stuname=$ENV{'REMOTE_ADDR'};
                   3022:   }
1.168     albertel 3023:   my %returnhash;
                   3024:   $namespace=~s/\//\_/g;
                   3025:   $namespace=~s/\W//g;
                   3026:   my %hash;
                   3027:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3028:   if (tie(%hash,'GDBM_File',
                   3029: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3030: 	  &GDBM_READER(),0640)) {
1.168     albertel 3031:     my $version=$hash{"version:$symb"};
                   3032:     $returnhash{'version'}=$version;
                   3033:     my $scope;
                   3034:     for ($scope=1;$scope<=$version;$scope++) {
                   3035:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3036:       my @keys=split(/:/,$vkeys);
                   3037:       my $key;
                   3038:       $returnhash{"$scope:keys"}=$vkeys;
                   3039:       foreach $key (@keys) {
1.591     albertel 3040: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3041: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3042:       }
                   3043:     }
1.168     albertel 3044:     if (!(untie(%hash))) {
                   3045:       return "error:$!";
                   3046:     }
                   3047:   } else {
                   3048:     return "error:$!";
                   3049:   }
                   3050:   return %returnhash;
1.167     albertel 3051: }
                   3052: 
1.9       www      3053: # ----------------------------------------------------------------------- Store
                   3054: 
                   3055: sub store {
1.124     www      3056:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3057:     my $home='';
                   3058: 
1.168     albertel 3059:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3060: 
1.213     www      3061:     $symb=&symbclean($symb);
1.122     albertel 3062:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3063: 
1.620     albertel 3064:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3065:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3066: 
                   3067:     &devalidate($symb,$stuname,$domain);
1.109     www      3068: 
                   3069:     $symb=escape($symb);
1.187     www      3070:     if (!$namespace) { 
1.620     albertel 3071:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3072:           return ''; 
                   3073:        } 
                   3074:     }
1.620     albertel 3075:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3076: 
                   3077:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3078:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3079: 
1.12      www      3080:     my $namevalue='';
1.800     albertel 3081:     foreach my $key (keys(%$storehash)) {
                   3082:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3083:     }
1.12      www      3084:     $namevalue=~s/\&$//;
1.187     www      3085:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3086:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3087: }
                   3088: 
1.47      www      3089: # -------------------------------------------------------------- Critical Store
                   3090: 
                   3091: sub cstore {
1.124     www      3092:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3093:     my $home='';
                   3094: 
1.168     albertel 3095:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3096: 
1.213     www      3097:     $symb=&symbclean($symb);
1.122     albertel 3098:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3099: 
1.620     albertel 3100:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3101:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3102: 
                   3103:     &devalidate($symb,$stuname,$domain);
1.109     www      3104: 
                   3105:     $symb=escape($symb);
1.187     www      3106:     if (!$namespace) { 
1.620     albertel 3107:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3108:           return ''; 
                   3109:        } 
                   3110:     }
1.620     albertel 3111:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3112: 
                   3113:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3114:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3115: 
1.47      www      3116:     my $namevalue='';
1.800     albertel 3117:     foreach my $key (keys(%$storehash)) {
                   3118:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3119:     }
1.47      www      3120:     $namevalue=~s/\&$//;
1.187     www      3121:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3122:     return critical
                   3123:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3124: }
                   3125: 
1.9       www      3126: # --------------------------------------------------------------------- Restore
                   3127: 
                   3128: sub restore {
1.124     www      3129:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3130:     my $home='';
                   3131: 
1.168     albertel 3132:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3133: 
1.122     albertel 3134:     if (!$symb) {
                   3135:       unless ($symb=escape(&symbread())) { return ''; }
                   3136:     } else {
1.213     www      3137:       $symb=&escape(&symbclean($symb));
1.122     albertel 3138:     }
1.188     www      3139:     if (!$namespace) { 
1.620     albertel 3140:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3141:           return ''; 
                   3142:        } 
                   3143:     }
1.620     albertel 3144:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3145:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3146:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3147:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3148: 
1.12      www      3149:     my %returnhash=();
1.800     albertel 3150:     foreach my $line (split(/\&/,$answer)) {
                   3151: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3152:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3153:     }
1.75      www      3154:     my $version;
                   3155:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3156:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3157:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3158:        }
1.75      www      3159:     }
1.13      www      3160:     return %returnhash;
1.34      www      3161: }
                   3162: 
                   3163: # ---------------------------------------------------------- Course Description
                   3164: 
                   3165: sub coursedescription {
1.731     albertel 3166:     my ($courseid,$args)=@_;
1.34      www      3167:     $courseid=~s/^\///;
1.49      www      3168:     $courseid=~s/\_/\//g;
1.34      www      3169:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3170:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3171:     my $normalid=$cdomain.'_'.$cnum;
                   3172:     # need to always cache even if we get errors otherwise we keep 
                   3173:     # trying and trying and trying to get the course description.
                   3174:     my %envhash=();
                   3175:     my %returnhash=();
1.731     albertel 3176:     
                   3177:     my $expiretime=600;
                   3178:     if ($env{'request.course.id'} eq $normalid) {
                   3179: 	$expiretime=120;
                   3180:     }
                   3181: 
                   3182:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3183:     if (!$args->{'freshen_cache'}
                   3184: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3185: 	foreach my $key (keys(%env)) {
                   3186: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3187: 	    my ($setting) = $1;
                   3188: 	    $returnhash{$setting} = $env{$key};
                   3189: 	}
                   3190: 	return %returnhash;
                   3191:     }
                   3192: 
                   3193:     # get the data agin
                   3194:     if (!$args->{'one_time'}) {
                   3195: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3196:     }
1.811     albertel 3197: 
1.34      www      3198:     if ($chome ne 'no_host') {
1.302     albertel 3199:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3200:        if (!exists($returnhash{'con_lost'})) {
                   3201:            $returnhash{'home'}= $chome;
                   3202: 	   $returnhash{'domain'} = $cdomain;
                   3203: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3204:            if (!defined($returnhash{'type'})) {
                   3205:                $returnhash{'type'} = 'Course';
                   3206:            }
1.130     albertel 3207:            while (my ($name,$value) = each %returnhash) {
1.53      www      3208:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3209:            }
1.270     www      3210:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3211:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3212: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3213:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3214:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3215:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3216:        }
                   3217:     }
1.731     albertel 3218:     if (!$args->{'one_time'}) {
                   3219: 	&appenv(%envhash);
                   3220:     }
1.302     albertel 3221:     return %returnhash;
1.461     www      3222: }
                   3223: 
                   3224: # -------------------------------------------------See if a user is privileged
                   3225: 
                   3226: sub privileged {
                   3227:     my ($username,$domain)=@_;
                   3228:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3229: 			&homeserver($username,$domain));
                   3230:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3231:     my $now=time;
                   3232:     if ($rolesdump ne '') {
1.800     albertel 3233:         foreach my $entry (split(/&/,$rolesdump)) {
                   3234: 	    if ($entry!~/^rolesdef_/) {
                   3235: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3236: 		$area=~s/\_\w\w$//;
                   3237: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3238: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3239: 		    my $active=1;
                   3240: 		    if ($tend) {
                   3241: 			if ($tend<$now) { $active=0; }
                   3242: 		    }
                   3243: 		    if ($tstart) {
                   3244: 			if ($tstart>$now) { $active=0; }
                   3245: 		    }
                   3246: 		    if ($active) { return 1; }
                   3247: 		}
                   3248: 	    }
                   3249: 	}
                   3250:     }
                   3251:     return 0;
1.9       www      3252: }
1.1       albertel 3253: 
1.103     harris41 3254: # -------------------------------------------------------- Get user privileges
1.11      www      3255: 
                   3256: sub rolesinit {
                   3257:     my ($domain,$username,$authhost)=@_;
                   3258:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3259:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3260:     my %allroles=();
1.678     raeburn  3261:     my %allgroups=();   
1.11      www      3262:     my $now=time;
1.743     albertel 3263:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3264:     my $group_privs;
1.11      www      3265: 
                   3266:     if ($rolesdump ne '') {
1.800     albertel 3267:         foreach my $entry (split(/&/,$rolesdump)) {
                   3268: 	  if ($entry!~/^rolesdef_/) {
                   3269:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3270: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3271:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3272: 	    if ($role=~/^cr/) { 
1.807     albertel 3273: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3274: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3275: 		    ($tend,$tstart)=split('_',$trest);
                   3276: 		} else {
                   3277: 		    $trole=$role;
                   3278: 		}
1.678     raeburn  3279:             } elsif ($role =~ m|^gr/|) {
                   3280:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3281:                 ($trole,$group_privs) = split(/\//,$trole);
                   3282:                 $group_privs = &unescape($group_privs);
1.587     albertel 3283: 	    } else {
                   3284: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3285: 	    }
1.743     albertel 3286: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3287: 					 $username);
                   3288: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3289:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3290:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3291:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3292: 		my $spec=$trole.'.'.$area;
                   3293: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3294: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3295:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3296:                 } elsif ($trole eq 'gr') {
                   3297:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3298: 		} else {
1.567     raeburn  3299:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3300: 		}
1.12      www      3301:             }
1.662     raeburn  3302:           }
1.191     harris41 3303:         }
1.743     albertel 3304:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3305:         $userroles{'user.adv'}    = $adv;
                   3306: 	$userroles{'user.author'} = $author;
1.620     albertel 3307:         $env{'user.adv'}=$adv;
1.11      www      3308:     }
1.743     albertel 3309:     return \%userroles;  
1.11      www      3310: }
                   3311: 
1.567     raeburn  3312: sub set_arearole {
                   3313:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3314: # log the associated role with the area
                   3315:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3316:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3317: }
                   3318: 
                   3319: sub custom_roleprivs {
                   3320:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3321:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3322:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3323:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3324:         my ($rdummy,$roledef)=
                   3325:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3326:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3327:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3328:             if (defined($syspriv)) {
                   3329:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3330:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3331:             }
                   3332:             if ($tdomain ne '') {
                   3333:                 if (defined($dompriv)) {
                   3334:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3335:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3336:                 }
                   3337:                 if (($trest ne '') && (defined($coursepriv))) {
                   3338:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3339:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3340:                 }
                   3341:             }
                   3342:         }
                   3343:     }
                   3344: }
                   3345: 
1.678     raeburn  3346: sub group_roleprivs {
                   3347:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3348:     my $access = 1;
                   3349:     my $now = time;
                   3350:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3351:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3352:     if ($access) {
1.811     albertel 3353:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3354:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3355:     }
                   3356: }
1.567     raeburn  3357: 
                   3358: sub standard_roleprivs {
                   3359:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3360:     if (defined($pr{$trole.':s'})) {
                   3361:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3362:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3363:     }
                   3364:     if ($tdomain ne '') {
                   3365:         if (defined($pr{$trole.':d'})) {
                   3366:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3367:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3368:         }
                   3369:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3370:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3371:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3372:         }
                   3373:     }
                   3374: }
                   3375: 
                   3376: sub set_userprivs {
1.678     raeburn  3377:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3378:     my $author=0;
                   3379:     my $adv=0;
1.678     raeburn  3380:     my %grouproles = ();
                   3381:     if (keys(%{$allgroups}) > 0) {
                   3382:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3383:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3384:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3385:                 $trole = $1;
                   3386:                 $area = $2;
1.681     raeburn  3387:                 $sec = $3;
                   3388:                 $extendedarea = $area.$sec;
                   3389:                 if (exists($$allgroups{$area})) {
                   3390:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3391:                         my $spec = $trole.'.'.$extendedarea;
                   3392:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3393:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3394:                     }
                   3395:                 }
                   3396:             }
                   3397:         }
                   3398:     }
1.800     albertel 3399:     foreach my $group (keys(%grouproles)) {
                   3400:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3401:     }
1.800     albertel 3402:     foreach my $role (keys(%{$allroles})) {
                   3403:         my %thesepriv;
                   3404:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3405:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3406:             if ($item ne '') {
                   3407:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3408:                 if ($restrictions eq '') {
                   3409:                     $thesepriv{$privilege}='F';
                   3410:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3411:                     $thesepriv{$privilege}.=$restrictions;
                   3412:                 }
                   3413:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3414:             }
                   3415:         }
                   3416:         my $thesestr='';
1.800     albertel 3417:         foreach my $priv (keys(%thesepriv)) {
                   3418: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3419: 	}
                   3420:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3421:     }
                   3422:     return ($author,$adv);
                   3423: }
                   3424: 
1.12      www      3425: # --------------------------------------------------------------- get interface
                   3426: 
                   3427: sub get {
1.131     albertel 3428:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3429:    my $items='';
1.800     albertel 3430:    foreach my $item (@$storearr) {
                   3431:        $items.=&escape($item).'&';
1.191     harris41 3432:    }
1.12      www      3433:    $items=~s/\&$//;
1.620     albertel 3434:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3435:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3436:    my $uhome=&homeserver($uname,$udomain);
                   3437: 
1.133     albertel 3438:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3439:    my @pairs=split(/\&/,$rep);
1.273     albertel 3440:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3441:      return @pairs;
                   3442:    }
1.15      www      3443:    my %returnhash=();
1.42      www      3444:    my $i=0;
1.800     albertel 3445:    foreach my $item (@$storearr) {
                   3446:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3447:       $i++;
1.191     harris41 3448:    }
1.15      www      3449:    return %returnhash;
1.27      www      3450: }
                   3451: 
                   3452: # --------------------------------------------------------------- del interface
                   3453: 
                   3454: sub del {
1.133     albertel 3455:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3456:    my $items='';
1.800     albertel 3457:    foreach my $item (@$storearr) {
                   3458:        $items.=&escape($item).'&';
1.191     harris41 3459:    }
1.27      www      3460:    $items=~s/\&$//;
1.620     albertel 3461:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3462:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3463:    my $uhome=&homeserver($uname,$udomain);
                   3464: 
                   3465:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3466: }
                   3467: 
                   3468: # -------------------------------------------------------------- dump interface
                   3469: 
                   3470: sub dump {
1.755     albertel 3471:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3472:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3473:     if (!$uname) { $uname=$env{'user.name'}; }
                   3474:     my $uhome=&homeserver($uname,$udomain);
                   3475:     if ($regexp) {
                   3476: 	$regexp=&escape($regexp);
                   3477:     } else {
                   3478: 	$regexp='.';
                   3479:     }
                   3480:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3481:     my @pairs=split(/\&/,$rep);
                   3482:     my %returnhash=();
                   3483:     foreach my $item (@pairs) {
                   3484: 	my ($key,$value)=split(/=/,$item,2);
                   3485: 	$key = &unescape($key);
                   3486: 	next if ($key =~ /^error: 2 /);
                   3487: 	$returnhash{$key}=&thaw_unescape($value);
                   3488:     }
                   3489:     return %returnhash;
1.407     www      3490: }
                   3491: 
1.717     albertel 3492: # --------------------------------------------------------- dumpstore interface
                   3493: 
                   3494: sub dumpstore {
                   3495:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3496:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3497:    if (!$uname) { $uname=$env{'user.name'}; }
                   3498:    my $uhome=&homeserver($uname,$udomain);
                   3499:    if ($regexp) {
                   3500:        $regexp=&escape($regexp);
                   3501:    } else {
                   3502:        $regexp='.';
                   3503:    }
                   3504:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3505:    my @pairs=split(/\&/,$rep);
                   3506:    my %returnhash=();
                   3507:    foreach my $item (@pairs) {
                   3508:        my ($key,$value)=split(/=/,$item,2);
                   3509:        next if ($key =~ /^error: 2 /);
                   3510:        $returnhash{$key}=&thaw_unescape($value);
                   3511:    }
                   3512:    return %returnhash;
1.717     albertel 3513: }
                   3514: 
1.407     www      3515: # -------------------------------------------------------------- keys interface
                   3516: 
                   3517: sub getkeys {
                   3518:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3519:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3520:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3521:    my $uhome=&homeserver($uname,$udomain);
                   3522:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3523:    my @keyarray=();
1.800     albertel 3524:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3525:       next if ($key =~ /^error: 2 /);
1.800     albertel 3526:       push(@keyarray,&unescape($key));
1.407     www      3527:    }
                   3528:    return @keyarray;
1.318     matthew  3529: }
                   3530: 
1.319     matthew  3531: # --------------------------------------------------------------- currentdump
                   3532: sub currentdump {
1.328     matthew  3533:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3534:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3535:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3536:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3537:    my $uhome = &homeserver($sname,$sdom);
                   3538:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3539:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3540:    #
1.318     matthew  3541:    my %returnhash=();
1.319     matthew  3542:    #
                   3543:    if ($rep eq "unknown_cmd") { 
                   3544:        # an old lond will not know currentdump
                   3545:        # Do a dump and make it look like a currentdump
1.822     albertel 3546:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3547:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3548:        my %hash = @tmp;
                   3549:        @tmp=();
1.424     matthew  3550:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3551:    } else {
                   3552:        my @pairs=split(/\&/,$rep);
1.800     albertel 3553:        foreach my $pair (@pairs) {
                   3554:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3555:            my ($symb,$param) = split(/:/,$key);
                   3556:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3557:                                                         &thaw_unescape($value);
1.319     matthew  3558:        }
1.191     harris41 3559:    }
1.12      www      3560:    return %returnhash;
1.424     matthew  3561: }
                   3562: 
                   3563: sub convert_dump_to_currentdump{
                   3564:     my %hash = %{shift()};
                   3565:     my %returnhash;
                   3566:     # Code ripped from lond, essentially.  The only difference
                   3567:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3568:     # we might run in to problems with parameter names =~ /^v\./
                   3569:     while (my ($key,$value) = each(%hash)) {
                   3570:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3571: 	$symb  = &unescape($symb);
                   3572: 	$param = &unescape($param);
1.424     matthew  3573:         next if ($v eq 'version' || $symb eq 'keys');
                   3574:         next if (exists($returnhash{$symb}) &&
                   3575:                  exists($returnhash{$symb}->{$param}) &&
                   3576:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3577:         $returnhash{$symb}->{$param}=$value;
                   3578:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3579:     }
                   3580:     #
                   3581:     # Remove all of the keys in the hashes which keep track of
                   3582:     # the version of the parameter.
                   3583:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3584:         # use a foreach because we are going to delete from the hash.
                   3585:         foreach my $key (keys(%$param_hash)) {
                   3586:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3587:         }
                   3588:     }
                   3589:     return \%returnhash;
1.12      www      3590: }
                   3591: 
1.627     albertel 3592: # ------------------------------------------------------ critical inc interface
                   3593: 
                   3594: sub cinc {
                   3595:     return &inc(@_,'critical');
                   3596: }
                   3597: 
1.449     matthew  3598: # --------------------------------------------------------------- inc interface
                   3599: 
                   3600: sub inc {
1.627     albertel 3601:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3602:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3603:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3604:     my $uhome=&homeserver($uname,$udomain);
                   3605:     my $items='';
                   3606:     if (! ref($store)) {
                   3607:         # got a single value, so use that instead
                   3608:         $items = &escape($store).'=&';
                   3609:     } elsif (ref($store) eq 'SCALAR') {
                   3610:         $items = &escape($$store).'=&';        
                   3611:     } elsif (ref($store) eq 'ARRAY') {
                   3612:         $items = join('=&',map {&escape($_);} @{$store});
                   3613:     } elsif (ref($store) eq 'HASH') {
                   3614:         while (my($key,$value) = each(%{$store})) {
                   3615:             $items.= &escape($key).'='.&escape($value).'&';
                   3616:         }
                   3617:     }
                   3618:     $items=~s/\&$//;
1.627     albertel 3619:     if ($critical) {
                   3620: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3621:     } else {
                   3622: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3623:     }
1.449     matthew  3624: }
                   3625: 
1.12      www      3626: # --------------------------------------------------------------- put interface
                   3627: 
                   3628: sub put {
1.134     albertel 3629:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3630:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3631:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3632:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3633:    my $items='';
1.800     albertel 3634:    foreach my $item (keys(%$storehash)) {
                   3635:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3636:    }
1.12      www      3637:    $items=~s/\&$//;
1.134     albertel 3638:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3639: }
                   3640: 
1.631     albertel 3641: # ------------------------------------------------------------ newput interface
                   3642: 
                   3643: sub newput {
                   3644:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3645:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3646:    if (!$uname) { $uname=$env{'user.name'}; }
                   3647:    my $uhome=&homeserver($uname,$udomain);
                   3648:    my $items='';
                   3649:    foreach my $key (keys(%$storehash)) {
                   3650:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3651:    }
                   3652:    $items=~s/\&$//;
                   3653:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3654: }
                   3655: 
                   3656: # ---------------------------------------------------------  putstore interface
                   3657: 
1.524     raeburn  3658: sub putstore {
1.715     albertel 3659:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3660:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3661:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3662:    my $uhome=&homeserver($uname,$udomain);
                   3663:    my $items='';
1.715     albertel 3664:    foreach my $key (keys(%$storehash)) {
                   3665:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3666:    }
1.715     albertel 3667:    $items=~s/\&$//;
1.716     albertel 3668:    my $esc_symb=&escape($symb);
                   3669:    my $esc_v=&escape($version);
1.715     albertel 3670:    my $reply =
1.716     albertel 3671:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3672: 	      $uhome);
                   3673:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3674:        # gfall back to way things use to be done
1.715     albertel 3675:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3676: 			    $uname);
1.524     raeburn  3677:    }
1.715     albertel 3678:    return $reply;
                   3679: }
                   3680: 
                   3681: sub old_putstore {
1.716     albertel 3682:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3683:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3684:     if (!$uname) { $uname=$env{'user.name'}; }
                   3685:     my $uhome=&homeserver($uname,$udomain);
                   3686:     my %newstorehash;
1.800     albertel 3687:     foreach my $item (keys(%$storehash)) {
                   3688: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3689: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3690:     }
                   3691:     my $items='';
                   3692:     my %allitems = ();
1.800     albertel 3693:     foreach my $item (keys(%newstorehash)) {
                   3694: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3695: 	    my $key = $1.':keys:'.$2;
                   3696: 	    $allitems{$key} .= $3.':';
                   3697: 	}
1.800     albertel 3698: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3699:     }
1.800     albertel 3700:     foreach my $item (keys(%allitems)) {
                   3701: 	$allitems{$item} =~ s/\:$//;
                   3702: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3703:     }
                   3704:     $items=~s/\&$//;
                   3705:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3706: }
                   3707: 
1.47      www      3708: # ------------------------------------------------------ critical put interface
                   3709: 
                   3710: sub cput {
1.134     albertel 3711:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3712:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3713:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3714:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3715:    my $items='';
1.800     albertel 3716:    foreach my $item (keys(%$storehash)) {
                   3717:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3718:    }
1.47      www      3719:    $items=~s/\&$//;
1.134     albertel 3720:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3721: }
                   3722: 
                   3723: # -------------------------------------------------------------- eget interface
                   3724: 
                   3725: sub eget {
1.133     albertel 3726:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3727:    my $items='';
1.800     albertel 3728:    foreach my $item (@$storearr) {
                   3729:        $items.=&escape($item).'&';
1.191     harris41 3730:    }
1.12      www      3731:    $items=~s/\&$//;
1.620     albertel 3732:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3733:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3734:    my $uhome=&homeserver($uname,$udomain);
                   3735:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3736:    my @pairs=split(/\&/,$rep);
                   3737:    my %returnhash=();
1.42      www      3738:    my $i=0;
1.800     albertel 3739:    foreach my $item (@$storearr) {
                   3740:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3741:       $i++;
1.191     harris41 3742:    }
1.12      www      3743:    return %returnhash;
                   3744: }
                   3745: 
1.667     albertel 3746: # ------------------------------------------------------------ tmpput interface
                   3747: sub tmpput {
1.802     raeburn  3748:     my ($storehash,$server,$context)=@_;
1.667     albertel 3749:     my $items='';
1.800     albertel 3750:     foreach my $item (keys(%$storehash)) {
                   3751: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3752:     }
                   3753:     $items=~s/\&$//;
1.802     raeburn  3754:     if (defined($context)) {
                   3755:         $items .= ':'.&escape($context);
                   3756:     }
1.667     albertel 3757:     return &reply("tmpput:$items",$server);
                   3758: }
                   3759: 
                   3760: # ------------------------------------------------------------ tmpget interface
                   3761: sub tmpget {
1.688     albertel 3762:     my ($token,$server)=@_;
                   3763:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3764:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3765:     my %returnhash;
                   3766:     foreach my $item (split(/\&/,$rep)) {
                   3767: 	my ($key,$value)=split(/=/,$item);
                   3768: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3769:     }
                   3770:     return %returnhash;
                   3771: }
                   3772: 
1.688     albertel 3773: # ------------------------------------------------------------ tmpget interface
                   3774: sub tmpdel {
                   3775:     my ($token,$server)=@_;
                   3776:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3777:     return &reply("tmpdel:$token",$server);
                   3778: }
                   3779: 
1.765     albertel 3780: # -------------------------------------------------- portfolio access checking
                   3781: 
                   3782: sub portfolio_access {
1.766     albertel 3783:     my ($requrl) = @_;
1.765     albertel 3784:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3785:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3786:     if ($result) {
                   3787:         my %setters;
                   3788:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3789:             my ($startblock,$endblock) =
                   3790:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3791:             if ($startblock && $endblock) {
                   3792:                 return 'B';
                   3793:             }
                   3794:         } else {
                   3795:             my ($startblock,$endblock) =
                   3796:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3797:             if ($startblock && $endblock) {
                   3798:                 return 'B';
                   3799:             }
                   3800:         }
                   3801:     }
1.765     albertel 3802:     if ($result eq 'ok') {
1.766     albertel 3803:        return 'F';
1.765     albertel 3804:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3805:        return 'A';
1.765     albertel 3806:     }
1.766     albertel 3807:     return '';
1.765     albertel 3808: }
                   3809: 
                   3810: sub get_portfolio_access {
1.767     albertel 3811:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3812: 
                   3813:     if (!ref($access_hash)) {
                   3814: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3815: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3816: 						   $file_name);
                   3817: 	$access_hash = $access_controls{$file_name};
                   3818:     }
                   3819: 
1.765     albertel 3820:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3821:     my $now = time;
                   3822:     if (ref($access_hash) eq 'HASH') {
                   3823:         foreach my $key (keys(%{$access_hash})) {
                   3824:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3825:             if ($start > $now) {
                   3826:                 next;
                   3827:             }
                   3828:             if ($end && $end<$now) {
                   3829:                 next;
                   3830:             }
                   3831:             if ($scope eq 'public') {
                   3832:                 $public = $key;
                   3833:                 last;
                   3834:             } elsif ($scope eq 'guest') {
                   3835:                 $guest = $key;
                   3836:             } elsif ($scope eq 'domains') {
                   3837:                 push(@domains,$key);
                   3838:             } elsif ($scope eq 'users') {
                   3839:                 push(@users,$key);
                   3840:             } elsif ($scope eq 'course') {
                   3841:                 push(@courses,$key);
                   3842:             } elsif ($scope eq 'group') {
                   3843:                 push(@groups,$key);
                   3844:             }
                   3845:         }
                   3846:         if ($public) {
                   3847:             return 'ok';
                   3848:         }
                   3849:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3850:             if ($guest) {
                   3851:                 return $guest;
                   3852:             }
                   3853:         } else {
                   3854:             if (@domains > 0) {
                   3855:                 foreach my $domkey (@domains) {
                   3856:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3857:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3858:                             return 'ok';
                   3859:                         }
                   3860:                     }
                   3861:                 }
                   3862:             }
                   3863:             if (@users > 0) {
                   3864:                 foreach my $userkey (@users) {
1.865     raeburn  3865:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3866:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3867:                             if (ref($item) eq 'HASH') {
                   3868:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3869:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3870:                                     return 'ok';
                   3871:                                 }
                   3872:                             }
                   3873:                         }
                   3874:                     } 
1.765     albertel 3875:                 }
                   3876:             }
                   3877:             my %roleshash;
                   3878:             my @courses_and_groups = @courses;
                   3879:             push(@courses_and_groups,@groups); 
                   3880:             if (@courses_and_groups > 0) {
                   3881:                 my (%allgroups,%allroles); 
                   3882:                 my ($start,$end,$role,$sec,$group);
                   3883:                 foreach my $envkey (%env) {
1.811     albertel 3884:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3885:                         my $cid = $2.'_'.$3; 
                   3886:                         if ($1 eq 'gr') {
                   3887:                             $group = $4;
                   3888:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3889:                         } else {
                   3890:                             if ($4 eq '') {
                   3891:                                 $sec = 'none';
                   3892:                             } else {
                   3893:                                 $sec = $4;
                   3894:                             }
                   3895:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3896:                         }
1.811     albertel 3897:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3898:                         my $cid = $2.'_'.$3;
                   3899:                         if ($4 eq '') {
                   3900:                             $sec = 'none';
                   3901:                         } else {
                   3902:                             $sec = $4;
                   3903:                         }
                   3904:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3905:                     }
                   3906:                 }
                   3907:                 if (keys(%allroles) == 0) {
                   3908:                     return;
                   3909:                 }
                   3910:                 foreach my $key (@courses_and_groups) {
                   3911:                     my %content = %{$$access_hash{$key}};
                   3912:                     my $cnum = $content{'number'};
                   3913:                     my $cdom = $content{'domain'};
                   3914:                     my $cid = $cdom.'_'.$cnum;
                   3915:                     if (!exists($allroles{$cid})) {
                   3916:                         next;
                   3917:                     }    
                   3918:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3919:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3920:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3921:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3922:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3923:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3924:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3925:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3926:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3927:                                         if (grep/^all$/,@sections) {
                   3928:                                             return 'ok';
                   3929:                                         } else {
                   3930:                                             if (grep/^$sec$/,@sections) {
                   3931:                                                 return 'ok';
                   3932:                                             }
                   3933:                                         }
                   3934:                                     }
                   3935:                                 }
                   3936:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3937:                                     if (grep/^none$/,@groups) {
                   3938:                                         return 'ok';
                   3939:                                     }
                   3940:                                 } else {
                   3941:                                     if (grep/^all$/,@groups) {
                   3942:                                         return 'ok';
                   3943:                                     } 
                   3944:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3945:                                         if (grep/^$group$/,@groups) {
                   3946:                                             return 'ok';
                   3947:                                         }
                   3948:                                     }
                   3949:                                 } 
                   3950:                             }
                   3951:                         }
                   3952:                     }
                   3953:                 }
                   3954:             }
                   3955:             if ($guest) {
                   3956:                 return $guest;
                   3957:             }
                   3958:         }
                   3959:     }
                   3960:     return;
                   3961: }
                   3962: 
                   3963: sub course_group_datechecker {
                   3964:     my ($dates,$now,$status) = @_;
                   3965:     my ($start,$end) = split(/\./,$dates);
                   3966:     if (!$start && !$end) {
                   3967:         return 'ok';
                   3968:     }
                   3969:     if (grep/^active$/,@{$status}) {
                   3970:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3971:             return 'ok';
                   3972:         }
                   3973:     }
                   3974:     if (grep/^previous$/,@{$status}) {
                   3975:         if ($end > $now ) {
                   3976:             return 'ok';
                   3977:         }
                   3978:     }
                   3979:     if (grep/^future$/,@{$status}) {
                   3980:         if ($start > $now) {
                   3981:             return 'ok';
                   3982:         }
                   3983:     }
                   3984:     return; 
                   3985: }
                   3986: 
                   3987: sub parse_portfolio_url {
                   3988:     my ($url) = @_;
                   3989: 
                   3990:     my ($type,$udom,$unum,$group,$file_name);
                   3991:     
1.823     albertel 3992:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3993: 	$type = 1;
                   3994:         $udom = $1;
                   3995:         $unum = $2;
                   3996:         $file_name = $3;
1.823     albertel 3997:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3998: 	$type = 2;
                   3999:         $udom = $1;
                   4000:         $unum = $2;
                   4001:         $group = $3;
                   4002:         $file_name = $3.'/'.$4;
                   4003:     }
                   4004:     if (wantarray) {
                   4005: 	return ($type,$udom,$unum,$file_name,$group);
                   4006:     }
                   4007:     return $type;
                   4008: }
                   4009: 
                   4010: sub is_portfolio_url {
                   4011:     my ($url) = @_;
                   4012:     return scalar(&parse_portfolio_url($url));
                   4013: }
                   4014: 
1.798     raeburn  4015: sub is_portfolio_file {
                   4016:     my ($file) = @_;
1.820     raeburn  4017:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4018:         return 1;
                   4019:     }
                   4020:     return;
                   4021: }
                   4022: 
                   4023: 
1.341     www      4024: # ---------------------------------------------- Custom access rule evaluation
                   4025: 
                   4026: sub customaccess {
                   4027:     my ($priv,$uri)=@_;
1.807     albertel 4028:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4029:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4030:     $udom = &LONCAPA::clean_domain($udom);
                   4031:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4032:     my $access=0;
1.800     albertel 4033:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4034: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4035: 	if ($type eq 'user') {
                   4036: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4037: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4038: 		if ($tdom) {
                   4039: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4040: 		}
1.896     albertel 4041: 		if ($tuname) {
                   4042: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4043: 		}
                   4044: 		$access=($effect eq 'allow');
                   4045: 		last;
                   4046: 	    }
                   4047: 	} else {
                   4048: 	    if ($role) {
                   4049: 		if ($role ne $urole) { next; }
                   4050: 	    }
                   4051: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4052: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4053: 		if ($tdom) {
                   4054: 		    if ($tdom ne $udom) { next; }
                   4055: 		}
                   4056: 		if ($tcrs) {
                   4057: 		    if ($tcrs ne $ucrs) { next; }
                   4058: 		}
                   4059: 		if ($tsec) {
                   4060: 		    if ($tsec ne $usec) { next; }
                   4061: 		}
                   4062: 		$access=($effect eq 'allow');
                   4063: 		last;
                   4064: 	    }
                   4065: 	    if ($realm eq '' && $role eq '') {
                   4066: 		$access=($effect eq 'allow');
                   4067: 	    }
1.402     bowersj2 4068: 	}
1.341     www      4069:     }
                   4070:     return $access;
                   4071: }
                   4072: 
1.103     harris41 4073: # ------------------------------------------------- Check for a user privilege
1.12      www      4074: 
                   4075: sub allowed {
1.810     raeburn  4076:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4077:     my $ver_orguri=$uri;
1.439     www      4078:     $uri=&deversion($uri);
1.152     www      4079:     my $orguri=$uri;
1.52      www      4080:     $uri=&declutter($uri);
1.809     raeburn  4081: 
1.810     raeburn  4082:     if ($priv eq 'evb') {
                   4083: # Evade communication block restrictions for specified role in a course
                   4084:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4085:             return $1;
                   4086:         } else {
                   4087:             return;
                   4088:         }
                   4089:     }
                   4090: 
1.620     albertel 4091:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4092: # Free bre access to adm and meta resources
1.775     albertel 4093:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4094: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4095: 	&& ($priv eq 'bre')) {
1.14      www      4096: 	return 'F';
1.159     www      4097:     }
                   4098: 
1.545     banghart 4099: # Free bre access to user's own portfolio contents
1.714     raeburn  4100:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4101:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4102: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4103:         my %setters;
                   4104:         my ($startblock,$endblock) = 
                   4105:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4106:         if ($startblock && $endblock) {
                   4107:             return 'B';
                   4108:         } else {
                   4109:             return 'F';
                   4110:         }
1.545     banghart 4111:     }
                   4112: 
1.762     raeburn  4113: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4114:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4115:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4116:         if (exists($env{'request.course.id'})) {
                   4117:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4118:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4119:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4120:                 my $courseprivid=$env{'request.course.id'};
                   4121:                 $courseprivid=~s/\_/\//;
                   4122:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4123:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4124:                     return $1; 
1.762     raeburn  4125:                 } else {
                   4126:                     if ($env{'request.course.sec'}) {
                   4127:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4128:                     }
                   4129:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4130:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4131:                         return $2;
                   4132:                     }
1.714     raeburn  4133:                 }
                   4134:             }
                   4135:         }
                   4136:     }
                   4137: 
1.159     www      4138: # Free bre to public access
                   4139: 
                   4140:     if ($priv eq 'bre') {
1.238     www      4141:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4142: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4143:            return 'F'; 
                   4144:         }
1.238     www      4145:         if ($copyright eq 'priv') {
                   4146:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4147: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4148: 		return '';
                   4149:             }
                   4150:         }
                   4151:         if ($copyright eq 'domain') {
                   4152:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4153: 	    unless (($env{'user.domain'} eq $1) ||
                   4154:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4155: 		return '';
                   4156:             }
1.262     matthew  4157:         }
1.620     albertel 4158:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4159:             # Library role, so allow browsing of resources in this domain.
                   4160:             return 'F';
1.238     www      4161:         }
1.341     www      4162:         if ($copyright eq 'custom') {
                   4163: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4164:         }
1.14      www      4165:     }
1.264     matthew  4166:     # Domain coordinator is trying to create a course
1.620     albertel 4167:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4168:         # uri is the requested domain in this case.
                   4169:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4170:         # a role of dc for the domain in question.
1.620     albertel 4171:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4172:     }
1.29      www      4173: 
1.52      www      4174:     my $thisallowed='';
                   4175:     my $statecond=0;
                   4176:     my $courseprivid='';
                   4177: 
                   4178: # Course
                   4179: 
1.620     albertel 4180:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4181:        $thisallowed.=$1;
                   4182:     }
1.29      www      4183: 
1.52      www      4184: # Domain
                   4185: 
1.620     albertel 4186:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4187:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4188:        $thisallowed.=$1;
                   4189:     }
1.52      www      4190: 
                   4191: # Course: uri itself is a course
1.66      www      4192:     my $courseuri=$uri;
                   4193:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4194:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4195: 
1.620     albertel 4196:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4197:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4198:        $thisallowed.=$1;
                   4199:     }
1.29      www      4200: 
1.665     albertel 4201: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4202: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4203:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4204: 	$thisallowed='';
1.671     raeburn  4205:         my ($match)=&is_on_map($uri);
                   4206:         if ($match) {
                   4207:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4208:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4209:                 $thisallowed.=$1;
                   4210:             }
                   4211:         } else {
1.705     albertel 4212:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4213:             if ($refuri) {
                   4214:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4215:                     $thisallowed='F';
1.671     raeburn  4216:                 } else {
                   4217:                     $refuri=&declutter($refuri);
                   4218:                     my ($match) = &is_on_map($refuri);
                   4219:                     if ($match) {
                   4220:                         $thisallowed='F';
                   4221:                     }
1.669     raeburn  4222:                 }
1.671     raeburn  4223:             }
                   4224:         }
1.314     www      4225:     }
1.492     albertel 4226: 
1.766     albertel 4227:     if ($priv eq 'bre'
                   4228: 	&& $thisallowed ne 'F' 
                   4229: 	&& $thisallowed ne '2'
                   4230: 	&& &is_portfolio_url($uri)) {
                   4231: 	$thisallowed = &portfolio_access($uri);
                   4232:     }
                   4233:     
1.52      www      4234: # Full access at system, domain or course-wide level? Exit.
1.29      www      4235: 
                   4236:     if ($thisallowed=~/F/) {
                   4237: 	return 'F';
                   4238:     }
                   4239: 
1.52      www      4240: # If this is generating or modifying users, exit with special codes
1.29      www      4241: 
1.643     www      4242:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4243: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4244: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4245: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4246: 	    unless ($auname) { return $thisallowed; }
                   4247: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4248: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4249: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4250: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4251: 	}
1.52      www      4252: 	return $thisallowed;
                   4253:     }
                   4254: #
1.103     harris41 4255: # Gathered so far: system, domain and course wide privileges
1.52      www      4256: #
                   4257: # Course: See if uri or referer is an individual resource that is part of 
                   4258: # the course
                   4259: 
1.620     albertel 4260:     if ($env{'request.course.id'}) {
1.232     www      4261: 
1.620     albertel 4262:        $courseprivid=$env{'request.course.id'};
                   4263:        if ($env{'request.course.sec'}) {
                   4264:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4265:        }
                   4266:        $courseprivid=~s/\_/\//;
                   4267:        my $checkreferer=1;
1.232     www      4268:        my ($match,$cond)=&is_on_map($uri);
                   4269:        if ($match) {
                   4270:            $statecond=$cond;
1.620     albertel 4271:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4272:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4273:                $thisallowed.=$1;
                   4274:                $checkreferer=0;
                   4275:            }
1.29      www      4276:        }
1.83      www      4277:        
1.148     www      4278:        if ($checkreferer) {
1.620     albertel 4279: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4280:             unless ($refuri) {
1.800     albertel 4281:                 foreach my $key (keys(%env)) {
                   4282: 		    if ($key=~/^httpref\..*\*/) {
                   4283: 			my $pattern=$key;
1.156     www      4284:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4285:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4286:                         $pattern=~s/\//\\\//g;
1.152     www      4287:                         if ($orguri=~/$pattern/) {
1.800     albertel 4288: 			    $refuri=$env{$key};
1.148     www      4289:                         }
                   4290:                     }
1.191     harris41 4291:                 }
1.148     www      4292:             }
1.232     www      4293: 
1.148     www      4294:          if ($refuri) { 
1.152     www      4295: 	  $refuri=&declutter($refuri);
1.232     www      4296:           my ($match,$cond)=&is_on_map($refuri);
                   4297:             if ($match) {
                   4298:               my $refstatecond=$cond;
1.620     albertel 4299:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4300:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4301:                   $thisallowed.=$1;
1.53      www      4302:                   $uri=$refuri;
                   4303:                   $statecond=$refstatecond;
1.52      www      4304:               }
                   4305:           }
1.148     www      4306:         }
1.29      www      4307:        }
1.52      www      4308:    }
1.29      www      4309: 
1.52      www      4310: #
1.103     harris41 4311: # Gathered now: all privileges that could apply, and condition number
1.52      www      4312: # 
                   4313: #
                   4314: # Full or no access?
                   4315: #
1.29      www      4316: 
1.52      www      4317:     if ($thisallowed=~/F/) {
                   4318: 	return 'F';
                   4319:     }
1.29      www      4320: 
1.52      www      4321:     unless ($thisallowed) {
                   4322:         return '';
                   4323:     }
1.29      www      4324: 
1.52      www      4325: # Restrictions exist, deal with them
                   4326: #
                   4327: #   C:according to course preferences
                   4328: #   R:according to resource settings
                   4329: #   L:unless locked
                   4330: #   X:according to user session state
                   4331: #
                   4332: 
                   4333: # Possibly locked functionality, check all courses
1.54      www      4334: # Locks might take effect only after 10 minutes cache expiration for other
                   4335: # courses, and 2 minutes for current course
1.52      www      4336: 
                   4337:     my $envkey;
                   4338:     if ($thisallowed=~/L/) {
1.620     albertel 4339:         foreach $envkey (keys %env) {
1.54      www      4340:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4341:                my $courseid=$2;
                   4342:                my $roleid=$1.'.'.$2;
1.92      www      4343:                $courseid=~s/^\///;
1.54      www      4344:                my $expiretime=600;
1.620     albertel 4345:                if ($env{'request.role'} eq $roleid) {
1.54      www      4346: 		  $expiretime=120;
                   4347:                }
                   4348: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4349:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4350:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4351: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4352:                }
1.620     albertel 4353:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4354:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4355: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4356:                        &log($env{'user.domain'},$env{'user.name'},
                   4357:                             $env{'user.home'},
1.57      www      4358:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4359:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4360:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4361: 		       return '';
                   4362:                    }
                   4363:                }
1.620     albertel 4364:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4365:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4366: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4367:                        &log($env{'user.domain'},$env{'user.name'},
                   4368:                             $env{'user.home'},
1.57      www      4369:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4370:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4371:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4372: 		       return '';
                   4373:                    }
                   4374:                }
                   4375: 	   }
1.29      www      4376:        }
1.52      www      4377:     }
                   4378:    
                   4379: #
                   4380: # Rest of the restrictions depend on selected course
                   4381: #
                   4382: 
1.620     albertel 4383:     unless ($env{'request.course.id'}) {
1.766     albertel 4384: 	if ($thisallowed eq 'A') {
                   4385: 	    return 'A';
1.814     raeburn  4386:         } elsif ($thisallowed eq 'B') {
                   4387:             return 'B';
1.766     albertel 4388: 	} else {
                   4389: 	    return '1';
                   4390: 	}
1.52      www      4391:     }
1.29      www      4392: 
1.52      www      4393: #
                   4394: # Now user is definitely in a course
                   4395: #
1.53      www      4396: 
                   4397: 
                   4398: # Course preferences
                   4399: 
                   4400:    if ($thisallowed=~/C/) {
1.620     albertel 4401:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4402:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4403:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4404: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4405: 	   if ($priv ne 'pch') { 
                   4406: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4407: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4408: 			$env{'request.course.id'});
                   4409: 	   }
1.237     www      4410:            return '';
                   4411:        }
                   4412: 
1.620     albertel 4413:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4414: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4415: 	   if ($priv ne 'pch') { 
                   4416: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4417: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4418: 			$env{'request.course.id'});
                   4419: 	   }
1.54      www      4420:            return '';
                   4421:        }
1.53      www      4422:    }
                   4423: 
                   4424: # Resource preferences
                   4425: 
                   4426:    if ($thisallowed=~/R/) {
1.620     albertel 4427:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4428:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4429: 	   if ($priv ne 'pch') { 
                   4430: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4431: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4432: 	   }
                   4433: 	   return '';
1.54      www      4434:        }
1.53      www      4435:    }
1.30      www      4436: 
1.246     www      4437: # Restricted by state or randomout?
1.30      www      4438: 
1.52      www      4439:    if ($thisallowed=~/X/) {
1.620     albertel 4440:       if ($env{'acc.randomout'}) {
1.579     albertel 4441: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4442:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4443:             return ''; 
                   4444:          }
1.247     www      4445:       }
                   4446:       if (&condval($statecond)) {
1.52      www      4447: 	 return '2';
                   4448:       } else {
                   4449:          return '';
                   4450:       }
                   4451:    }
1.30      www      4452: 
1.766     albertel 4453:     if ($thisallowed eq 'A') {
                   4454: 	return 'A';
1.814     raeburn  4455:     } elsif ($thisallowed eq 'B') {
                   4456:         return 'B';
1.766     albertel 4457:     }
1.52      www      4458:    return 'F';
1.232     www      4459: }
                   4460: 
1.710     albertel 4461: sub split_uri_for_cond {
                   4462:     my $uri=&deversion(&declutter(shift));
                   4463:     my @uriparts=split(/\//,$uri);
                   4464:     my $filename=pop(@uriparts);
                   4465:     my $pathname=join('/',@uriparts);
                   4466:     return ($pathname,$filename);
                   4467: }
1.232     www      4468: # --------------------------------------------------- Is a resource on the map?
                   4469: 
                   4470: sub is_on_map {
1.710     albertel 4471:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4472:     #Trying to find the conditional for the file
1.620     albertel 4473:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4474: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4475:     if ($match) {
1.289     bowersj2 4476: 	return (1,$1);
                   4477:     } else {
1.434     www      4478: 	return (0,0);
1.289     bowersj2 4479:     }
1.12      www      4480: }
                   4481: 
1.427     www      4482: # --------------------------------------------------------- Get symb from alias
                   4483: 
                   4484: sub get_symb_from_alias {
                   4485:     my $symb=shift;
                   4486:     my ($map,$resid,$url)=&decode_symb($symb);
                   4487: # Already is a symb
                   4488:     if ($url) { return $symb; }
                   4489: # Must be an alias
                   4490:     my $aliassymb='';
                   4491:     my %bighash;
1.620     albertel 4492:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4493:                             &GDBM_READER(),0640)) {
                   4494:         my $rid=$bighash{'mapalias_'.$symb};
                   4495: 	if ($rid) {
                   4496: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4497: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4498: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4499: 	}
                   4500:         untie %bighash;
                   4501:     }
                   4502:     return $aliassymb;
                   4503: }
                   4504: 
1.12      www      4505: # ----------------------------------------------------------------- Define Role
                   4506: 
                   4507: sub definerole {
                   4508:   if (allowed('mcr','/')) {
                   4509:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4510:     foreach my $role (split(':',$sysrole)) {
                   4511: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4512:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4513:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4514: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4515:                return "refused:s:$crole&$cqual"; 
                   4516:             }
                   4517:         }
1.191     harris41 4518:     }
1.800     albertel 4519:     foreach my $role (split(':',$domrole)) {
                   4520: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4521:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4522:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4523: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4524:                return "refused:d:$crole&$cqual"; 
                   4525:             }
                   4526:         }
1.191     harris41 4527:     }
1.800     albertel 4528:     foreach my $role (split(':',$courole)) {
                   4529: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4530:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4531:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4532: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4533:                return "refused:c:$crole&$cqual"; 
                   4534:             }
                   4535:         }
1.191     harris41 4536:     }
1.620     albertel 4537:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4538:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4539: 	        "rolesdef_$rolename=".
                   4540:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4541:     return reply($command,$env{'user.home'});
1.12      www      4542:   } else {
                   4543:     return 'refused';
                   4544:   }
1.105     harris41 4545: }
                   4546: 
                   4547: # ---------------- Make a metadata query against the network of library servers
                   4548: 
                   4549: sub metadata_query {
1.244     matthew  4550:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4551:     my %rhash;
1.845     albertel 4552:     my %libserv = &all_library();
1.244     matthew  4553:     my @server_list = (defined($server_array) ? @$server_array
                   4554:                                               : keys(%libserv) );
                   4555:     for my $server (@server_list) {
1.118     harris41 4556: 	unless ($custom or $customshow) {
                   4557: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4558: 	    $rhash{$server}=$reply;
                   4559: 	}
                   4560: 	else {
                   4561: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4562: 			     &escape($custom).':'.&escape($customshow),
                   4563: 			     $server);
                   4564: 	    $rhash{$server}=$reply;
                   4565: 	}
1.112     harris41 4566:     }
1.118     harris41 4567:     return \%rhash;
1.240     www      4568: }
                   4569: 
                   4570: # ----------------------------------------- Send log queries and wait for reply
                   4571: 
                   4572: sub log_query {
                   4573:     my ($uname,$udom,$query,%filters)=@_;
                   4574:     my $uhome=&homeserver($uname,$udom);
                   4575:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4576:     my $uhost=&hostname($uhome);
1.800     albertel 4577:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4578:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4579:                        $uhome);
1.479     albertel 4580:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4581:     return get_query_reply($queryid);
                   4582: }
                   4583: 
1.818     raeburn  4584: # -------------------------- Update MySQL table for portfolio file
                   4585: 
                   4586: sub update_portfolio_table {
1.821     raeburn  4587:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4588:     my $homeserver = &homeserver($uname,$udom);
                   4589:     my $queryid=
1.821     raeburn  4590:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4591:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4592:     my $reply = &get_query_reply($queryid);
                   4593:     return $reply;
                   4594: }
                   4595: 
1.899     raeburn  4596: # -------------------------- Update MySQL allusers table
                   4597: 
                   4598: sub update_allusers_table {
                   4599:     my ($uname,$udom,$names) = @_;
                   4600:     my $homeserver = &homeserver($uname,$udom);
                   4601:     my $queryid=
                   4602:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4603:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4604:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4605:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4606:                'generation='.&escape($names->{'generation'}).'%%'.
                   4607:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4608:                'id='.&escape($names->{'id'}),$homeserver);
                   4609:     my $reply = &get_query_reply($queryid);
                   4610:     return $reply;
                   4611: }
                   4612: 
1.508     raeburn  4613: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4614: 
                   4615: sub fetch_enrollment_query {
1.511     raeburn  4616:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4617:     my $homeserver;
1.547     raeburn  4618:     my $maxtries = 1;
1.508     raeburn  4619:     if ($context eq 'automated') {
                   4620:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4621:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4622:     } else {
                   4623:         $homeserver = &homeserver($cnum,$dom);
                   4624:     }
1.838     albertel 4625:     my $host=&hostname($homeserver);
1.506     raeburn  4626:     my $cmd = '';
1.800     albertel 4627:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4628:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4629:     }
                   4630:     $cmd =~ s/%%$//;
                   4631:     $cmd = &escape($cmd);
                   4632:     my $query = 'fetchenrollment';
1.620     albertel 4633:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4634:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4635:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4636:         return 'error: '.$queryid;
                   4637:     }
1.506     raeburn  4638:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4639:     my $tries = 1;
                   4640:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4641:         $reply = &get_query_reply($queryid);
                   4642:         $tries ++;
                   4643:     }
1.526     raeburn  4644:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4645:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4646:     } else {
1.901     albertel 4647:         my @responses = split(/:/,$reply);
1.515     raeburn  4648:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4649:             foreach my $line (@responses) {
                   4650:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4651:                 $$replyref{$key} = $value;
                   4652:             }
                   4653:         } else {
1.506     raeburn  4654:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4655:             foreach my $line (@responses) {
                   4656:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4657:                 $$replyref{$key} = $value;
                   4658:                 if ($value > 0) {
1.800     albertel 4659:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4660:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4661:                         my $destname = $pathname.'/'.$filename;
                   4662:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4663:                         if ($xml_classlist =~ /^error/) {
                   4664:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4665:                         } else {
1.506     raeburn  4666:                             if ( open(FILE,">$destname") ) {
                   4667:                                 print FILE &unescape($xml_classlist);
                   4668:                                 close(FILE);
1.526     raeburn  4669:                             } else {
                   4670:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4671:                             }
                   4672:                         }
                   4673:                     }
                   4674:                 }
                   4675:             }
                   4676:         }
                   4677:         return 'ok';
                   4678:     }
                   4679:     return 'error';
                   4680: }
                   4681: 
1.242     www      4682: sub get_query_reply {
                   4683:     my $queryid=shift;
1.240     www      4684:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4685:     my $reply='';
                   4686:     for (1..100) {
                   4687: 	sleep 2;
                   4688:         if (-e $replyfile.'.end') {
1.448     albertel 4689: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4690: 		$reply = join('',<$fh>);
                   4691: 		close($fh);
1.240     www      4692: 	   } else { return 'error: reply_file_error'; }
1.242     www      4693:            return &unescape($reply);
                   4694: 	}
1.240     www      4695:     }
1.242     www      4696:     return 'timeout:'.$queryid;
1.240     www      4697: }
                   4698: 
                   4699: sub courselog_query {
1.241     www      4700: #
                   4701: # possible filters:
                   4702: # url: url or symb
                   4703: # username
                   4704: # domain
                   4705: # action: view, submit, grade
                   4706: # start: timestamp
                   4707: # end: timestamp
                   4708: #
1.240     www      4709:     my (%filters)=@_;
1.620     albertel 4710:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4711:     if ($filters{'url'}) {
                   4712: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4713:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4714:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4715:     }
1.620     albertel 4716:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4717:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4718:     return &log_query($cname,$cdom,'courselog',%filters);
                   4719: }
                   4720: 
                   4721: sub userlog_query {
1.858     raeburn  4722: #
                   4723: # possible filters:
                   4724: # action: log check role
                   4725: # start: timestamp
                   4726: # end: timestamp
                   4727: #
1.240     www      4728:     my ($uname,$udom,%filters)=@_;
                   4729:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4730: }
                   4731: 
1.506     raeburn  4732: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4733: 
                   4734: sub auto_run {
1.508     raeburn  4735:     my ($cnum,$cdom) = @_;
1.876     raeburn  4736:     my $response = 0;
                   4737:     my $settings;
                   4738:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4739:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4740:         $settings = $domconfig{'autoenroll'};
                   4741:         if ($settings->{'run'} eq '1') {
                   4742:             $response = 1;
                   4743:         }
                   4744:     } else {
                   4745:         my $homeserver = &homeserver($cnum,$cdom);
                   4746:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4747:     }
1.506     raeburn  4748:     return $response;
                   4749: }
1.776     albertel 4750: 
1.506     raeburn  4751: sub auto_get_sections {
1.508     raeburn  4752:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4753:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4754:     my @secs = ();
1.511     raeburn  4755:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4756:     unless ($response eq 'refused') {
1.901     albertel 4757:         @secs = split(/:/,$response);
1.506     raeburn  4758:     }
                   4759:     return @secs;
                   4760: }
1.776     albertel 4761: 
1.506     raeburn  4762: sub auto_new_course {
1.508     raeburn  4763:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4764:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4765:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4766:     return $response;
                   4767: }
1.776     albertel 4768: 
1.506     raeburn  4769: sub auto_validate_courseID {
1.508     raeburn  4770:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4771:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4772:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4773:     return $response;
                   4774: }
1.776     albertel 4775: 
1.506     raeburn  4776: sub auto_create_password {
1.873     raeburn  4777:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4778:     my ($homeserver,$response);
1.506     raeburn  4779:     my $create_passwd = 0;
                   4780:     my $authchk = '';
1.873     raeburn  4781:     if ($udom =~ /^$match_domain$/) {
                   4782:         $homeserver = &domain($udom,'primary');
                   4783:     }
                   4784:     if ($homeserver eq '') {
                   4785:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4786:             $homeserver = &homeserver($cnum,$cdom);
                   4787:         }
                   4788:     }
                   4789:     if ($homeserver eq '') {
                   4790:         $authchk = 'nodomain';
1.506     raeburn  4791:     } else {
1.873     raeburn  4792:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4793:         if ($response eq 'refused') {
                   4794:             $authchk = 'refused';
                   4795:         } else {
1.901     albertel 4796:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4797:         }
1.506     raeburn  4798:     }
                   4799:     return ($authparam,$create_passwd,$authchk);
                   4800: }
                   4801: 
1.706     raeburn  4802: sub auto_photo_permission {
                   4803:     my ($cnum,$cdom,$students) = @_;
                   4804:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4805:     my ($outcome,$perm_reqd,$conditions) = 
                   4806: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4807:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4808: 	return (undef,undef);
                   4809:     }
1.706     raeburn  4810:     return ($outcome,$perm_reqd,$conditions);
                   4811: }
                   4812: 
                   4813: sub auto_checkphotos {
                   4814:     my ($uname,$udom,$pid) = @_;
                   4815:     my $homeserver = &homeserver($uname,$udom);
                   4816:     my ($result,$resulttype);
                   4817:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4818: 				   &escape($uname).':'.&escape($pid),
                   4819: 				   $homeserver));
1.709     albertel 4820:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4821: 	return (undef,undef);
                   4822:     }
1.706     raeburn  4823:     if ($outcome) {
                   4824:         ($result,$resulttype) = split(/:/,$outcome);
                   4825:     } 
                   4826:     return ($result,$resulttype);
                   4827: }
                   4828: 
                   4829: sub auto_photochoice {
                   4830:     my ($cnum,$cdom) = @_;
                   4831:     my $homeserver = &homeserver($cnum,$cdom);
                   4832:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4833: 						       &escape($cdom),
                   4834: 						       $homeserver)));
1.709     albertel 4835:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4836: 	return (undef,undef);
                   4837:     }
1.706     raeburn  4838:     return ($update,$comment);
                   4839: }
                   4840: 
                   4841: sub auto_photoupdate {
                   4842:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4843:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4844:     my $host=&hostname($homeserver);
1.706     raeburn  4845:     my $cmd = '';
                   4846:     my $maxtries = 1;
1.800     albertel 4847:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4848:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4849:     }
                   4850:     $cmd =~ s/%%$//;
                   4851:     $cmd = &escape($cmd);
                   4852:     my $query = 'institutionalphotos';
                   4853:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4854:     unless ($queryid=~/^\Q$host\E\_/) {
                   4855:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4856:         return 'error: '.$queryid;
                   4857:     }
                   4858:     my $reply = &get_query_reply($queryid);
                   4859:     my $tries = 1;
                   4860:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4861:         $reply = &get_query_reply($queryid);
                   4862:         $tries ++;
                   4863:     }
                   4864:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4865:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4866:     } else {
                   4867:         my @responses = split(/:/,$reply);
                   4868:         my $outcome = shift(@responses); 
                   4869:         foreach my $item (@responses) {
                   4870:             my ($key,$value) = split(/=/,$item);
                   4871:             $$photo{$key} = $value;
                   4872:         }
                   4873:         return $outcome;
                   4874:     }
                   4875:     return 'error';
                   4876: }
                   4877: 
1.521     raeburn  4878: sub auto_instcode_format {
1.793     albertel 4879:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4880: 	$cat_order) = @_;
1.521     raeburn  4881:     my $courses = '';
1.772     raeburn  4882:     my @homeservers;
1.521     raeburn  4883:     if ($caller eq 'global') {
1.841     albertel 4884: 	my %servers = &get_servers($codedom,'library');
                   4885: 	foreach my $tryserver (keys(%servers)) {
                   4886: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4887: 		push(@homeservers,$tryserver);
                   4888: 	    }
1.584     raeburn  4889:         }
1.521     raeburn  4890:     } else {
1.772     raeburn  4891:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4892:     }
1.793     albertel 4893:     foreach my $code (keys(%{$instcodes})) {
                   4894:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4895:     }
                   4896:     chop($courses);
1.772     raeburn  4897:     my $ok_response = 0;
                   4898:     my $response;
                   4899:     while (@homeservers > 0 && $ok_response == 0) {
                   4900:         my $server = shift(@homeservers); 
                   4901:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4902:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4903:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4904: 		split(/:/,$response);
1.772     raeburn  4905:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4906:             push(@{$codetitles},&str2array($codetitles_str));
                   4907:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4908:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4909:             $ok_response = 1;
                   4910:         }
                   4911:     }
                   4912:     if ($ok_response) {
1.521     raeburn  4913:         return 'ok';
1.772     raeburn  4914:     } else {
                   4915:         return $response;
1.521     raeburn  4916:     }
                   4917: }
                   4918: 
1.792     raeburn  4919: sub auto_instcode_defaults {
                   4920:     my ($domain,$returnhash,$code_order) = @_;
                   4921:     my @homeservers;
1.841     albertel 4922: 
                   4923:     my %servers = &get_servers($domain,'library');
                   4924:     foreach my $tryserver (keys(%servers)) {
                   4925: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4926: 	    push(@homeservers,$tryserver);
                   4927: 	}
1.792     raeburn  4928:     }
1.841     albertel 4929: 
1.792     raeburn  4930:     my $response;
1.841     albertel 4931:     foreach my $server (@homeservers) {
1.792     raeburn  4932:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4933:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4934: 	
                   4935: 	foreach my $pair (split(/\&/,$response)) {
                   4936: 	    my ($name,$value)=split(/\=/,$pair);
                   4937: 	    if ($name eq 'code_order') {
                   4938: 		@{$code_order} = split(/\&/,&unescape($value));
                   4939: 	    } else {
                   4940: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4941: 	    }
                   4942: 	}
                   4943: 	return 'ok';
1.792     raeburn  4944:     }
1.841     albertel 4945: 
                   4946:     return $response;
1.792     raeburn  4947: } 
                   4948: 
1.777     albertel 4949: sub auto_validate_class_sec {
1.773     raeburn  4950:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4951:     my $homeserver = &homeserver($cnum,$cdom);
                   4952:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4953:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4954:     return $response;
                   4955: }
                   4956: 
1.679     raeburn  4957: # ------------------------------------------------------- Course Group routines
                   4958: 
                   4959: sub get_coursegroups {
1.809     raeburn  4960:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4961:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4962: }
                   4963: 
1.679     raeburn  4964: sub modify_coursegroup {
                   4965:     my ($cdom,$cnum,$groupsettings) = @_;
                   4966:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4967: }
                   4968: 
1.809     raeburn  4969: sub toggle_coursegroup_status {
                   4970:     my ($cdom,$cnum,$group,$action) = @_;
                   4971:     my ($from_namespace,$to_namespace);
                   4972:     if ($action eq 'delete') {
                   4973:         $from_namespace = 'coursegroups';
                   4974:         $to_namespace = 'deleted_groups';
                   4975:     } else {
                   4976:         $from_namespace = 'deleted_groups';
                   4977:         $to_namespace = 'coursegroups';
                   4978:     }
                   4979:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4980:     if (my $tmp = &error(%curr_group)) {
                   4981:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4982:         return ('read error',$tmp);
                   4983:     } else {
                   4984:         my %savedsettings = %curr_group; 
1.809     raeburn  4985:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4986:         my $deloutcome;
                   4987:         if ($result eq 'ok') {
1.809     raeburn  4988:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4989:         } else {
                   4990:             return ('write error',$result);
                   4991:         }
                   4992:         if ($deloutcome eq 'ok') {
                   4993:             return 'ok';
                   4994:         } else {
                   4995:             return ('delete error',$deloutcome);
                   4996:         }
                   4997:     }
                   4998: }
                   4999: 
1.679     raeburn  5000: sub modify_group_roles {
                   5001:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5002:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5003:     my $role = 'gr/'.&escape($userprivs);
                   5004:     my ($uname,$udom) = split(/:/,$user);
                   5005:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5006:     if ($result eq 'ok') {
                   5007:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5008:     }
1.679     raeburn  5009:     return $result;
                   5010: }
                   5011: 
                   5012: sub modify_coursegroup_membership {
                   5013:     my ($cdom,$cnum,$membership) = @_;
                   5014:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5015:     return $result;
                   5016: }
                   5017: 
1.682     raeburn  5018: sub get_active_groups {
                   5019:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5020:     my $now = time;
                   5021:     my %groups = ();
                   5022:     foreach my $key (keys(%env)) {
1.811     albertel 5023:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5024:             my ($start,$end) = split(/\./,$env{$key});
                   5025:             if (($end!=0) && ($end<$now)) { next; }
                   5026:             if (($start!=0) && ($start>$now)) { next; }
                   5027:             if ($1 eq $cdom && $2 eq $cnum) {
                   5028:                 $groups{$3} = $env{$key} ;
                   5029:             }
                   5030:         }
                   5031:     }
                   5032:     return %groups;
                   5033: }
                   5034: 
1.683     raeburn  5035: sub get_group_membership {
                   5036:     my ($cdom,$cnum,$group) = @_;
                   5037:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5038: }
                   5039: 
                   5040: sub get_users_groups {
                   5041:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5042:     my @usersgroups;
1.683     raeburn  5043:     my $cachetime=1800;
                   5044: 
                   5045:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5046:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5047:     if (defined($cached)) {
1.734     albertel 5048:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5049:     } else {  
                   5050:         $grouplist = '';
1.816     raeburn  5051:         my $courseurl = &courseid_to_courseurl($courseid);
                   5052:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5053:         my $access_end = $env{'course.'.$courseid.
                   5054:                               '.default_enrollment_end_date'};
                   5055:         my $now = time;
                   5056:         foreach my $key (keys(%roleshash)) {
                   5057:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5058:                 my $group = $1;
                   5059:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5060:                     my $start = $2;
                   5061:                     my $end = $1;
                   5062:                     if ($start == -1) { next; } # deleted from group
                   5063:                     if (($start!=0) && ($start>$now)) { next; }
                   5064:                     if (($end!=0) && ($end<$now)) {
                   5065:                         if ($access_end && $access_end < $now) {
                   5066:                             if ($access_end - $end < 86400) {
                   5067:                                 push(@usersgroups,$group);
1.733     raeburn  5068:                             }
                   5069:                         }
1.817     raeburn  5070:                         next;
1.733     raeburn  5071:                     }
1.817     raeburn  5072:                     push(@usersgroups,$group);
1.683     raeburn  5073:                 }
                   5074:             }
                   5075:         }
1.817     raeburn  5076:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5077:         $grouplist = join(':',@usersgroups);
                   5078:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5079:     }
1.733     raeburn  5080:     return @usersgroups;
1.683     raeburn  5081: }
                   5082: 
                   5083: sub devalidate_getgroups_cache {
                   5084:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5085:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5086: 
1.683     raeburn  5087:     my $hashid="$udom:$uname:$courseid";
                   5088:     &devalidate_cache_new('getgroups',$hashid);
                   5089: }
                   5090: 
1.12      www      5091: # ------------------------------------------------------------------ Plain Text
                   5092: 
                   5093: sub plaintext {
1.742     raeburn  5094:     my ($short,$type,$cid) = @_;
1.758     albertel 5095:     if ($short =~ /^cr/) {
                   5096: 	return (split('/',$short))[-1];
                   5097:     }
1.742     raeburn  5098:     if (!defined($cid)) {
                   5099:         $cid = $env{'request.course.id'};
                   5100:     }
                   5101:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5102:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5103:                                           '.plaintext'});
                   5104:     }
                   5105:     my %rolenames = (
                   5106:                       Course => 'std',
                   5107:                       Group => 'alt1',
                   5108:                     );
                   5109:     if (defined($type) && 
                   5110:          defined($rolenames{$type}) && 
                   5111:          defined($prp{$short}{$rolenames{$type}})) {
                   5112:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5113:     } else {
                   5114:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5115:     }
1.12      www      5116: }
                   5117: 
                   5118: # ----------------------------------------------------------------- Assign Role
                   5119: 
                   5120: sub assignrole {
1.357     www      5121:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5122:     my $mrole;
                   5123:     if ($role =~ /^cr\//) {
1.393     www      5124:         my $cwosec=$url;
1.811     albertel 5125:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5126: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5127:            &logthis('Refused custom assignrole: '.
                   5128:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5129: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5130:            return 'refused'; 
                   5131:         }
1.21      www      5132:         $mrole='cr';
1.678     raeburn  5133:     } elsif ($role =~ /^gr\//) {
                   5134:         my $cwogrp=$url;
1.811     albertel 5135:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5136:         unless (&allowed('mdg',$cwogrp)) {
                   5137:             &logthis('Refused group assignrole: '.
                   5138:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5139:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5140:             return 'refused';
                   5141:         }
                   5142:         $mrole='gr';
1.21      www      5143:     } else {
1.82      www      5144:         my $cwosec=$url;
1.811     albertel 5145:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5146:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5147:            &logthis('Refused assignrole: '.
                   5148:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5149: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5150:            return 'refused'; 
                   5151:         }
1.21      www      5152:         $mrole=$role;
                   5153:     }
1.620     albertel 5154:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5155:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5156:     if ($end) { $command.='_'.$end; }
1.21      www      5157:     if ($start) {
                   5158: 	if ($end) { 
1.81      www      5159:            $command.='_'.$start; 
1.21      www      5160:         } else {
1.81      www      5161:            $command.='_0_'.$start;
1.21      www      5162:         }
                   5163:     }
1.739     raeburn  5164:     my $origstart = $start;
                   5165:     my $origend = $end;
1.357     www      5166: # actually delete
                   5167:     if ($deleteflag) {
1.373     www      5168: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5169: # modify command to delete the role
1.620     albertel 5170:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5171:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5172: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5173: # set start and finish to negative values for userrolelog
                   5174:            $start=-1;
                   5175:            $end=-1;
                   5176:         }
                   5177:     }
                   5178: # send command
1.349     www      5179:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5180: # log new user role if status is ok
1.349     www      5181:     if ($answer eq 'ok') {
1.663     raeburn  5182: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5183: # for course roles, perform group memberships changes triggered by role change.
                   5184:         unless ($role =~ /^gr/) {
                   5185:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5186:                                              $origstart);
                   5187:         }
1.349     www      5188:     }
                   5189:     return $answer;
1.169     harris41 5190: }
                   5191: 
                   5192: # -------------------------------------------------- Modify user authentication
1.197     www      5193: # Overrides without validation
                   5194: 
1.169     harris41 5195: sub modifyuserauth {
                   5196:     my ($udom,$uname,$umode,$upass)=@_;
                   5197:     my $uhome=&homeserver($uname,$udom);
1.197     www      5198:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5199:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5200:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5201:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5202:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5203: 		     &escape($upass),$uhome);
1.620     albertel 5204:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5205:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5206:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5207:     &log($udom,,$uname,$uhome,
1.620     albertel 5208:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5209:                                      $env{'user.name'}.', '.$umode.
1.197     www      5210:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5211:     unless ($reply eq 'ok') {
1.197     www      5212:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5213: 	return 'error: '.$reply;
                   5214:     }   
1.170     harris41 5215:     return 'ok';
1.80      www      5216: }
                   5217: 
1.81      www      5218: # --------------------------------------------------------------- Modify a user
1.80      www      5219: 
1.81      www      5220: sub modifyuser {
1.206     matthew  5221:     my ($udom,    $uname, $uid,
                   5222:         $umode,   $upass, $first,
                   5223:         $middle,  $last,  $gene,
1.387     www      5224:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5225:     $udom= &LONCAPA::clean_domain($udom);
                   5226:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5227:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5228:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5229: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5230:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5231:                                      ' desiredhome not specified'). 
1.620     albertel 5232:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5233:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5234:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5235: # ----------------------------------------------------------------- Create User
1.406     albertel 5236:     if (($uhome eq 'no_host') && 
                   5237: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5238:         my $unhome='';
1.844     albertel 5239:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5240:             $unhome = $desiredhome;
1.620     albertel 5241: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5242: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5243:         } else { # load balancing routine for determining $unhome
1.81      www      5244:             my $loadm=10000000;
1.841     albertel 5245: 	    my %servers = &get_servers($udom,'library');
                   5246: 	    foreach my $tryserver (keys(%servers)) {
                   5247: 		my $answer=reply('load',$tryserver);
                   5248: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5249: 		    $loadm=$answer;
                   5250: 		    $unhome=$tryserver;
                   5251: 		}
1.80      www      5252: 	    }
                   5253:         }
                   5254:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5255: 	    return 'error: unable to find a home server for '.$uname.
                   5256:                    ' in domain '.$udom;
1.80      www      5257:         }
                   5258:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5259:                          &escape($upass),$unhome);
                   5260: 	unless ($reply eq 'ok') {
                   5261:             return 'error: '.$reply;
                   5262:         }   
1.230     stredwic 5263:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5264:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5265: 	    return 'error: unable verify users home machine.';
1.80      www      5266:         }
1.209     matthew  5267:     }   # End of creation of new user
1.80      www      5268: # ---------------------------------------------------------------------- Add ID
                   5269:     if ($uid) {
                   5270:        $uid=~tr/A-Z/a-z/;
                   5271:        my %uidhash=&idrget($udom,$uname);
1.196     www      5272:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5273:          && (!$forceid)) {
1.80      www      5274: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5275: 	      return 'error: user id "'.$uid.'" does not match '.
                   5276:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5277:           }
                   5278:        } else {
                   5279: 	  &idput($udom,($uname => $uid));
                   5280:        }
                   5281:     }
                   5282: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5283:     my @tmp=&get('environment',
1.899     raeburn  5284: 		   ['firstname','middlename','lastname','generation','id',
                   5285:                     'permanentemail'],
1.134     albertel 5286: 		   $udom,$uname);
1.313     matthew  5287:     my %names;
                   5288:     if ($tmp[0] =~ m/^error:.*/) { 
                   5289:         %names=(); 
                   5290:     } else {
                   5291:         %names = @tmp;
                   5292:     }
1.388     www      5293: #
                   5294: # Make sure to not trash student environment if instructor does not bother
                   5295: # to supply name and email information
                   5296: #
                   5297:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5298:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5299:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5300:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5301:     if ($email) {
                   5302:        $email=~s/[^\w\@\.\-\,]//gs;
                   5303:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5304: 			   $names{'critnotification'} = $email;
                   5305: 			   $names{'permanentemail'} = $email; }
                   5306:     }
1.899     raeburn  5307:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5308:     my $reply = &put('environment', \%names, $udom,$uname);
                   5309:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5310:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5311:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5312:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5313:              $umode.', '.$first.', '.$middle.', '.
                   5314: 	     $last.', '.$gene.' by '.
1.620     albertel 5315:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5316:     return 'ok';
1.80      www      5317: }
                   5318: 
1.81      www      5319: # -------------------------------------------------------------- Modify student
1.80      www      5320: 
1.81      www      5321: sub modifystudent {
                   5322:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5323:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5324:     if (!$cid) {
1.620     albertel 5325: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5326: 	    return 'not_in_class';
                   5327: 	}
1.80      www      5328:     }
                   5329: # --------------------------------------------------------------- Make the user
1.81      www      5330:     my $reply=&modifyuser
1.209     matthew  5331: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5332:          $desiredhome,$email);
1.80      www      5333:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5334:     # This will cause &modify_student_enrollment to get the uid from the
                   5335:     # students environment
                   5336:     $uid = undef if (!$forceid);
1.455     albertel 5337:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5338: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5339:     return $reply;
                   5340: }
                   5341: 
                   5342: sub modify_student_enrollment {
1.515     raeburn  5343:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5344:     my ($cdom,$cnum,$chome);
                   5345:     if (!$cid) {
1.620     albertel 5346: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5347: 	    return 'not_in_class';
                   5348: 	}
1.620     albertel 5349: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5350: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5351:     } else {
                   5352: 	($cdom,$cnum)=split(/_/,$cid);
                   5353:     }
1.620     albertel 5354:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5355:     if (!$chome) {
1.457     raeburn  5356: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5357:     }
1.455     albertel 5358:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5359:     # Make sure the user exists
1.81      www      5360:     my $uhome=&homeserver($uname,$udom);
                   5361:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5362: 	return 'error: no such user';
                   5363:     }
1.297     matthew  5364:     # Get student data if we were not given enough information
                   5365:     if (!defined($first)  || $first  eq '' || 
                   5366:         !defined($last)   || $last   eq '' || 
                   5367:         !defined($uid)    || $uid    eq '' || 
                   5368:         !defined($middle) || $middle eq '' || 
                   5369:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5370:         # They did not supply us with enough data to enroll the student, so
                   5371:         # we need to pick up more information.
1.297     matthew  5372:         my %tmp = &get('environment',
1.294     matthew  5373:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5374:                        ,$udom,$uname);
                   5375: 
1.800     albertel 5376:         #foreach my $key (keys(%tmp)) {
                   5377:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5378:         #}
1.294     matthew  5379:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5380:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5381:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5382:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5383:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5384:     }
1.556     albertel 5385:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5386:     my $reply=cput('classlist',
                   5387: 		   {"$uname:$udom" => 
1.515     raeburn  5388: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5389: 		   $cdom,$cnum);
1.81      www      5390:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5391: 	return 'error: '.$reply;
1.652     albertel 5392:     } else {
                   5393: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5394:     }
1.297     matthew  5395:     # Add student role to user
1.83      www      5396:     my $uurl='/'.$cid;
1.81      www      5397:     $uurl=~s/\_/\//g;
                   5398:     if ($usec) {
                   5399: 	$uurl.='/'.$usec;
                   5400:     }
                   5401:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5402: }
                   5403: 
1.556     albertel 5404: sub format_name {
                   5405:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5406:     my $name;
                   5407:     if ($first ne 'lastname') {
                   5408: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5409:     } else {
                   5410: 	if ($lastname=~/\S/) {
                   5411: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5412: 	    $name=~s/\s+,/,/;
                   5413: 	} else {
                   5414: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5415: 	}
                   5416:     }
                   5417:     $name=~s/^\s+//;
                   5418:     $name=~s/\s+$//;
                   5419:     $name=~s/\s+/ /g;
                   5420:     return $name;
                   5421: }
                   5422: 
1.84      www      5423: # ------------------------------------------------- Write to course preferences
                   5424: 
                   5425: sub writecoursepref {
                   5426:     my ($courseid,%prefs)=@_;
                   5427:     $courseid=~s/^\///;
                   5428:     $courseid=~s/\_/\//g;
                   5429:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5430:     my $chome=homeserver($cnum,$cdomain);
                   5431:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5432: 	return 'error: no such course';
                   5433:     }
                   5434:     my $cstring='';
1.800     albertel 5435:     foreach my $pref (keys(%prefs)) {
                   5436: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5437:     }
1.84      www      5438:     $cstring=~s/\&$//;
                   5439:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5440: }
                   5441: 
                   5442: # ---------------------------------------------------------- Make/modify course
                   5443: 
                   5444: sub createcourse {
1.741     raeburn  5445:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5446:         $course_owner,$crstype)=@_;
1.84      www      5447:     $url=&declutter($url);
                   5448:     my $cid='';
1.264     matthew  5449:     unless (&allowed('ccc',$udom)) {
1.84      www      5450:         return 'refused';
                   5451:     }
                   5452: # ------------------------------------------------------------------- Create ID
1.674     www      5453:    my $uname=int(1+rand(9)).
                   5454:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5455:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5456:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5457: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5458:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5459:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5460:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5461:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5462:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5463:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5464:            return 'error: unable to generate unique course-ID';
                   5465:        } 
                   5466:    }
1.264     matthew  5467: # ------------------------------------------------ Check supplied server name
1.620     albertel 5468:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5469:     if (! &is_library($course_server)) {
1.264     matthew  5470:         return 'error:bad server name '.$course_server;
                   5471:     }
1.84      www      5472: # ------------------------------------------------------------- Make the course
                   5473:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5474:                       $course_server);
1.84      www      5475:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5476:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5477:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5478: 	return 'error: no such course';
                   5479:     }
1.271     www      5480: # ----------------------------------------------------------------- Course made
1.516     raeburn  5481: # log existence
                   5482:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5483:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5484:                   &escape($crstype),$uhome);
1.358     www      5485:     &flushcourselogs();
                   5486: # set toplevel url
1.271     www      5487:     my $topurl=$url;
                   5488:     unless ($nonstandard) {
                   5489: # ------------------------------------------ For standard courses, make top url
                   5490:         my $mapurl=&clutter($url);
1.278     www      5491:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5492:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5493: <map>
                   5494: <resource id="1" type="start"></resource>
                   5495: <resource id="2" src="$mapurl"></resource>
                   5496: <resource id="3" type="finish"></resource>
                   5497: <link index="1" from="1" to="2"></link>
                   5498: <link index="2" from="2" to="3"></link>
                   5499: </map>
                   5500: ENDINITMAP
                   5501:         $topurl=&declutter(
1.638     albertel 5502:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5503:                           );
                   5504:     }
                   5505: # ----------------------------------------------------------- Write preferences
1.84      www      5506:     &writecoursepref($udom.'_'.$uname,
                   5507:                      ('description' => $description,
1.271     www      5508:                       'url'         => $topurl));
1.84      www      5509:     return '/'.$udom.'/'.$uname;
                   5510: }
                   5511: 
1.813     albertel 5512: sub is_course {
                   5513:     my ($cdom,$cnum) = @_;
                   5514:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5515: 				undef,'.');
                   5516:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5517:         return 1;
                   5518:     }
                   5519:     return 0;
                   5520: }
                   5521: 
1.21      www      5522: # ---------------------------------------------------------- Assign Custom Role
                   5523: 
                   5524: sub assigncustomrole {
1.357     www      5525:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5526:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5527:                        $end,$start,$deleteflag);
1.21      www      5528: }
                   5529: 
                   5530: # ----------------------------------------------------------------- Revoke Role
                   5531: 
                   5532: sub revokerole {
1.357     www      5533:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5534:     my $now=time;
1.357     www      5535:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5536: }
                   5537: 
                   5538: # ---------------------------------------------------------- Revoke Custom Role
                   5539: 
                   5540: sub revokecustomrole {
1.357     www      5541:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5542:     my $now=time;
1.357     www      5543:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5544:            $deleteflag);
1.17      www      5545: }
                   5546: 
1.533     banghart 5547: # ------------------------------------------------------------ Disk usage
1.535     albertel 5548: sub diskusage {
1.533     banghart 5549:     my ($udom,$uname,$directoryRoot)=@_;
                   5550:     $directoryRoot =~ s/\/$//;
1.535     albertel 5551:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5552:     return $listing;
1.512     banghart 5553: }
                   5554: 
1.566     banghart 5555: sub is_locked {
                   5556:     my ($file_name, $domain, $user) = @_;
                   5557:     my @check;
                   5558:     my $is_locked;
                   5559:     push @check, $file_name;
1.613     albertel 5560:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5561: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5562:     my ($tmp)=keys(%locked);
                   5563:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5564:     
1.566     banghart 5565:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5566:         $is_locked = 'false';
                   5567:         foreach my $entry (@{$locked{$file_name}}) {
                   5568:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5569:                $is_locked = 'true';
                   5570:                last;
1.745     raeburn  5571:            }
                   5572:        }
1.566     banghart 5573:     } else {
                   5574:         $is_locked = 'false';
                   5575:     }
                   5576: }
                   5577: 
1.759     albertel 5578: sub declutter_portfile {
                   5579:     my ($file) = @_;
1.833     albertel 5580:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5581:     return $file;
                   5582: }
                   5583: 
1.559     banghart 5584: # ------------------------------------------------------------- Mark as Read Only
                   5585: 
                   5586: sub mark_as_readonly {
                   5587:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5588:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5589:     my ($tmp)=keys(%current_permissions);
                   5590:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5591:     foreach my $file (@{$files}) {
1.759     albertel 5592: 	$file = &declutter_portfile($file);
1.561     banghart 5593:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5594:     }
1.613     albertel 5595:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5596:     return;
                   5597: }
                   5598: 
1.572     banghart 5599: # ------------------------------------------------------------Save Selected Files
                   5600: 
                   5601: sub save_selected_files {
                   5602:     my ($user, $path, @files) = @_;
                   5603:     my $filename = $user."savedfiles";
1.573     banghart 5604:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5605:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5606:     foreach my $file (@files) {
1.620     albertel 5607:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5608:     }
                   5609:     foreach my $file (@other_files) {
1.574     banghart 5610:         print (OUT $file."\n");
1.572     banghart 5611:     }
1.574     banghart 5612:     close (OUT);
1.572     banghart 5613:     return 'ok';
                   5614: }
                   5615: 
1.574     banghart 5616: sub clear_selected_files {
                   5617:     my ($user) = @_;
                   5618:     my $filename = $user."savedfiles";
                   5619:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5620:     print (OUT undef);
                   5621:     close (OUT);
                   5622:     return ("ok");    
                   5623: }
                   5624: 
1.572     banghart 5625: sub files_in_path {
                   5626:     my ($user, $path) = @_;
                   5627:     my $filename = $user."savedfiles";
                   5628:     my %return_files;
1.574     banghart 5629:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5630:     while (my $line_in = <IN>) {
1.574     banghart 5631:         chomp ($line_in);
                   5632:         my @paths_and_file = split (m!/!, $line_in);
                   5633:         my $file_part = pop (@paths_and_file);
                   5634:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5635:         $path_part.='/';
                   5636:         my $path_and_file = $path_part.$file_part;
                   5637:         if ($path_part eq $path) {
                   5638:             $return_files{$file_part}= 'selected';
                   5639:         }
                   5640:     }
1.574     banghart 5641:     close (IN);
                   5642:     return (\%return_files);
1.572     banghart 5643: }
                   5644: 
                   5645: # called in portfolio select mode, to show files selected NOT in current directory
                   5646: sub files_not_in_path {
                   5647:     my ($user, $path) = @_;
                   5648:     my $filename = $user."savedfiles";
                   5649:     my @return_files;
                   5650:     my $path_part;
1.800     albertel 5651:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5652:     while (my $line = <IN>) {
1.572     banghart 5653:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5654:         my @paths_and_file = split(m|/|, $line);
                   5655:         my $file_part = pop(@paths_and_file);
                   5656:         chomp($file_part);
                   5657:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5658:         $path_part .= '/';
                   5659:         my $path_and_file = $path_part.$file_part;
                   5660:         if ($path_part ne $path) {
1.800     albertel 5661:             push(@return_files, ($path_and_file));
1.572     banghart 5662:         }
                   5663:     }
1.800     albertel 5664:     close(OUT);
1.574     banghart 5665:     return (@return_files);
1.572     banghart 5666: }
                   5667: 
1.745     raeburn  5668: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5669: 
1.745     raeburn  5670: sub get_portfile_permissions {
                   5671:     my ($domain,$user) = @_;
1.613     albertel 5672:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5673:     my ($tmp)=keys(%current_permissions);
                   5674:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5675:     return \%current_permissions;
                   5676: }
                   5677: 
                   5678: #---------------------------------------------Get portfolio file access controls
                   5679: 
1.749     raeburn  5680: sub get_access_controls {
1.745     raeburn  5681:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5682:     my %access;
                   5683:     my $real_file = $file;
                   5684:     $file =~ s/\.meta$//;
1.745     raeburn  5685:     if (defined($file)) {
1.749     raeburn  5686:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5687:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5688:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5689:             }
                   5690:         }
1.745     raeburn  5691:     } else {
1.749     raeburn  5692:         foreach my $key (keys(%{$current_permissions})) {
                   5693:             if ($key =~ /\0accesscontrol$/) {
                   5694:                 if (defined($group)) {
                   5695:                     if ($key !~ m-^\Q$group\E/-) {
                   5696:                         next;
                   5697:                     }
                   5698:                 }
                   5699:                 my ($fullpath) = split(/\0/,$key);
                   5700:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5701:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5702:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5703:                     }
                   5704:                 }
                   5705:             }
                   5706:         }
                   5707:     }
                   5708:     return %access;
                   5709: }
                   5710: 
                   5711: sub modify_access_controls {
                   5712:     my ($file_name,$changes,$domain,$user)=@_;
                   5713:     my ($outcome,$deloutcome);
                   5714:     my %store_permissions;
                   5715:     my %new_values;
                   5716:     my %new_control;
                   5717:     my %translation;
                   5718:     my @deletions = ();
                   5719:     my $now = time;
                   5720:     if (exists($$changes{'activate'})) {
                   5721:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5722:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5723:             my $numnew = scalar(@newitems);
                   5724:             for (my $i=0; $i<$numnew; $i++) {
                   5725:                 my $newkey = $newitems[$i];
                   5726:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5727:                 if ($newkey =~ /^\d+:/) { 
                   5728:                     $newkey =~ s/^(\d+)/$newid/;
                   5729:                     $translation{$1} = $newid;
                   5730:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5731:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5732:                     $translation{$1} = $newid;
                   5733:                 }
1.749     raeburn  5734:                 $new_values{$file_name."\0".$newkey} = 
                   5735:                                           $$changes{'activate'}{$newitems[$i]};
                   5736:                 $new_control{$newkey} = $now;
                   5737:             }
                   5738:         }
                   5739:     }
                   5740:     my %todelete;
                   5741:     my %changed_items;
                   5742:     foreach my $action ('delete','update') {
                   5743:         if (exists($$changes{$action})) {
                   5744:             if (ref($$changes{$action}) eq 'HASH') {
                   5745:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5746:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5747:                     if ($action eq 'delete') { 
                   5748:                         $todelete{$itemnum} = 1;
                   5749:                     } else {
                   5750:                         $changed_items{$itemnum} = $key;
                   5751:                     }
                   5752:                 }
1.745     raeburn  5753:             }
                   5754:         }
1.749     raeburn  5755:     }
                   5756:     # get lock on access controls for file.
                   5757:     my $lockhash = {
                   5758:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5759:                                                        ':'.$env{'user.domain'},
                   5760:                    }; 
                   5761:     my $tries = 0;
                   5762:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5763:    
                   5764:     while (($gotlock ne 'ok') && $tries <3) {
                   5765:         $tries ++;
                   5766:         sleep 1;
                   5767:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5768:     }
                   5769:     if ($gotlock eq 'ok') {
                   5770:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5771:         my ($tmp)=keys(%curr_permissions);
                   5772:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5773:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5774:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5775:             if (ref($curr_controls) eq 'HASH') {
                   5776:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5777:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5778:                     if (defined($todelete{$itemnum})) {
                   5779:                         push(@deletions,$file_name."\0".$control_item);
                   5780:                     } else {
                   5781:                         if (defined($changed_items{$itemnum})) {
                   5782:                             $new_control{$changed_items{$itemnum}} = $now;
                   5783:                             push(@deletions,$file_name."\0".$control_item);
                   5784:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5785:                         } else {
                   5786:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5787:                         }
                   5788:                     }
1.745     raeburn  5789:                 }
                   5790:             }
                   5791:         }
1.749     raeburn  5792:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5793:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5794:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5795:         #  remove lock
                   5796:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5797:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5798:         my ($file,$group);
                   5799:         if (&is_course($domain,$user)) {
                   5800:             ($group,$file) = split(/\//,$file_name,2);
                   5801:         } else {
                   5802:             $file = $file_name;
                   5803:         }
                   5804:         my $sqlresult =
                   5805:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5806:                                     $group);
1.749     raeburn  5807:     } else {
                   5808:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5809:     }
1.749     raeburn  5810:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5811: }
                   5812: 
1.827     raeburn  5813: sub make_public_indefinitely {
                   5814:     my ($requrl) = @_;
                   5815:     my $now = time;
                   5816:     my $action = 'activate';
                   5817:     my $aclnum = 0;
                   5818:     if (&is_portfolio_url($requrl)) {
                   5819:         my (undef,$udom,$unum,$file_name,$group) =
                   5820:             &parse_portfolio_url($requrl);
                   5821:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5822:         my %access_controls = &get_access_controls($current_perms,
                   5823:                                                    $group,$file_name);
                   5824:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5825:             my ($num,$scope,$end,$start) = 
                   5826:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5827:             if ($scope eq 'public') {
                   5828:                 if ($start <= $now && $end == 0) {
                   5829:                     $action = 'none';
                   5830:                 } else {
                   5831:                     $action = 'update';
                   5832:                     $aclnum = $num;
                   5833:                 }
                   5834:                 last;
                   5835:             }
                   5836:         }
                   5837:         if ($action eq 'none') {
                   5838:              return 'ok';
                   5839:         } else {
                   5840:             my %changes;
                   5841:             my $newend = 0;
                   5842:             my $newstart = $now;
                   5843:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5844:             $changes{$action}{$newkey} = {
                   5845:                 type => 'public',
                   5846:                 time => {
                   5847:                     start => $newstart,
                   5848:                     end   => $newend,
                   5849:                 },
                   5850:             };
                   5851:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5852:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5853:             return $outcome;
                   5854:         }
                   5855:     } else {
                   5856:         return 'invalid';
                   5857:     }
                   5858: }
                   5859: 
1.745     raeburn  5860: #------------------------------------------------------Get Marked as Read Only
                   5861: 
                   5862: sub get_marked_as_readonly {
                   5863:     my ($domain,$user,$what,$group) = @_;
                   5864:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5865:     my @readonly_files;
1.629     banghart 5866:     my $cmp1=$what;
                   5867:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5868:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5869:         if (defined($group)) {
                   5870:             if ($file_name !~ m-^\Q$group\E/-) {
                   5871:                 next;
                   5872:             }
                   5873:         }
1.561     banghart 5874:         if (ref($value) eq "ARRAY"){
                   5875:             foreach my $stored_what (@{$value}) {
1.629     banghart 5876:                 my $cmp2=$stored_what;
1.759     albertel 5877:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5878:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5879:                 }
1.629     banghart 5880:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5881:                     push(@readonly_files, $file_name);
1.745     raeburn  5882:                     last;
1.563     banghart 5883:                 } elsif (!defined($what)) {
                   5884:                     push(@readonly_files, $file_name);
1.745     raeburn  5885:                     last;
1.561     banghart 5886:                 }
                   5887:             }
1.745     raeburn  5888:         }
1.561     banghart 5889:     }
                   5890:     return @readonly_files;
                   5891: }
1.577     banghart 5892: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5893: 
1.577     banghart 5894: sub get_marked_as_readonly_hash {
1.745     raeburn  5895:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5896:     my %readonly_files;
1.745     raeburn  5897:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5898:         if (defined($group)) {
                   5899:             if ($file_name !~ m-^\Q$group\E/-) {
                   5900:                 next;
                   5901:             }
                   5902:         }
1.577     banghart 5903:         if (ref($value) eq "ARRAY"){
                   5904:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5905:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5906:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5907:                         if ($lock_descriptor eq 'graded') {
                   5908:                             $readonly_files{$file_name} = 'graded';
                   5909:                         } elsif ($lock_descriptor eq 'handback') {
                   5910:                             $readonly_files{$file_name} = 'handback';
                   5911:                         } else {
                   5912:                             if (!exists($readonly_files{$file_name})) {
                   5913:                                 $readonly_files{$file_name} = 'locked';
                   5914:                             }
                   5915:                         }
1.745     raeburn  5916:                     }
1.750     banghart 5917:                 } 
1.577     banghart 5918:             }
                   5919:         } 
                   5920:     }
                   5921:     return %readonly_files;
                   5922: }
1.559     banghart 5923: # ------------------------------------------------------------ Unmark as Read Only
                   5924: 
                   5925: sub unmark_as_readonly {
1.629     banghart 5926:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5927:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5928:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5929:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5930:     my $symb_crs = $what;
                   5931:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5932:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5933:     my ($tmp)=keys(%current_permissions);
                   5934:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5935:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5936:     foreach my $file (@readonly_files) {
1.759     albertel 5937: 	my $clean_file = &declutter_portfile($file);
                   5938: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5939: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5940:         my @new_locks;
                   5941:         my @del_keys;
                   5942:         if (ref($current_locks) eq "ARRAY"){
                   5943:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5944:                 my $compare=$locker;
1.749     raeburn  5945:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5946:                     $compare=join('',@{$locker});
1.746     raeburn  5947:                     if ($compare ne $symb_crs) {
                   5948:                         push(@new_locks, $locker);
                   5949:                     }
1.563     banghart 5950:                 }
                   5951:             }
1.650     albertel 5952:             if (scalar(@new_locks) > 0) {
1.563     banghart 5953:                 $current_permissions{$file} = \@new_locks;
                   5954:             } else {
                   5955:                 push(@del_keys, $file);
1.613     albertel 5956:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5957:                 delete($current_permissions{$file});
1.563     banghart 5958:             }
                   5959:         }
1.561     banghart 5960:     }
1.613     albertel 5961:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5962:     return;
                   5963: }
1.512     banghart 5964: 
1.17      www      5965: # ------------------------------------------------------------ Directory lister
                   5966: 
                   5967: sub dirlist {
1.253     stredwic 5968:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5969: 
1.18      www      5970:     $uri=~s/^\///;
                   5971:     $uri=~s/\/$//;
1.253     stredwic 5972:     my ($udom, $uname);
                   5973:     (undef,$udom,$uname)=split(/\//,$uri);
                   5974:     if(defined($userdomain)) {
                   5975:         $udom = $userdomain;
                   5976:     }
                   5977:     if(defined($username)) {
                   5978:         $uname = $username;
                   5979:     }
                   5980: 
                   5981:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5982:     if(defined($alternateDirectoryRoot)) {
                   5983:         $dirRoot = $alternateDirectoryRoot;
                   5984:         $dirRoot =~ s/\/$//;
1.751     banghart 5985:     }
1.253     stredwic 5986: 
                   5987:     if($udom) {
                   5988:         if($uname) {
1.800     albertel 5989:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5990: 				 &homeserver($uname,$udom));
1.605     matthew  5991:             my @listing_results;
                   5992:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5993:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5994: 				  &homeserver($uname,$udom));
1.605     matthew  5995:                 @listing_results = split(/:/,$listing);
                   5996:             } else {
                   5997:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5998:             }
                   5999:             return @listing_results;
1.253     stredwic 6000:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6001:             my %allusers;
1.841     albertel 6002: 	    my %servers = &get_servers($udom,'library');
                   6003: 	    foreach my $tryserver (keys(%servers)) {
                   6004: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6005: 				     $udom, $tryserver);
                   6006: 		my @listing_results;
                   6007: 		if ($listing eq 'unknown_cmd') {
                   6008: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6009: 				      $udom, $tryserver);
                   6010: 		    @listing_results = split(/:/,$listing);
                   6011: 		} else {
                   6012: 		    @listing_results =
                   6013: 			map { &unescape($_); } split(/:/,$listing);
                   6014: 		}
                   6015: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6016: 		    $listing_results[0] ne 'empty'       &&
                   6017: 		    $listing_results[0] ne 'con_lost') {
                   6018: 		    foreach my $line (@listing_results) {
                   6019: 			my ($entry) = split(/&/,$line,2);
                   6020: 			$allusers{$entry} = 1;
                   6021: 		    }
                   6022: 		}
1.253     stredwic 6023:             }
                   6024:             my $alluserstr='';
1.800     albertel 6025:             foreach my $user (sort(keys(%allusers))) {
                   6026:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6027:             }
                   6028:             $alluserstr=~s/:$//;
                   6029:             return split(/:/,$alluserstr);
                   6030:         } else {
1.800     albertel 6031:             return ('missing user name');
1.253     stredwic 6032:         }
                   6033:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6034:         my @all_domains = sort(&all_domains());
                   6035:          foreach my $domain (@all_domains) {
                   6036:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6037:          }
                   6038:          return @all_domains;
                   6039:      } else {
1.800     albertel 6040:         return ('missing domain');
1.275     stredwic 6041:     }
                   6042: }
                   6043: 
                   6044: # --------------------------------------------- GetFileTimestamp
                   6045: # This function utilizes dirlist and returns the date stamp for
                   6046: # when it was last modified.  It will also return an error of -1
                   6047: # if an error occurs
                   6048: 
1.410     matthew  6049: ##
                   6050: ## FIXME: This subroutine assumes its caller knows something about the
                   6051: ## directory structure of the home server for the student ($root).
                   6052: ## Not a good assumption to make.  Since this is for looking up files
                   6053: ## in user directories, the full path should be constructed by lond, not
                   6054: ## whatever machine we request data from.
                   6055: ##
1.275     stredwic 6056: sub GetFileTimestamp {
                   6057:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6058:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6059:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6060:     my $subdir=$studentName.'__';
                   6061:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6062:     my $proname="$studentDomain/$subdir/$studentName";
                   6063:     $proname .= '/'.$filename;
1.375     matthew  6064:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6065:                                               $studentName, $root);
1.275     stredwic 6066:     my @stats = split('&', $fileStat);
                   6067:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6068:         # @stats contains first the filename, then the stat output
                   6069:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6070:     } else {
                   6071:         return -1;
1.253     stredwic 6072:     }
1.26      www      6073: }
                   6074: 
1.712     albertel 6075: sub stat_file {
                   6076:     my ($uri) = @_;
1.787     albertel 6077:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6078: 
1.712     albertel 6079:     my ($udom,$uname,$file,$dir);
                   6080:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6081: 	($udom,$uname,$file) =
1.811     albertel 6082: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6083: 	$file = 'userfiles/'.$file;
1.740     www      6084: 	$dir = &propath($udom,$uname);
1.712     albertel 6085:     }
                   6086:     if ($uri =~ m-^/res/-) {
                   6087: 	($udom,$uname) = 
1.807     albertel 6088: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6089: 	$file = $uri;
                   6090:     }
                   6091: 
                   6092:     if (!$udom || !$uname || !$file) {
                   6093: 	# unable to handle the uri
                   6094: 	return ();
                   6095:     }
                   6096: 
                   6097:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6098:     my @stats = split('&', $result);
1.721     banghart 6099:     
1.712     albertel 6100:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6101: 	shift(@stats); #filename is first
                   6102: 	return @stats;
                   6103:     }
                   6104:     return ();
                   6105: }
                   6106: 
1.26      www      6107: # -------------------------------------------------------- Value of a Condition
                   6108: 
1.713     albertel 6109: # gets the value of a specific preevaluated condition
                   6110: #    stored in the string  $env{user.state.<cid>}
                   6111: # or looks up a condition reference in the bighash and if if hasn't
                   6112: # already been evaluated recurses into docondval to get the value of
                   6113: # the condition, then memoizing it to 
                   6114: #   $env{user.state.<cid>.<condition>}
1.40      www      6115: sub directcondval {
                   6116:     my $number=shift;
1.620     albertel 6117:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6118: 	&Apache::lonuserstate::evalstate();
                   6119:     }
1.713     albertel 6120:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6121: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6122:     } elsif ($number =~ /^_/) {
                   6123: 	my $sub_condition;
                   6124: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6125: 		&GDBM_READER(),0640)) {
                   6126: 	    $sub_condition=$bighash{'conditions'.$number};
                   6127: 	    untie(%bighash);
                   6128: 	}
                   6129: 	my $value = &docondval($sub_condition);
                   6130: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6131: 	return $value;
                   6132:     }
1.620     albertel 6133:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6134:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6135:     } else {
                   6136:        return 2;
                   6137:     }
                   6138: }
                   6139: 
1.713     albertel 6140: # get the collection of conditions for this resource
1.26      www      6141: sub condval {
                   6142:     my $condidx=shift;
1.54      www      6143:     my $allpathcond='';
1.713     albertel 6144:     foreach my $cond (split(/\|/,$condidx)) {
                   6145: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6146: 	    $allpathcond.=
                   6147: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6148: 	}
1.191     harris41 6149:     }
1.54      www      6150:     $allpathcond=~s/\|$//;
1.713     albertel 6151:     return &docondval($allpathcond);
                   6152: }
                   6153: 
                   6154: #evaluates an expression of conditions
                   6155: sub docondval {
                   6156:     my ($allpathcond) = @_;
                   6157:     my $result=0;
                   6158:     if ($env{'request.course.id'}
                   6159: 	&& defined($allpathcond)) {
                   6160: 	my $operand='|';
                   6161: 	my @stack;
                   6162: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6163: 	    if ($chunk eq '(') {
                   6164: 		push @stack,($operand,$result);
                   6165: 	    } elsif ($chunk eq ')') {
                   6166: 		my $before=pop @stack;
                   6167: 		if (pop @stack eq '&') {
                   6168: 		    $result=$result>$before?$before:$result;
                   6169: 		} else {
                   6170: 		    $result=$result>$before?$result:$before;
                   6171: 		}
                   6172: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6173: 		$operand=$chunk;
                   6174: 	    } else {
                   6175: 		my $new=directcondval($chunk);
                   6176: 		if ($operand eq '&') {
                   6177: 		    $result=$result>$new?$new:$result;
                   6178: 		} else {
                   6179: 		    $result=$result>$new?$result:$new;
                   6180: 		}
                   6181: 	    }
                   6182: 	}
1.26      www      6183:     }
                   6184:     return $result;
1.421     albertel 6185: }
                   6186: 
                   6187: # ---------------------------------------------------- Devalidate courseresdata
                   6188: 
                   6189: sub devalidatecourseresdata {
                   6190:     my ($coursenum,$coursedomain)=@_;
                   6191:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6192:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6193: }
                   6194: 
1.763     www      6195: 
1.200     www      6196: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6197: #
                   6198: #  Parameters:
                   6199: #      $coursenum    - Number of the course.
                   6200: #      $coursedomain - Domain at which the course was created.
                   6201: #  Returns:
                   6202: #     A hash of the course parameters along (I think) with timestamps
                   6203: #     and version info.
1.877     foxr     6204: 
1.624     albertel 6205: sub get_courseresdata {
                   6206:     my ($coursenum,$coursedomain)=@_;
1.200     www      6207:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6208:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6209:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6210:     my %dumpreply;
1.417     albertel 6211:     unless (defined($cached)) {
1.624     albertel 6212: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6213: 	$result=\%dumpreply;
1.251     albertel 6214: 	my ($tmp) = keys(%dumpreply);
                   6215: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6216: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6217: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6218: 	    return $tmp;
1.416     albertel 6219: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6220: 	    $result=undef;
1.599     albertel 6221: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6222: 	}
                   6223:     }
1.624     albertel 6224:     return $result;
                   6225: }
                   6226: 
1.633     albertel 6227: sub devalidateuserresdata {
                   6228:     my ($uname,$udom)=@_;
                   6229:     my $hashid="$udom:$uname";
                   6230:     &devalidate_cache_new('userres',$hashid);
                   6231: }
                   6232: 
1.624     albertel 6233: sub get_userresdata {
                   6234:     my ($uname,$udom)=@_;
                   6235:     #most student don\'t have any data set, check if there is some data
                   6236:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6237: 
                   6238:     my $hashid="$udom:$uname";
                   6239:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6240:     if (!defined($cached)) {
                   6241: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6242: 	$result=\%resourcedata;
                   6243: 	&do_cache_new('userres',$hashid,$result,600);
                   6244:     }
                   6245:     my ($tmp)=keys(%$result);
                   6246:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6247: 	return $result;
                   6248:     }
                   6249:     #error 2 occurs when the .db doesn't exist
                   6250:     if ($tmp!~/error: 2 /) {
1.672     albertel 6251: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6252: 		 " Trying to get resource data for ".
                   6253: 		 $uname." at ".$udom.": ".
                   6254: 		 $tmp."</font>");
                   6255:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6256: 	#&EXT_cache_set($udom,$uname);
                   6257: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6258: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6259:     }
                   6260:     return $tmp;
                   6261: }
1.879     foxr     6262: #----------------------------------------------- resdata - return resource data
                   6263: #  Purpose:
                   6264: #    Return resource data for either users or for a course.
                   6265: #  Parameters:
                   6266: #     $name      - Course/user name.
                   6267: #     $domain    - Name of the domain the user/course is registered on.
                   6268: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6269: #     @which     - Array of names of resources desired.
                   6270: #  Returns:
                   6271: #     The value of the first reasource in @which that is found in the
                   6272: #     resource hash.
                   6273: #  Exceptional Conditions:
                   6274: #     If the $type passed in is not valid (not the string 'course' or 
                   6275: #     'user', an undefined  reference is returned.
                   6276: #     If none of the resources are found, an undef is returned
1.624     albertel 6277: sub resdata {
                   6278:     my ($name,$domain,$type,@which)=@_;
                   6279:     my $result;
                   6280:     if ($type eq 'course') {
                   6281: 	$result=&get_courseresdata($name,$domain);
                   6282:     } elsif ($type eq 'user') {
                   6283: 	$result=&get_userresdata($name,$domain);
                   6284:     }
                   6285:     if (!ref($result)) { return $result; }    
1.251     albertel 6286:     foreach my $item (@which) {
1.417     albertel 6287: 	if (defined($result->{$item})) {
                   6288: 	    return $result->{$item};
1.251     albertel 6289: 	}
1.250     albertel 6290:     }
1.291     albertel 6291:     return undef;
1.200     www      6292: }
                   6293: 
1.379     matthew  6294: #
                   6295: # EXT resource caching routines
                   6296: #
                   6297: 
                   6298: sub clear_EXT_cache_status {
1.383     albertel 6299:     &delenv('cache.EXT.');
1.379     matthew  6300: }
                   6301: 
                   6302: sub EXT_cache_status {
                   6303:     my ($target_domain,$target_user) = @_;
1.383     albertel 6304:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6305:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6306:         # We know already the user has no data
                   6307:         return 1;
                   6308:     } else {
                   6309:         return 0;
                   6310:     }
                   6311: }
                   6312: 
                   6313: sub EXT_cache_set {
                   6314:     my ($target_domain,$target_user) = @_;
1.383     albertel 6315:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6316:     #&appenv($cachename => time);
1.379     matthew  6317: }
                   6318: 
1.28      www      6319: # --------------------------------------------------------- Value of a Variable
1.58      www      6320: sub EXT {
1.715     albertel 6321: 
1.395     albertel 6322:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6323:     unless ($varname) { return ''; }
1.218     albertel 6324:     #get real user name/domain, courseid and symb
                   6325:     my $courseid;
1.359     albertel 6326:     my $publicuser;
1.427     www      6327:     if ($symbparm) {
                   6328: 	$symbparm=&get_symb_from_alias($symbparm);
                   6329:     }
1.218     albertel 6330:     if (!($uname && $udom)) {
1.790     albertel 6331:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6332:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6333:     } else {
1.620     albertel 6334: 	$courseid=$env{'request.course.id'};
1.218     albertel 6335:     }
1.48      www      6336:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6337:     my $rest;
1.320     albertel 6338:     if (defined($therest[0])) {
1.48      www      6339:        $rest=join('.',@therest);
                   6340:     } else {
                   6341:        $rest='';
                   6342:     }
1.320     albertel 6343: 
1.57      www      6344:     my $qualifierrest=$qualifier;
                   6345:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6346:     my $spacequalifierrest=$space;
                   6347:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6348:     if ($realm eq 'user') {
1.48      www      6349: # --------------------------------------------------------------- user.resource
                   6350: 	if ($space eq 'resource') {
1.651     albertel 6351: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6352: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6353: 		 &&
1.744     albertel 6354: 		 ($symbparm eq &symbread()) ) {	
                   6355: 		# if we are in the middle of processing the resource the
                   6356: 		# get the value we are planning on committing
                   6357:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6358:                     return $Apache::lonhomework::results{$qualifierrest};
                   6359:                 } else {
                   6360:                     return $Apache::lonhomework::history{$qualifierrest};
                   6361:                 }
1.335     albertel 6362: 	    } else {
1.359     albertel 6363: 		my %restored;
1.620     albertel 6364: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6365: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6366: 		} else {
                   6367: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6368: 		}
1.335     albertel 6369: 		return $restored{$qualifierrest};
                   6370: 	    }
1.48      www      6371: # ----------------------------------------------------------------- user.access
                   6372:         } elsif ($space eq 'access') {
1.218     albertel 6373: 	    # FIXME - not supporting calls for a specific user
1.48      www      6374:             return &allowed($qualifier,$rest);
                   6375: # ------------------------------------------ user.preferences, user.environment
                   6376:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6377: 	    if (($uname eq $env{'user.name'}) &&
                   6378: 		($udom eq $env{'user.domain'})) {
                   6379: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6380: 	    } else {
1.359     albertel 6381: 		my %returnhash;
                   6382: 		if (!$publicuser) {
                   6383: 		    %returnhash=&userenvironment($udom,$uname,
                   6384: 						 $qualifierrest);
                   6385: 		}
1.218     albertel 6386: 		return $returnhash{$qualifierrest};
                   6387: 	    }
1.48      www      6388: # ----------------------------------------------------------------- user.course
                   6389:         } elsif ($space eq 'course') {
1.218     albertel 6390: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6391:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6392: # ------------------------------------------------------------------- user.role
                   6393:         } elsif ($space eq 'role') {
1.218     albertel 6394: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6395:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6396:             if ($qualifier eq 'value') {
                   6397: 		return $role;
                   6398:             } elsif ($qualifier eq 'extent') {
                   6399:                 return $where;
                   6400:             }
                   6401: # ----------------------------------------------------------------- user.domain
                   6402:         } elsif ($space eq 'domain') {
1.218     albertel 6403:             return $udom;
1.48      www      6404: # ------------------------------------------------------------------- user.name
                   6405:         } elsif ($space eq 'name') {
1.218     albertel 6406:             return $uname;
1.48      www      6407: # ---------------------------------------------------- Any other user namespace
1.29      www      6408:         } else {
1.359     albertel 6409: 	    my %reply;
                   6410: 	    if (!$publicuser) {
                   6411: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6412: 	    }
                   6413: 	    return $reply{$qualifierrest};
1.48      www      6414:         }
1.236     www      6415:     } elsif ($realm eq 'query') {
                   6416: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6417:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6418: 						[$spacequalifierrest]);
1.620     albertel 6419: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6420:    } elsif ($realm eq 'request') {
1.48      www      6421: # ------------------------------------------------------------- request.browser
                   6422:         if ($space eq 'browser') {
1.430     www      6423: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6424: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6425: 		    return 1;
                   6426: 		} else {
                   6427: 		    return 0;
                   6428: 		}
                   6429: 	    } else {
1.620     albertel 6430: 		return $env{'browser.'.$qualifier};
1.430     www      6431: 	    }
1.57      www      6432: # ------------------------------------------------------------ request.filename
                   6433:         } else {
1.620     albertel 6434:             return $env{'request.'.$spacequalifierrest};
1.29      www      6435:         }
1.28      www      6436:     } elsif ($realm eq 'course') {
1.48      www      6437: # ---------------------------------------------------------- course.description
1.620     albertel 6438:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6439:     } elsif ($realm eq 'resource') {
1.165     www      6440: 
1.620     albertel 6441: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6442: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6443: 	}
1.693     albertel 6444: 
                   6445: 	if ($space eq 'title') {
                   6446: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6447: 	    return &gettitle($symbparm);
                   6448: 	}
                   6449: 	
                   6450: 	if ($space eq 'map') {
                   6451: 	    my ($map) = &decode_symb($symbparm);
                   6452: 	    return &symbread($map);
                   6453: 	}
1.905     albertel 6454: 	if ($space eq 'filename') {
                   6455: 	    if ($symbparm) {
                   6456: 		return &clutter((&decode_symb($symbparm))[2]);
                   6457: 	    }
                   6458: 	    return &hreflocation('',$env{'request.filename'});
                   6459: 	}
1.693     albertel 6460: 
                   6461: 	my ($section, $group, @groups);
1.593     albertel 6462: 	my ($courselevelm,$courselevel);
1.539     albertel 6463: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6464: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6465: 
1.218     albertel 6466: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6467: 
1.60      www      6468: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6469: 	    my $symbp=$symbparm;
1.735     albertel 6470: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6471: 
                   6472: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6473: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6474: 
1.620     albertel 6475: 	    if (($env{'user.name'} eq $uname) &&
                   6476: 		($env{'user.domain'} eq $udom)) {
                   6477: 		$section=$env{'request.course.sec'};
1.733     raeburn  6478:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6479:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6480: 	    } else {
1.539     albertel 6481: 		if (! defined($usection)) {
1.551     albertel 6482: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6483: 		} else {
                   6484: 		    $section = $usection;
                   6485: 		}
1.733     raeburn  6486:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6487: 	    }
                   6488: 
                   6489: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6490: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6491: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6492: 
1.593     albertel 6493: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6494: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6495: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6496: 
1.60      www      6497: # ----------------------------------------------------------- first, check user
1.624     albertel 6498: 
                   6499: 	    my $userreply=&resdata($uname,$udom,'user',
                   6500: 				       ($courselevelr,$courselevelm,
                   6501: 					$courselevel));
                   6502: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6503: 
1.594     albertel 6504: # ------------------------------------------------ second, check some of course
1.684     raeburn  6505:             my $coursereply;
1.691     raeburn  6506:             if (@groups > 0) {
                   6507:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6508:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6509:                 if (defined($coursereply)) { return $coursereply; }
                   6510:             }
1.96      www      6511: 
1.684     raeburn  6512: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6513: 				     $env{'course.'.$courseid.'.domain'},
                   6514: 				     'course',
                   6515: 				     ($seclevelr,$seclevelm,$seclevel,
                   6516: 				      $courselevelr));
1.287     albertel 6517: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6518: 
1.60      www      6519: # ------------------------------------------------------ third, check map parms
1.218     albertel 6520: 	    my %parmhash=();
                   6521: 	    my $thisparm='';
                   6522: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6523: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6524: 		    &GDBM_READER(),0640)) {
1.218     albertel 6525: 		$thisparm=$parmhash{$symbparm};
                   6526: 		untie(%parmhash);
                   6527: 	    }
                   6528: 	    if ($thisparm) { return $thisparm; }
                   6529: 	}
1.594     albertel 6530: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6531: 
1.218     albertel 6532: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6533: 	my $filename;
                   6534: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6535: 	if ($symbparm) {
1.409     www      6536: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6537: 	} else {
1.620     albertel 6538: 	    $filename=$env{'request.filename'};
1.282     albertel 6539: 	}
                   6540: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6541: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6542: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6543: 	if (defined($metadata)) { return $metadata; }
1.142     www      6544: 
1.594     albertel 6545: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6546: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6547: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6548: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6549: 				     $env{'course.'.$courseid.'.domain'},
                   6550: 				     'course',
                   6551: 				     ($courselevelm,$courselevel));
1.593     albertel 6552: 	    if (defined($coursereply)) { return $coursereply; }
                   6553: 	}
1.145     www      6554: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6555: 	unless ($space eq '0') {
1.336     albertel 6556: 	    my @parts=split(/_/,$space);
                   6557: 	    my $id=pop(@parts);
                   6558: 	    my $part=join('_',@parts);
                   6559: 	    if ($part eq '') { $part='0'; }
                   6560: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6561: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6562: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6563: 	}
1.395     albertel 6564: 	if ($recurse) { return undef; }
                   6565: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6566: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6567: 
1.48      www      6568: # ---------------------------------------------------- Any other user namespace
                   6569:     } elsif ($realm eq 'environment') {
                   6570: # ----------------------------------------------------------------- environment
1.620     albertel 6571: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6572: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6573: 	} else {
1.770     albertel 6574: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6575: 		return '';
                   6576: 	    }
1.219     albertel 6577: 	    my %returnhash=&userenvironment($udom,$uname,
                   6578: 					    $spacequalifierrest);
                   6579: 	    return $returnhash{$spacequalifierrest};
                   6580: 	}
1.28      www      6581:     } elsif ($realm eq 'system') {
1.48      www      6582: # ----------------------------------------------------------------- system.time
                   6583: 	if ($space eq 'time') {
                   6584: 	    return time;
                   6585:         }
1.696     albertel 6586:     } elsif ($realm eq 'server') {
                   6587: # ----------------------------------------------------------------- system.time
                   6588: 	if ($space eq 'name') {
                   6589: 	    return $ENV{'SERVER_NAME'};
                   6590:         }
1.28      www      6591:     }
1.48      www      6592:     return '';
1.61      www      6593: }
                   6594: 
1.691     raeburn  6595: sub check_group_parms {
                   6596:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6597:     my @groupitems = ();
                   6598:     my $resultitem;
                   6599:     my @levels = ($symbparm,$mapparm,$what);
                   6600:     foreach my $group (@{$groups}) {
                   6601:         foreach my $level (@levels) {
                   6602:              my $item = $courseid.'.['.$group.'].'.$level;
                   6603:              push(@groupitems,$item);
                   6604:         }
                   6605:     }
                   6606:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6607:                             $env{'course.'.$courseid.'.domain'},
                   6608:                                      'course',@groupitems);
                   6609:     return $coursereply;
                   6610: }
                   6611: 
                   6612: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6613:     my ($courseid,@groups) = @_;
                   6614:     @groups = sort(@groups);
1.691     raeburn  6615:     return @groups;
                   6616: }
                   6617: 
1.395     albertel 6618: sub packages_tab_default {
                   6619:     my ($uri,$varname)=@_;
                   6620:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6621: 
                   6622:     my (@extension,@specifics,$do_default);
                   6623:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6624: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6625: 	if ($pack_type eq 'default') {
                   6626: 	    $do_default=1;
                   6627: 	} elsif ($pack_type eq 'extension') {
                   6628: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6629: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6630: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6631: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6632: 	}
                   6633:     }
                   6634:     # first look for a package that matches the requested part id
                   6635:     foreach my $package (@specifics) {
                   6636: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6637: 	next if ($pack_part ne $part);
                   6638: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6639: 	    return $packagetab{"$pack_type&$name&default"};
                   6640: 	}
                   6641:     }
                   6642:     # look for any possible matching non extension_ package
                   6643:     foreach my $package (@specifics) {
                   6644: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6645: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6646: 	    return $packagetab{"$pack_type&$name&default"};
                   6647: 	}
1.585     albertel 6648: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6649: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6650: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6651: 	}
                   6652:     }
1.738     albertel 6653:     # look for any posible extension_ match
                   6654:     foreach my $package (@extension) {
                   6655: 	my ($package,$pack_type)=@{$package};
                   6656: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6657: 	    return $packagetab{"$pack_type&$name&default"};
                   6658: 	}
                   6659: 	if (defined($packagetab{$package."&$name&default"})) {
                   6660: 	    return $packagetab{$package."&$name&default"};
                   6661: 	}
                   6662:     }
                   6663:     # look for a global default setting
                   6664:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6665: 	return $packagetab{"default&$name&default"};
                   6666:     }
1.395     albertel 6667:     return undef;
                   6668: }
                   6669: 
1.334     albertel 6670: sub add_prefix_and_part {
                   6671:     my ($prefix,$part)=@_;
                   6672:     my $keyroot;
                   6673:     if (defined($prefix) && $prefix !~ /^__/) {
                   6674: 	# prefix that has a part already
                   6675: 	$keyroot=$prefix;
                   6676:     } elsif (defined($prefix)) {
                   6677: 	# prefix that is missing a part
                   6678: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6679:     } else {
                   6680: 	# no prefix at all
                   6681: 	if (defined($part)) { $keyroot='_'.$part; }
                   6682:     }
                   6683:     return $keyroot;
                   6684: }
                   6685: 
1.71      www      6686: # ---------------------------------------------------------------- Get metadata
                   6687: 
1.599     albertel 6688: my %metaentry;
1.71      www      6689: sub metadata {
1.176     www      6690:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6691:     $uri=&declutter($uri);
1.288     albertel 6692:     # if it is a non metadata possible uri return quickly
1.529     albertel 6693:     if (($uri eq '') || 
                   6694: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6695: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6696:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6697: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6698: 	return undef;
1.288     albertel 6699:     }
1.73      www      6700:     my $filename=$uri;
                   6701:     $uri=~s/\.meta$//;
1.172     www      6702: #
                   6703: # Is the metadata already cached?
1.177     www      6704: # Look at timestamp of caching
1.172     www      6705: # Everything is cached by the main uri, libraries are never directly cached
                   6706: #
1.428     albertel 6707:     if (!defined($liburi)) {
1.599     albertel 6708: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6709: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6710:     }
                   6711:     {
1.172     www      6712: #
                   6713: # Is this a recursive call for a library?
                   6714: #
1.599     albertel 6715: #	if (! exists($metacache{$uri})) {
                   6716: #	    $metacache{$uri}={};
                   6717: #	}
1.171     www      6718:         if ($liburi) {
                   6719: 	    $liburi=&declutter($liburi);
                   6720:             $filename=$liburi;
1.401     bowersj2 6721:         } else {
1.599     albertel 6722: 	    &devalidate_cache_new('meta',$uri);
                   6723: 	    undef(%metaentry);
1.401     bowersj2 6724: 	}
1.140     www      6725:         my %metathesekeys=();
1.73      www      6726:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6727: 	my $metastring;
1.768     albertel 6728: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6729: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6730: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6731: 	    $metastring=&getfile($file);
1.489     albertel 6732: 	}
1.208     albertel 6733:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6734:         my $token;
1.140     www      6735:         undef %metathesekeys;
1.71      www      6736:         while ($token=$parser->get_token) {
1.339     albertel 6737: 	    if ($token->[0] eq 'S') {
                   6738: 		if (defined($token->[2]->{'package'})) {
1.172     www      6739: #
                   6740: # This is a package - get package info
                   6741: #
1.339     albertel 6742: 		    my $package=$token->[2]->{'package'};
                   6743: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6744: 		    if (defined($token->[2]->{'id'})) { 
                   6745: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6746: 		    }
1.599     albertel 6747: 		    if ($metaentry{':packages'}) {
                   6748: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6749: 		    } else {
1.599     albertel 6750: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6751: 		    }
1.736     albertel 6752: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6753: 			my $part=$keyroot;
                   6754: 			$part=~s/^\_//;
1.736     albertel 6755: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6756: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6757: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6758: 			    # ignore package.tab specified default values
                   6759:                             # here &package_tab_default() will fetch those
                   6760: 			    if ($subp eq 'default') { next; }
1.736     albertel 6761: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6762: 			    my $unikey;
                   6763: 			    if ($pack =~ /_0$/) {
                   6764: 				$unikey='parameter_0_'.$name;
                   6765: 				$part=0;
                   6766: 			    } else {
                   6767: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6768: 			    }
1.339     albertel 6769: 			    if ($subp eq 'display') {
                   6770: 				$value.=' [Part: '.$part.']';
                   6771: 			    }
1.599     albertel 6772: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6773: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6774: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6775: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6776: 			    }
1.599     albertel 6777: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6778: 				$metaentry{':'.$unikey}=
                   6779: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6780: 			    }
1.339     albertel 6781: 			}
                   6782: 		    }
                   6783: 		} else {
1.172     www      6784: #
                   6785: # This is not a package - some other kind of start tag
1.339     albertel 6786: #
                   6787: 		    my $entry=$token->[1];
                   6788: 		    my $unikey;
                   6789: 		    if ($entry eq 'import') {
                   6790: 			$unikey='';
                   6791: 		    } else {
                   6792: 			$unikey=$entry;
                   6793: 		    }
                   6794: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6795: 
                   6796: 		    if (defined($token->[2]->{'id'})) { 
                   6797: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6798: 		    }
1.175     www      6799: 
1.339     albertel 6800: 		    if ($entry eq 'import') {
1.175     www      6801: #
                   6802: # Importing a library here
1.339     albertel 6803: #
                   6804: 			if ($depthcount<20) {
                   6805: 			    my $location=$parser->get_text('/import');
                   6806: 			    my $dir=$filename;
                   6807: 			    $dir=~s|[^/]*$||;
                   6808: 			    $location=&filelocation($dir,$location);
1.736     albertel 6809: 			    my $metadata = 
                   6810: 				&metadata($uri,'keys', $location,$unikey,
                   6811: 					  $depthcount+1);
                   6812: 			    foreach my $meta (split(',',$metadata)) {
                   6813: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6814: 				$metathesekeys{$meta}=1;
1.339     albertel 6815: 			    }
                   6816: 			}
                   6817: 		    } else { 
                   6818: 			
                   6819: 			if (defined($token->[2]->{'name'})) { 
                   6820: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6821: 			}
                   6822: 			$metathesekeys{$unikey}=1;
1.736     albertel 6823: 			foreach my $param (@{$token->[3]}) {
                   6824: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6825: 				$token->[2]->{$param};
1.339     albertel 6826: 			}
                   6827: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6828: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6829: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6830: 		 # only ws inside the tag, and not in default, so use default
                   6831: 		 # as value
1.599     albertel 6832: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6833: 			} elsif ( $internaltext =~ /\S/ ) {
                   6834: 		  # something interesting inside the tag
                   6835: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6836: 			} else {
1.908     albertel 6837: 		  # no interesting values, don't set a default
1.339     albertel 6838: 			}
1.172     www      6839: # end of not-a-package not-a-library import
1.339     albertel 6840: 		    }
1.172     www      6841: # end of not-a-package start tag
1.339     albertel 6842: 		}
1.172     www      6843: # the next is the end of "start tag"
1.339     albertel 6844: 	    }
                   6845: 	}
1.483     albertel 6846: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6847: 	$extension = lc($extension);
                   6848: 	if ($extension eq 'htm') { $extension='html'; }
                   6849: 
1.737     albertel 6850: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6851: 	    #no specific packages #how's our extension
                   6852: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6853: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6854: 					 \%metathesekeys);
                   6855: 	}
1.883     albertel 6856: 
                   6857: 	if (!exists($metaentry{':packages'})
                   6858: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6859: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6860: 		#no specific packages well let's get default then
                   6861: 		if ($key!~/^default&/) { next; }
1.488     albertel 6862: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6863: 					     \%metathesekeys);
                   6864: 	    }
                   6865: 	}
1.338     www      6866: # are there custom rights to evaluate
1.599     albertel 6867: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6868: 
1.338     www      6869:     #
                   6870:     # Importing a rights file here
1.339     albertel 6871:     #
                   6872: 	    unless ($depthcount) {
1.599     albertel 6873: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6874: 		my $dir=$filename;
                   6875: 		$dir=~s|[^/]*$||;
                   6876: 		$location=&filelocation($dir,$location);
1.736     albertel 6877: 		my $rights_metadata =
                   6878: 		    &metadata($uri,'keys',$location,'_rights',
                   6879: 			      $depthcount+1);
                   6880: 		foreach my $rights (split(',',$rights_metadata)) {
                   6881: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6882: 		    $metathesekeys{$rights}=1;
1.339     albertel 6883: 		}
                   6884: 	    }
                   6885: 	}
1.737     albertel 6886: 	# uniqifiy package listing
                   6887: 	my %seen;
                   6888: 	my @uniq_packages =
                   6889: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6890: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6891: 
                   6892: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6893: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6894: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6895: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6896: # this is the end of "was not already recently cached
1.71      www      6897:     }
1.599     albertel 6898:     return $metaentry{':'.$what};
1.261     albertel 6899: }
                   6900: 
1.488     albertel 6901: sub metadata_create_package_def {
1.483     albertel 6902:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6903:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6904:     if ($subp eq 'default') { next; }
                   6905:     
1.599     albertel 6906:     if (defined($metaentry{':packages'})) {
                   6907: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6908:     } else {
1.599     albertel 6909: 	$metaentry{':packages'}=$package;
1.483     albertel 6910:     }
                   6911:     my $value=$packagetab{$key};
                   6912:     my $unikey;
                   6913:     $unikey='parameter_0_'.$name;
1.599     albertel 6914:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6915:     $$metathesekeys{$unikey}=1;
1.599     albertel 6916:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6917: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6918:     }
1.599     albertel 6919:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6920: 	$metaentry{':'.$unikey}=
                   6921: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6922:     }
                   6923: }
                   6924: 
1.261     albertel 6925: sub metadata_generate_part0 {
                   6926:     my ($metadata,$metacache,$uri) = @_;
                   6927:     my %allnames;
1.737     albertel 6928:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6929: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6930: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6931: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6932: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6933: 	    $allnames{$name}=$part;
                   6934: 	  }
                   6935: 	}
                   6936:     }
                   6937:     foreach my $name (keys(%allnames)) {
                   6938:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6939:       my $key=":parameter_0_$name";
1.261     albertel 6940:       $$metacache{"$key.part"}='0';
                   6941:       $$metacache{"$key.name"}=$name;
1.428     albertel 6942:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6943: 					   $allnames{$name}.'_'.$name.
                   6944: 					   '.type'};
1.428     albertel 6945:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6946: 			     '.display'};
1.644     www      6947:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6948:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6949:       $$metacache{"$key.display"}=$olddis;
                   6950:     }
1.71      www      6951: }
                   6952: 
1.764     albertel 6953: # ------------------------------------------------------ Devalidate title cache
                   6954: 
                   6955: sub devalidate_title_cache {
                   6956:     my ($url)=@_;
                   6957:     if (!$env{'request.course.id'}) { return; }
                   6958:     my $symb=&symbread($url);
                   6959:     if (!$symb) { return; }
                   6960:     my $key=$env{'request.course.id'}."\0".$symb;
                   6961:     &devalidate_cache_new('title',$key);
                   6962: }
                   6963: 
1.301     www      6964: # ------------------------------------------------- Get the title of a resource
                   6965: 
                   6966: sub gettitle {
                   6967:     my $urlsymb=shift;
                   6968:     my $symb=&symbread($urlsymb);
1.534     albertel 6969:     if ($symb) {
1.620     albertel 6970: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6971: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6972: 	if (defined($cached)) { 
                   6973: 	    return $result;
                   6974: 	}
1.534     albertel 6975: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6976: 	my $title='';
1.907     albertel 6977: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   6978: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   6979: 	} else {
                   6980: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6981: 		    &GDBM_READER(),0640)) {
                   6982: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6983: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   6984: 		untie(%bighash);
                   6985: 	    }
1.534     albertel 6986: 	}
                   6987: 	$title=~s/\&colon\;/\:/gs;
                   6988: 	if ($title) {
1.599     albertel 6989: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6990: 	}
                   6991: 	$urlsymb=$url;
                   6992:     }
                   6993:     my $title=&metadata($urlsymb,'title');
                   6994:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6995:     return $title;
1.301     www      6996: }
1.613     albertel 6997: 
1.614     albertel 6998: sub get_slot {
                   6999:     my ($which,$cnum,$cdom)=@_;
                   7000:     if (!$cnum || !$cdom) {
1.790     albertel 7001: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7002: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7003: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7004:     }
1.703     albertel 7005:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7006:     my %slotinfo;
                   7007:     if (exists($remembered{$key})) {
                   7008: 	$slotinfo{$which} = $remembered{$key};
                   7009:     } else {
                   7010: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7011: 	&Apache::lonhomework::showhash(%slotinfo);
                   7012: 	my ($tmp)=keys(%slotinfo);
                   7013: 	if ($tmp=~/^error:/) { return (); }
                   7014: 	$remembered{$key} = $slotinfo{$which};
                   7015:     }
1.616     albertel 7016:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7017: 	return %{$slotinfo{$which}};
                   7018:     }
                   7019:     return $slotinfo{$which};
1.614     albertel 7020: }
1.31      www      7021: # ------------------------------------------------- Update symbolic store links
                   7022: 
                   7023: sub symblist {
                   7024:     my ($mapname,%newhash)=@_;
1.438     www      7025:     $mapname=&deversion(&declutter($mapname));
1.31      www      7026:     my %hash;
1.620     albertel 7027:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7028:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7029:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7030: 	    foreach my $url (keys %newhash) {
                   7031: 		next if ($url eq 'last_known'
                   7032: 			 && $env{'form.no_update_last_known'});
                   7033: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7034: 						    $newhash{$url}->[1],
                   7035: 						    $newhash{$url}->[0]);
1.191     harris41 7036:             }
1.31      www      7037:             if (untie(%hash)) {
                   7038: 		return 'ok';
                   7039:             }
                   7040:         }
                   7041:     }
                   7042:     return 'error';
1.212     www      7043: }
                   7044: 
                   7045: # --------------------------------------------------------------- Verify a symb
                   7046: 
                   7047: sub symbverify {
1.510     www      7048:     my ($symb,$thisurl)=@_;
                   7049:     my $thisfn=$thisurl;
1.439     www      7050:     $thisfn=&declutter($thisfn);
1.215     www      7051: # direct jump to resource in page or to a sequence - will construct own symbs
                   7052:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7053: # check URL part
1.409     www      7054:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7055: 
1.431     www      7056:     unless ($url eq $thisfn) { return 0; }
1.213     www      7057: 
1.216     www      7058:     $symb=&symbclean($symb);
1.510     www      7059:     $thisurl=&deversion($thisurl);
1.439     www      7060:     $thisfn=&deversion($thisfn);
1.213     www      7061: 
                   7062:     my %bighash;
                   7063:     my $okay=0;
1.431     www      7064: 
1.620     albertel 7065:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7066:                             &GDBM_READER(),0640)) {
1.510     www      7067:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7068:         unless ($ids) { 
1.510     www      7069:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7070:         }
                   7071:         if ($ids) {
                   7072: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7073: 	    foreach my $id (split(/\,/,$ids)) {
                   7074: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7075:                if (
                   7076:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7077:    eq $symb) { 
1.620     albertel 7078: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7079: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7080: 		       $okay=1; 
                   7081: 		   }
                   7082: 	       }
1.216     www      7083: 	   }
                   7084:         }
1.213     www      7085: 	untie(%bighash);
                   7086:     }
                   7087:     return $okay;
1.31      www      7088: }
                   7089: 
1.210     www      7090: # --------------------------------------------------------------- Clean-up symb
                   7091: 
                   7092: sub symbclean {
                   7093:     my $symb=shift;
1.568     albertel 7094:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7095: # remove version from map
                   7096:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7097: 
1.210     www      7098: # remove version from URL
                   7099:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7100: 
1.507     www      7101: # remove wrapper
                   7102: 
1.510     www      7103:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7104:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7105:     return $symb;
1.409     www      7106: }
                   7107: 
                   7108: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7109: 
                   7110: sub encode_symb {
                   7111:     my ($map,$resid,$url)=@_;
                   7112:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7113: }
1.409     www      7114: 
                   7115: sub decode_symb {
1.568     albertel 7116:     my $symb=shift;
                   7117:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7118:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7119:     return (&fixversion($map),$resid,&fixversion($url));
                   7120: }
                   7121: 
                   7122: sub fixversion {
                   7123:     my $fn=shift;
1.609     banghart 7124:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7125:     my %bighash;
                   7126:     my $uri=&clutter($fn);
1.620     albertel 7127:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7128: # is this cached?
1.599     albertel 7129:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7130:     if (defined($cached)) { return $result; }
                   7131: # unfortunately not cached, or expired
1.620     albertel 7132:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7133: 	    &GDBM_READER(),0640)) {
                   7134:  	if ($bighash{'version_'.$uri}) {
                   7135:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7136:  	    unless (($version eq 'mostrecent') || 
                   7137: 		    ($version==&getversion($uri))) {
1.440     www      7138:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7139:  	    }
                   7140:  	}
                   7141:  	untie %bighash;
1.413     www      7142:     }
1.599     albertel 7143:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7144: }
                   7145: 
                   7146: sub deversion {
                   7147:     my $url=shift;
                   7148:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7149:     return $url;
1.210     www      7150: }
                   7151: 
1.31      www      7152: # ------------------------------------------------------ Return symb list entry
                   7153: 
                   7154: sub symbread {
1.249     www      7155:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7156:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7157:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7158: # no filename provided? try from environment
1.44      www      7159:     unless ($thisfn) {
1.620     albertel 7160:         if ($env{'request.symb'}) {
                   7161: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7162: 	}
1.620     albertel 7163: 	$thisfn=$env{'request.filename'};
1.44      www      7164:     }
1.569     albertel 7165:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7166: # is that filename actually a symb? Verify, clean, and return
                   7167:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7168: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7169: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7170: 	}
1.242     www      7171:     }
1.44      www      7172:     $thisfn=declutter($thisfn);
1.31      www      7173:     my %hash;
1.37      www      7174:     my %bighash;
                   7175:     my $syval='';
1.620     albertel 7176:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7177:         my $targetfn = $thisfn;
1.609     banghart 7178:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7179:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7180:         }
1.687     albertel 7181: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7182: 	    $targetfn=$1;
                   7183: 	}
1.620     albertel 7184:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7185:                       &GDBM_READER(),0640)) {
1.481     raeburn  7186: 	    $syval=$hash{$targetfn};
1.37      www      7187:             untie(%hash);
                   7188:         }
                   7189: # ---------------------------------------------------------- There was an entry
                   7190:         if ($syval) {
1.601     albertel 7191: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7192: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7193: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7194: 		    #return $env{$cache_str}='';
1.601     albertel 7195: 		#}    
                   7196: 		#$syval.=$1;
                   7197: 	    #}
1.37      www      7198:         } else {
                   7199: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7200:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7201:                             &GDBM_READER(),0640)) {
1.37      www      7202: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7203:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7204:               unless ($ids) { 
                   7205:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7206:               }
                   7207:               unless ($ids) {
                   7208: # alias?
                   7209: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7210:               }
1.37      www      7211:               if ($ids) {
                   7212: # ------------------------------------------------------------------- Has ID(s)
                   7213:                  my @possibilities=split(/\,/,$ids);
1.39      www      7214:                  if ($#possibilities==0) {
                   7215: # ----------------------------------------------- There is only one possibility
1.37      www      7216: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7217: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7218: 						    $resid,$thisfn);
1.249     www      7219:                  } elsif (!$donotrecurse) {
1.39      www      7220: # ------------------------------------------ There is more than one possibility
                   7221:                      my $realpossible=0;
1.800     albertel 7222:                      foreach my $id (@possibilities) {
                   7223: 			 my $file=$bighash{'src_'.$id};
1.39      www      7224:                          if (&allowed('bre',$file)) {
1.800     albertel 7225:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7226:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7227: 				$realpossible++;
1.626     albertel 7228:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7229: 						    $resid,$thisfn);
1.39      www      7230:                             }
                   7231: 			 }
1.191     harris41 7232:                      }
1.39      www      7233: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7234:                  } else {
                   7235:                      $syval='';
1.37      www      7236:                  }
                   7237: 	      }
                   7238:               untie(%bighash)
1.481     raeburn  7239:            }
1.31      www      7240:         }
1.62      www      7241:         if ($syval) {
1.620     albertel 7242: 	    return $env{$cache_str}=$syval;
1.62      www      7243:         }
1.31      www      7244:     }
1.44      www      7245:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7246:     return $env{$cache_str}='';
1.31      www      7247: }
                   7248: 
                   7249: # ---------------------------------------------------------- Return random seed
                   7250: 
1.32      www      7251: sub numval {
                   7252:     my $txt=shift;
                   7253:     $txt=~tr/A-J/0-9/;
                   7254:     $txt=~tr/a-j/0-9/;
                   7255:     $txt=~tr/K-T/0-9/;
                   7256:     $txt=~tr/k-t/0-9/;
                   7257:     $txt=~tr/U-Z/0-5/;
                   7258:     $txt=~tr/u-z/0-5/;
                   7259:     $txt=~s/\D//g;
1.564     albertel 7260:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7261:     return int($txt);
1.368     albertel 7262: }
                   7263: 
1.484     albertel 7264: sub numval2 {
                   7265:     my $txt=shift;
                   7266:     $txt=~tr/A-J/0-9/;
                   7267:     $txt=~tr/a-j/0-9/;
                   7268:     $txt=~tr/K-T/0-9/;
                   7269:     $txt=~tr/k-t/0-9/;
                   7270:     $txt=~tr/U-Z/0-5/;
                   7271:     $txt=~tr/u-z/0-5/;
                   7272:     $txt=~s/\D//g;
                   7273:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7274:     my $total;
                   7275:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7276:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7277:     return int($total);
                   7278: }
                   7279: 
1.575     albertel 7280: sub numval3 {
                   7281:     use integer;
                   7282:     my $txt=shift;
                   7283:     $txt=~tr/A-J/0-9/;
                   7284:     $txt=~tr/a-j/0-9/;
                   7285:     $txt=~tr/K-T/0-9/;
                   7286:     $txt=~tr/k-t/0-9/;
                   7287:     $txt=~tr/U-Z/0-5/;
                   7288:     $txt=~tr/u-z/0-5/;
                   7289:     $txt=~s/\D//g;
                   7290:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7291:     my $total;
                   7292:     foreach my $val (@txts) { $total+=$val; }
                   7293:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7294:     return $total;
                   7295: }
                   7296: 
1.675     albertel 7297: sub digest {
                   7298:     my ($data)=@_;
                   7299:     my $digest=&Digest::MD5::md5($data);
                   7300:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7301:     my ($e,$f);
                   7302:     {
                   7303:         use integer;
                   7304:         $e=($a+$b);
                   7305:         $f=($c+$d);
                   7306:         if ($_64bit) {
                   7307:             $e=(($e<<32)>>32);
                   7308:             $f=(($f<<32)>>32);
                   7309:         }
                   7310:     }
                   7311:     if (wantarray) {
                   7312: 	return ($e,$f);
                   7313:     } else {
                   7314: 	my $g;
                   7315: 	{
                   7316: 	    use integer;
                   7317: 	    $g=($e+$f);
                   7318: 	    if ($_64bit) {
                   7319: 		$g=(($g<<32)>>32);
                   7320: 	    }
                   7321: 	}
                   7322: 	return $g;
                   7323:     }
                   7324: }
                   7325: 
1.368     albertel 7326: sub latest_rnd_algorithm_id {
1.675     albertel 7327:     return '64bit5';
1.366     albertel 7328: }
1.32      www      7329: 
1.503     albertel 7330: sub get_rand_alg {
                   7331:     my ($courseid)=@_;
1.790     albertel 7332:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7333:     if ($courseid) {
1.620     albertel 7334: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7335:     }
                   7336:     return &latest_rnd_algorithm_id();
                   7337: }
                   7338: 
1.562     albertel 7339: sub validCODE {
                   7340:     my ($CODE)=@_;
                   7341:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7342:     return 0;
                   7343: }
                   7344: 
1.491     albertel 7345: sub getCODE {
1.620     albertel 7346:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7347:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7348: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7349: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7350: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7351:     }
                   7352:     return undef;
                   7353: }
                   7354: 
1.31      www      7355: sub rndseed {
1.155     albertel 7356:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7357:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7358:     if (!defined($symb)) {
1.366     albertel 7359: 	unless ($symb=$wsymb) { return time; }
                   7360:     }
                   7361:     if (!$courseid) { $courseid=$wcourseid; }
                   7362:     if (!$domain) { $domain=$wdomain; }
                   7363:     if (!$username) { $username=$wusername }
1.503     albertel 7364:     my $which=&get_rand_alg();
1.803     albertel 7365: 
1.491     albertel 7366:     if (defined(&getCODE())) {
1.675     albertel 7367: 	if ($which eq '64bit5') {
                   7368: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7369: 	} elsif ($which eq '64bit4') {
1.575     albertel 7370: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7371: 	} else {
                   7372: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7373: 	}
1.675     albertel 7374:     } elsif ($which eq '64bit5') {
                   7375: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7376:     } elsif ($which eq '64bit4') {
                   7377: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7378:     } elsif ($which eq '64bit3') {
                   7379: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7380:     } elsif ($which eq '64bit2') {
                   7381: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7382:     } elsif ($which eq '64bit') {
                   7383: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7384:     }
                   7385:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7386: }
                   7387: 
                   7388: sub rndseed_32bit {
                   7389:     my ($symb,$courseid,$domain,$username)=@_;
                   7390:     {
                   7391: 	use integer;
                   7392: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7393: 	my $symbseed=numval($symb) << 22;
                   7394: 	my $namechck=unpack("%32C*",$username) << 17;
                   7395: 	my $nameseed=numval($username) << 12;
                   7396: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7397: 	my $courseseed=unpack("%32C*",$courseid);
                   7398: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7399: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7400: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7401: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7402: 	return $num;
                   7403:     }
                   7404: }
                   7405: 
                   7406: sub rndseed_64bit {
                   7407:     my ($symb,$courseid,$domain,$username)=@_;
                   7408:     {
                   7409: 	use integer;
                   7410: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7411: 	my $symbseed=numval($symb) << 10;
                   7412: 	my $namechck=unpack("%32S*",$username);
                   7413: 	
                   7414: 	my $nameseed=numval($username) << 21;
                   7415: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7416: 	my $courseseed=unpack("%32S*",$courseid);
                   7417: 	
                   7418: 	my $num1=$symbchck+$symbseed+$namechck;
                   7419: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7420: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7421: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7422: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7423: 	return "$num1,$num2";
1.155     albertel 7424:     }
1.366     albertel 7425: }
                   7426: 
1.443     albertel 7427: sub rndseed_64bit2 {
                   7428:     my ($symb,$courseid,$domain,$username)=@_;
                   7429:     {
                   7430: 	use integer;
                   7431: 	# strings need to be an even # of cahracters long, it it is odd the
                   7432:         # last characters gets thrown away
                   7433: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7434: 	my $symbseed=numval($symb) << 10;
                   7435: 	my $namechck=unpack("%32S*",$username.' ');
                   7436: 	
                   7437: 	my $nameseed=numval($username) << 21;
1.501     albertel 7438: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7439: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7440: 	
                   7441: 	my $num1=$symbchck+$symbseed+$namechck;
                   7442: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7443: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7444: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7445: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7446: 	return "$num1,$num2";
                   7447:     }
                   7448: }
                   7449: 
                   7450: sub rndseed_64bit3 {
                   7451:     my ($symb,$courseid,$domain,$username)=@_;
                   7452:     {
                   7453: 	use integer;
                   7454: 	# strings need to be an even # of cahracters long, it it is odd the
                   7455:         # last characters gets thrown away
                   7456: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7457: 	my $symbseed=numval2($symb) << 10;
                   7458: 	my $namechck=unpack("%32S*",$username.' ');
                   7459: 	
                   7460: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7461: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7462: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7463: 	
                   7464: 	my $num1=$symbchck+$symbseed+$namechck;
                   7465: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7466: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7467: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7468: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7469: 	
1.503     albertel 7470: 	return "$num1:$num2";
1.443     albertel 7471:     }
                   7472: }
                   7473: 
1.575     albertel 7474: sub rndseed_64bit4 {
                   7475:     my ($symb,$courseid,$domain,$username)=@_;
                   7476:     {
                   7477: 	use integer;
                   7478: 	# strings need to be an even # of cahracters long, it it is odd the
                   7479:         # last characters gets thrown away
                   7480: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7481: 	my $symbseed=numval3($symb) << 10;
                   7482: 	my $namechck=unpack("%32S*",$username.' ');
                   7483: 	
                   7484: 	my $nameseed=numval3($username) << 21;
                   7485: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7486: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7487: 	
                   7488: 	my $num1=$symbchck+$symbseed+$namechck;
                   7489: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7490: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7491: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7492: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7493: 	
                   7494: 	return "$num1:$num2";
                   7495:     }
                   7496: }
                   7497: 
1.675     albertel 7498: sub rndseed_64bit5 {
                   7499:     my ($symb,$courseid,$domain,$username)=@_;
                   7500:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7501:     return "$num1:$num2";
                   7502: }
                   7503: 
1.366     albertel 7504: sub rndseed_CODE_64bit {
                   7505:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7506:     {
1.366     albertel 7507: 	use integer;
1.443     albertel 7508: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7509: 	my $symbseed=numval2($symb);
1.491     albertel 7510: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7511: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7512: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7513: 	my $num1=$symbseed+$CODEchck;
                   7514: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7515: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7516: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7517: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7518: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7519: 	return "$num1:$num2";
1.366     albertel 7520:     }
                   7521: }
                   7522: 
1.575     albertel 7523: sub rndseed_CODE_64bit4 {
                   7524:     my ($symb,$courseid,$domain,$username)=@_;
                   7525:     {
                   7526: 	use integer;
                   7527: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7528: 	my $symbseed=numval3($symb);
                   7529: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7530: 	my $CODEseed=numval3(&getCODE());
                   7531: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7532: 	my $num1=$symbseed+$CODEchck;
                   7533: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7534: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7535: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7536: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7537: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7538: 	return "$num1:$num2";
                   7539:     }
                   7540: }
                   7541: 
1.675     albertel 7542: sub rndseed_CODE_64bit5 {
                   7543:     my ($symb,$courseid,$domain,$username)=@_;
                   7544:     my $code = &getCODE();
                   7545:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7546:     return "$num1:$num2";
                   7547: }
                   7548: 
1.366     albertel 7549: sub setup_random_from_rndseed {
                   7550:     my ($rndseed)=@_;
1.503     albertel 7551:     if ($rndseed =~/([,:])/) {
                   7552: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7553: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7554:     } else {
                   7555: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7556:     }
1.36      albertel 7557: }
                   7558: 
1.474     albertel 7559: sub latest_receipt_algorithm_id {
1.835     albertel 7560:     return 'receipt3';
1.474     albertel 7561: }
                   7562: 
1.480     www      7563: sub recunique {
                   7564:     my $fucourseid=shift;
                   7565:     my $unique;
1.835     albertel 7566:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7567: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7568: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7569:     } else {
                   7570: 	$unique=$perlvar{'lonReceipt'};
                   7571:     }
                   7572:     return unpack("%32C*",$unique);
                   7573: }
                   7574: 
                   7575: sub recprefix {
                   7576:     my $fucourseid=shift;
                   7577:     my $prefix;
1.835     albertel 7578:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7579: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7580: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7581:     } else {
                   7582: 	$prefix=$perlvar{'lonHostID'};
                   7583:     }
                   7584:     return unpack("%32C*",$prefix);
                   7585: }
                   7586: 
1.76      www      7587: sub ireceipt {
1.474     albertel 7588:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7589: 
                   7590:     my $return =&recprefix($fucourseid).'-';
                   7591: 
                   7592:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7593: 	$env{'request.state'} eq 'construct') {
                   7594: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7595: 	return $return;
                   7596:     }
                   7597: 
1.76      www      7598:     my $cuname=unpack("%32C*",$funame);
                   7599:     my $cudom=unpack("%32C*",$fudom);
                   7600:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7601:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7602:     my $cunique=&recunique($fucourseid);
1.474     albertel 7603:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7604:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7605: 
1.790     albertel 7606: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7607: 			       
                   7608: 	$return.= ($cunique%$cuname+
                   7609: 		   $cunique%$cudom+
                   7610: 		   $cusymb%$cuname+
                   7611: 		   $cusymb%$cudom+
                   7612: 		   $cucourseid%$cuname+
                   7613: 		   $cucourseid%$cudom+
                   7614: 		   $cpart%$cuname+
                   7615: 		   $cpart%$cudom);
                   7616:     } else {
                   7617: 	$return.= ($cunique%$cuname+
                   7618: 		   $cunique%$cudom+
                   7619: 		   $cusymb%$cuname+
                   7620: 		   $cusymb%$cudom+
                   7621: 		   $cucourseid%$cuname+
                   7622: 		   $cucourseid%$cudom);
                   7623:     }
                   7624:     return $return;
1.76      www      7625: }
                   7626: 
                   7627: sub receipt {
1.474     albertel 7628:     my ($part)=@_;
1.790     albertel 7629:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7630:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7631: }
1.260     ng       7632: 
1.790     albertel 7633: sub whichuser {
                   7634:     my ($passedsymb)=@_;
                   7635:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7636:     if (defined($env{'form.grade_symb'})) {
                   7637: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7638: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7639: 	if (!$allowed &&
                   7640: 	    exists($env{'request.course.sec'}) &&
                   7641: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7642: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7643: 			      '/'.$env{'request.course.sec'});
                   7644: 	}
                   7645: 	if ($allowed) {
                   7646: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7647: 	    $courseid=$tmp_courseid;
                   7648: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7649: 	    ($name)=&get_env_multiple('form.grade_username');
                   7650: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7651: 	}
                   7652:     }
                   7653:     if (!$passedsymb) {
                   7654: 	$symb=&symbread();
                   7655:     } else {
                   7656: 	$symb=$passedsymb;
                   7657:     }
                   7658:     $courseid=$env{'request.course.id'};
                   7659:     $domain=$env{'user.domain'};
                   7660:     $name=$env{'user.name'};
                   7661:     if ($name eq 'public' && $domain eq 'public') {
                   7662: 	if (!defined($env{'form.username'})) {
                   7663: 	    $env{'form.username'}.=time.rand(10000000);
                   7664: 	}
                   7665: 	$name.=$env{'form.username'};
                   7666:     }
                   7667:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7668: 
                   7669: }
                   7670: 
1.36      albertel 7671: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7672: # returns either the contents of the file or 
                   7673: # -1 if the file doesn't exist
1.481     raeburn  7674: #
                   7675: # if the target is a file that was uploaded via DOCS, 
                   7676: # a check will be made to see if a current copy exists on the local server,
                   7677: # if it does this will be served, otherwise a copy will be retrieved from
                   7678: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7679: # the local server.   
1.472     albertel 7680: 
1.36      albertel 7681: sub getfile {
1.538     albertel 7682:     my ($file) = @_;
1.609     banghart 7683:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7684:     &repcopy($file);
                   7685:     return &readfile($file);
                   7686: }
                   7687: 
                   7688: sub repcopy_userfile {
                   7689:     my ($file)=@_;
1.609     banghart 7690:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7691:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7692:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7693: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7694:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7695:     if (-e "$file") {
1.828     www      7696: # we already have a local copy, check it out
1.538     albertel 7697: 	my @fileinfo = stat($file);
1.828     www      7698: 	my $rtncode;
                   7699: 	my $info;
1.538     albertel 7700: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7701: 	if ($lwpresp ne 'ok') {
1.828     www      7702: # there is no such file anymore, even though we had a local copy
1.482     albertel 7703: 	    if ($rtncode eq '404') {
1.538     albertel 7704: 		unlink($file);
1.482     albertel 7705: 	    }
                   7706: 	    return -1;
                   7707: 	}
                   7708: 	if ($info < $fileinfo[9]) {
1.828     www      7709: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7710: 	    return 'ok';
1.828     www      7711: 	} else {
                   7712: # the file is outdated, get rid of it
                   7713: 	    unlink($file);
1.482     albertel 7714: 	}
1.828     www      7715:     }
                   7716: # one way or the other, at this point, we don't have the file
                   7717: # construct the correct path for the file
                   7718:     my @parts = ($cdom,$cnum); 
                   7719:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7720: 	push @parts, split(/\//,$1);
                   7721:     }
                   7722:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7723:     foreach my $part (@parts) {
                   7724: 	$path .= '/'.$part;
                   7725: 	if (!-e $path) {
                   7726: 	    mkdir($path,0770);
1.482     albertel 7727: 	}
                   7728:     }
1.828     www      7729: # now the path exists for sure
                   7730: # get a user agent
                   7731:     my $ua=new LWP::UserAgent;
                   7732:     my $transferfile=$file.'.in.transfer';
                   7733: # FIXME: this should flock
                   7734:     if (-e $transferfile) { return 'ok'; }
                   7735:     my $request;
                   7736:     $uri=~s/^\///;
1.838     albertel 7737:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7738:     my $response=$ua->request($request,$transferfile);
                   7739: # did it work?
                   7740:     if ($response->is_error()) {
                   7741: 	unlink($transferfile);
                   7742: 	&logthis("Userfile repcopy failed for $uri");
                   7743: 	return -1;
                   7744:     }
                   7745: # worked, rename the transfer file
                   7746:     rename($transferfile,$file);
1.607     raeburn  7747:     return 'ok';
1.481     raeburn  7748: }
                   7749: 
1.517     albertel 7750: sub tokenwrapper {
                   7751:     my $uri=shift;
1.552     albertel 7752:     $uri=~s|^http\://([^/]+)||;
                   7753:     $uri=~s|^/||;
1.620     albertel 7754:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7755:     my $token=$1;
1.552     albertel 7756:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7757:     if ($udom && $uname && $file) {
                   7758: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7759:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7760:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7761:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7762:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7763:     } else {
                   7764:         return '/adm/notfound.html';
                   7765:     }
                   7766: }
                   7767: 
1.828     www      7768: # call with reqtype HEAD: get last modification time
                   7769: # call with reqtype GET: get the file contents
                   7770: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7771: #
1.481     raeburn  7772: sub getuploaded {
                   7773:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7774:     $uri=~s/^\///;
1.838     albertel 7775:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7776:     my $ua=new LWP::UserAgent;
                   7777:     my $request=new HTTP::Request($reqtype,$uri);
                   7778:     my $response=$ua->request($request);
                   7779:     $$rtncode = $response->code;
1.482     albertel 7780:     if (! $response->is_success()) {
                   7781: 	return 'failed';
                   7782:     }      
                   7783:     if ($reqtype eq 'HEAD') {
1.486     www      7784: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7785:     } elsif ($reqtype eq 'GET') {
                   7786: 	$$info = $response->content;
1.472     albertel 7787:     }
1.482     albertel 7788:     return 'ok';
1.36      albertel 7789: }
                   7790: 
1.481     raeburn  7791: sub readfile {
                   7792:     my $file = shift;
                   7793:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7794:     my $fh;
                   7795:     open($fh,"<$file");
                   7796:     my $a='';
1.800     albertel 7797:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7798:     return $a;
                   7799: }
                   7800: 
1.36      albertel 7801: sub filelocation {
1.590     banghart 7802:     my ($dir,$file) = @_;
                   7803:     my $location;
                   7804:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7805: 
                   7806:     if ($file =~ m-^/adm/-) {
                   7807: 	$file=~s-^/adm/wrapper/-/-;
                   7808: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7809:     }
1.882     albertel 7810: 
1.590     banghart 7811:     if ($file=~m:^/~:) { # is a contruction space reference
                   7812:         $location = $file;
                   7813:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7814:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7815: 	# is a correct contruction space reference
                   7816:         $location = $file;
1.609     banghart 7817:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7818:         my ($udom,$uname,$filename)=
1.811     albertel 7819:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7820:         my $home=&homeserver($uname,$udom);
                   7821:         my $is_me=0;
                   7822:         my @ids=&current_machine_ids();
                   7823:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7824:         if ($is_me) {
1.740     www      7825:   	    $location=&propath($udom,$uname).
1.590     banghart 7826:   	      '/userfiles/'.$filename;
                   7827:         } else {
                   7828:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7829:   	      $udom.'/'.$uname.'/'.$filename;
                   7830:         }
1.882     albertel 7831:     } elsif ($file =~ m-^/adm/-) {
                   7832: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7833:     } else {
                   7834:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7835:         $file=~s:^/res/:/:;
                   7836:         if ( !( $file =~ m:^/:) ) {
                   7837:             $location = $dir. '/'.$file;
                   7838:         } else {
                   7839:             $location = '/home/httpd/html/res'.$file;
                   7840:         }
1.59      albertel 7841:     }
1.590     banghart 7842:     $location=~s://+:/:g; # remove duplicate /
                   7843:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7844:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7845:     return $location;
1.46      www      7846: }
1.36      albertel 7847: 
1.46      www      7848: sub hreflocation {
                   7849:     my ($dir,$file)=@_;
1.460     albertel 7850:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7851: 	$file=filelocation($dir,$file);
1.700     albertel 7852:     } elsif ($file=~m-^/adm/-) {
                   7853: 	$file=~s-^/adm/wrapper/-/-;
                   7854: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7855:     }
                   7856:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7857: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7858:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7859: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7860:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7861: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7862: 	    -/uploaded/$1/$2/-x;
1.46      www      7863:     }
1.913     albertel 7864:     if ($file=~ m{^/userfiles/}) {
                   7865: 	$file =~ s{^/userfiles/}{/uploaded/};
                   7866:     }
1.462     albertel 7867:     return $file;
1.465     albertel 7868: }
                   7869: 
                   7870: sub current_machine_domains {
1.853     albertel 7871:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7872: }
                   7873: 
                   7874: sub machine_domains {
                   7875:     my ($hostname) = @_;
1.465     albertel 7876:     my @domains;
1.838     albertel 7877:     my %hostname = &all_hostnames();
1.465     albertel 7878:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7879: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7880: 	if ($hostname eq $name) {
1.844     albertel 7881: 	    push(@domains,&host_domain($id));
1.465     albertel 7882: 	}
                   7883:     }
                   7884:     return @domains;
                   7885: }
                   7886: 
                   7887: sub current_machine_ids {
1.853     albertel 7888:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7889: }
                   7890: 
                   7891: sub machine_ids {
                   7892:     my ($hostname) = @_;
                   7893:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7894:     my @ids;
1.888     albertel 7895:     my %name_to_host = &all_names();
1.889     albertel 7896:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7897: 	return @{ $name_to_host{$hostname} };
                   7898:     }
                   7899:     return;
1.31      www      7900: }
                   7901: 
1.824     raeburn  7902: sub additional_machine_domains {
                   7903:     my @domains;
                   7904:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7905:     while( my $line = <$fh>) {
                   7906:         $line =~ s/\s//g;
                   7907:         push(@domains,$line);
                   7908:     }
                   7909:     return @domains;
                   7910: }
                   7911: 
                   7912: sub default_login_domain {
                   7913:     my $domain = $perlvar{'lonDefDomain'};
                   7914:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7915:     foreach my $posdom (&current_machine_domains(),
                   7916:                         &additional_machine_domains()) {
                   7917:         if (lc($posdom) eq lc($testdomain)) {
                   7918:             $domain=$posdom;
                   7919:             last;
                   7920:         }
                   7921:     }
                   7922:     return $domain;
                   7923: }
                   7924: 
1.31      www      7925: # ------------------------------------------------------------- Declutters URLs
                   7926: 
                   7927: sub declutter {
                   7928:     my $thisfn=shift;
1.569     albertel 7929:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7930:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7931:     $thisfn=~s/^\///;
1.697     albertel 7932:     $thisfn=~s|^adm/wrapper/||;
                   7933:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7934:     $thisfn=~s/^res\///;
1.235     www      7935:     $thisfn=~s/\?.+$//;
1.268     www      7936:     return $thisfn;
                   7937: }
                   7938: 
                   7939: # ------------------------------------------------------------- Clutter up URLs
                   7940: 
                   7941: sub clutter {
                   7942:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7943:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7944: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7945:        $thisfn='/res'.$thisfn; 
                   7946:     }
1.694     albertel 7947:     if ($thisfn !~m|/adm|) {
1.695     albertel 7948: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7949: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7950: 	} else {
                   7951: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7952: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7953: 	    if ($embstyle eq 'ssi'
                   7954: 		|| ($embstyle eq 'hdn')
                   7955: 		|| ($embstyle eq 'rat')
                   7956: 		|| ($embstyle eq 'prv')
                   7957: 		|| ($embstyle eq 'ign')) {
                   7958: 		#do nothing with these
                   7959: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7960: 		|| ($embstyle eq 'emb')
                   7961: 		|| ($embstyle eq 'wrp')) {
                   7962: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7963: 	    } elsif ($embstyle eq 'unk'
                   7964: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7965: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7966: 	    } else {
1.718     www      7967: #		&logthis("Got a blank emb style");
1.695     albertel 7968: 	    }
1.694     albertel 7969: 	}
                   7970:     }
1.31      www      7971:     return $thisfn;
1.12      www      7972: }
                   7973: 
1.787     albertel 7974: sub clutter_with_no_wrapper {
                   7975:     my $uri = &clutter(shift);
                   7976:     if ($uri =~ m-^/adm/-) {
                   7977: 	$uri =~ s-^/adm/wrapper/-/-;
                   7978: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7979:     }
                   7980:     return $uri;
                   7981: }
                   7982: 
1.557     albertel 7983: sub freeze_escape {
                   7984:     my ($value)=@_;
                   7985:     if (ref($value)) {
                   7986: 	$value=&nfreeze($value);
                   7987: 	return '__FROZEN__'.&escape($value);
                   7988:     }
                   7989:     return &escape($value);
                   7990: }
                   7991: 
1.11      www      7992: 
1.557     albertel 7993: sub thaw_unescape {
                   7994:     my ($value)=@_;
                   7995:     if ($value =~ /^__FROZEN__/) {
                   7996: 	substr($value,0,10,undef);
                   7997: 	$value=&unescape($value);
                   7998: 	return &thaw($value);
                   7999:     }
                   8000:     return &unescape($value);
                   8001: }
                   8002: 
1.436     albertel 8003: sub correct_line_ends {
                   8004:     my ($result)=@_;
                   8005:     $$result =~s/\r\n/\n/mg;
                   8006:     $$result =~s/\r/\n/mg;
1.415     albertel 8007: }
1.1       albertel 8008: # ================================================================ Main Program
                   8009: 
1.184     www      8010: sub goodbye {
1.204     albertel 8011:    &logthis("Starting Shut down");
1.443     albertel 8012: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8013:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8014: #converted
1.599     albertel 8015: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8016:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8017: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8018: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8019: #1.1 only
1.870     albertel 8020: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8021: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8022: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8023: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8024:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8025:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8026:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8027:    &flushcourselogs();
                   8028:    &logthis("Shutting down");
                   8029: }
                   8030: 
1.852     albertel 8031: sub get_dns {
1.869     albertel 8032:     my ($url,$func,$ignore_cache) = @_;
                   8033:     if (!$ignore_cache) {
                   8034: 	my ($content,$cached)=
                   8035: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8036: 	if ($cached) {
                   8037: 	    &$func($content);
                   8038: 	    return;
                   8039: 	}
                   8040:     }
                   8041: 
                   8042:     my %alldns;
1.852     albertel 8043:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8044:     foreach my $dns (<$config>) {
                   8045: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8046: 	$alldns{$1} = 1;
                   8047:     }
                   8048:     while (%alldns) {
                   8049: 	my ($dns) = keys(%alldns);
                   8050: 	delete($alldns{$dns});
1.852     albertel 8051: 	my $ua=new LWP::UserAgent;
                   8052: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8053: 	my $response=$ua->request($request);
                   8054: 	next if ($response->is_error());
                   8055: 	my @content = split("\n",$response->content);
1.869     albertel 8056: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8057: 	&$func(\@content);
1.869     albertel 8058: 	return;
1.852     albertel 8059:     }
                   8060:     close($config);
1.871     albertel 8061:     my $which = (split('/',$url))[3];
                   8062:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8063:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8064:     my @content = <$config>;
                   8065:     &$func(\@content);
                   8066:     return;
1.852     albertel 8067: }
1.327     albertel 8068: # ------------------------------------------------------------ Read domain file
                   8069: {
1.852     albertel 8070:     my $loaded;
1.846     albertel 8071:     my %domain;
                   8072: 
1.852     albertel 8073:     sub parse_domain_tab {
                   8074: 	my ($lines) = @_;
                   8075: 	foreach my $line (@$lines) {
                   8076: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8077: 
1.846     albertel 8078: 	    chomp($line);
1.852     albertel 8079: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8080: 	    my %this_domain;
                   8081: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8082: 			       'lang_def', 'city', 'longi', 'lati',
                   8083: 			       'primary') {
                   8084: 		$this_domain{$field} = shift(@elements);
                   8085: 	    }
                   8086: 	    $domain{$name} = \%this_domain;
1.852     albertel 8087: 	}
                   8088:     }
1.864     albertel 8089: 
                   8090:     sub reset_domain_info {
                   8091: 	undef($loaded);
                   8092: 	undef(%domain);
                   8093:     }
                   8094: 
1.852     albertel 8095:     sub load_domain_tab {
1.869     albertel 8096: 	my ($ignore_cache) = @_;
                   8097: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8098: 	my $fh;
                   8099: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8100: 	    my @lines = <$fh>;
                   8101: 	    &parse_domain_tab(\@lines);
1.448     albertel 8102: 	}
1.852     albertel 8103: 	close($fh);
                   8104: 	$loaded = 1;
1.327     albertel 8105:     }
1.846     albertel 8106: 
                   8107:     sub domain {
1.852     albertel 8108: 	&load_domain_tab() if (!$loaded);
                   8109: 
1.846     albertel 8110: 	my ($name,$what) = @_;
                   8111: 	return if ( !exists($domain{$name}) );
                   8112: 
                   8113: 	if (!$what) {
                   8114: 	    return $domain{$name}{'description'};
                   8115: 	}
                   8116: 	return $domain{$name}{$what};
                   8117:     }
1.327     albertel 8118: }
                   8119: 
                   8120: 
1.1       albertel 8121: # ------------------------------------------------------------- Read hosts file
                   8122: {
1.838     albertel 8123:     my %hostname;
1.844     albertel 8124:     my %hostdom;
1.845     albertel 8125:     my %libserv;
1.852     albertel 8126:     my $loaded;
1.888     albertel 8127:     my %name_to_host;
1.852     albertel 8128: 
                   8129:     sub parse_hosts_tab {
                   8130: 	my ($file) = @_;
                   8131: 	foreach my $configline (@$file) {
                   8132: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8133: 	    next if ($configline =~ /^\^/);
                   8134: 	    chomp($configline);
                   8135: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8136: 	    $name=~s/\s//g;
                   8137: 	    if ($id && $domain && $role && $name) {
                   8138: 		$hostname{$id}=$name;
1.888     albertel 8139: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8140: 		$hostdom{$id}=$domain;
                   8141: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8142: 	    }
                   8143: 	}
                   8144:     }
1.864     albertel 8145:     
                   8146:     sub reset_hosts_info {
1.897     albertel 8147: 	&purge_remembered();
1.864     albertel 8148: 	&reset_domain_info();
                   8149: 	&reset_hosts_ip_info();
1.892     albertel 8150: 	undef(%name_to_host);
1.864     albertel 8151: 	undef(%hostname);
                   8152: 	undef(%hostdom);
                   8153: 	undef(%libserv);
                   8154: 	undef($loaded);
                   8155:     }
1.1       albertel 8156: 
1.852     albertel 8157:     sub load_hosts_tab {
1.869     albertel 8158: 	my ($ignore_cache) = @_;
                   8159: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8160: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8161: 	my @config = <$config>;
                   8162: 	&parse_hosts_tab(\@config);
                   8163: 	close($config);
                   8164: 	$loaded=1;
1.1       albertel 8165:     }
1.852     albertel 8166: 
1.838     albertel 8167:     sub hostname {
1.852     albertel 8168: 	&load_hosts_tab() if (!$loaded);
                   8169: 
1.838     albertel 8170: 	my ($lonid) = @_;
                   8171: 	return $hostname{$lonid};
                   8172:     }
1.845     albertel 8173: 
1.838     albertel 8174:     sub all_hostnames {
1.852     albertel 8175: 	&load_hosts_tab() if (!$loaded);
                   8176: 
1.838     albertel 8177: 	return %hostname;
                   8178:     }
1.845     albertel 8179: 
1.888     albertel 8180:     sub all_names {
                   8181: 	&load_hosts_tab() if (!$loaded);
                   8182: 
                   8183: 	return %name_to_host;
                   8184:     }
                   8185: 
1.845     albertel 8186:     sub is_library {
1.852     albertel 8187: 	&load_hosts_tab() if (!$loaded);
                   8188: 
1.845     albertel 8189: 	return exists($libserv{$_[0]});
                   8190:     }
                   8191: 
                   8192:     sub all_library {
1.852     albertel 8193: 	&load_hosts_tab() if (!$loaded);
                   8194: 
1.845     albertel 8195: 	return %libserv;
                   8196:     }
                   8197: 
1.841     albertel 8198:     sub get_servers {
1.852     albertel 8199: 	&load_hosts_tab() if (!$loaded);
                   8200: 
1.841     albertel 8201: 	my ($domain,$type) = @_;
                   8202: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8203: 	                                          : %hostname;
                   8204: 	my %result;
1.842     albertel 8205: 	if (ref($domain) eq 'ARRAY') {
                   8206: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8207: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8208: 		    $result{$host} = $hostname;
                   8209: 		}
                   8210: 	    }
                   8211: 	} else {
                   8212: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8213: 		if ($hostdom{$host} eq $domain) {
                   8214: 		    $result{$host} = $hostname;
                   8215: 		}
1.841     albertel 8216: 	    }
                   8217: 	}
                   8218: 	return %result;
                   8219:     }
1.845     albertel 8220: 
1.844     albertel 8221:     sub host_domain {
1.852     albertel 8222: 	&load_hosts_tab() if (!$loaded);
                   8223: 
1.844     albertel 8224: 	my ($lonid) = @_;
                   8225: 	return $hostdom{$lonid};
                   8226:     }
                   8227: 
1.841     albertel 8228:     sub all_domains {
1.852     albertel 8229: 	&load_hosts_tab() if (!$loaded);
                   8230: 
1.841     albertel 8231: 	my %seen;
                   8232: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8233: 	return @uniq;
                   8234:     }
1.1       albertel 8235: }
                   8236: 
1.847     albertel 8237: { 
                   8238:     my %iphost;
1.856     albertel 8239:     my %name_to_ip;
                   8240:     my %lonid_to_ip;
1.869     albertel 8241: 
1.847     albertel 8242:     sub get_hosts_from_ip {
                   8243: 	my ($ip) = @_;
                   8244: 	my %iphosts = &get_iphost();
                   8245: 	if (ref($iphosts{$ip})) {
                   8246: 	    return @{$iphosts{$ip}};
                   8247: 	}
                   8248: 	return;
1.839     albertel 8249:     }
1.864     albertel 8250:     
                   8251:     sub reset_hosts_ip_info {
                   8252: 	undef(%iphost);
                   8253: 	undef(%name_to_ip);
                   8254: 	undef(%lonid_to_ip);
                   8255:     }
1.856     albertel 8256: 
                   8257:     sub get_host_ip {
                   8258: 	my ($lonid) = @_;
                   8259: 	if (exists($lonid_to_ip{$lonid})) {
                   8260: 	    return $lonid_to_ip{$lonid};
                   8261: 	}
                   8262: 	my $name=&hostname($lonid);
                   8263:    	my $ip = gethostbyname($name);
                   8264: 	return if (!$ip || length($ip) ne 4);
                   8265: 	$ip=inet_ntoa($ip);
                   8266: 	$name_to_ip{$name}   = $ip;
                   8267: 	$lonid_to_ip{$lonid} = $ip;
                   8268: 	return $ip;
                   8269:     }
1.847     albertel 8270:     
                   8271:     sub get_iphost {
1.869     albertel 8272: 	my ($ignore_cache) = @_;
1.894     albertel 8273: 
1.869     albertel 8274: 	if (!$ignore_cache) {
                   8275: 	    if (%iphost) {
                   8276: 		return %iphost;
                   8277: 	    }
                   8278: 	    my ($ip_info,$cached)=
                   8279: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8280: 	    if ($cached) {
                   8281: 		%iphost      = %{$ip_info->[0]};
                   8282: 		%name_to_ip  = %{$ip_info->[1]};
                   8283: 		%lonid_to_ip = %{$ip_info->[2]};
                   8284: 		return %iphost;
                   8285: 	    }
                   8286: 	}
1.894     albertel 8287: 
                   8288: 	# get yesterday's info for fallback
                   8289: 	my %old_name_to_ip;
                   8290: 	my ($ip_info,$cached)=
                   8291: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8292: 	if ($cached) {
                   8293: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8294: 	}
                   8295: 
1.888     albertel 8296: 	my %name_to_host = &all_names();
                   8297: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8298: 	    my $ip;
                   8299: 	    if (!exists($name_to_ip{$name})) {
                   8300: 		$ip = gethostbyname($name);
                   8301: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8302: 		    if (defined($old_name_to_ip{$name})) {
                   8303: 			$ip = $old_name_to_ip{$name};
                   8304: 			&logthis("Can't find $name defaulting to old $ip");
                   8305: 		    } else {
                   8306: 			&logthis("Name $name no IP found");
                   8307: 			next;
                   8308: 		    }
                   8309: 		} else {
                   8310: 		    $ip=inet_ntoa($ip);
1.847     albertel 8311: 		}
                   8312: 		$name_to_ip{$name} = $ip;
                   8313: 	    } else {
                   8314: 		$ip = $name_to_ip{$name};
1.653     albertel 8315: 	    }
1.888     albertel 8316: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8317: 		$lonid_to_ip{$id} = $ip;
                   8318: 	    }
                   8319: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8320: 	}
1.869     albertel 8321: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8322: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8323: 				      48*60*60);
1.869     albertel 8324: 
1.847     albertel 8325: 	return %iphost;
1.598     albertel 8326:     }
                   8327: }
                   8328: 
1.862     albertel 8329: BEGIN {
                   8330: 
                   8331: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8332:     unless ($readit) {
                   8333: {
                   8334:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8335:     %perlvar = (%perlvar,%{$configvars});
                   8336: }
                   8337: 
                   8338: 
1.1       albertel 8339: # ------------------------------------------------------ Read spare server file
                   8340: {
1.448     albertel 8341:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8342: 
                   8343:     while (my $configline=<$config>) {
                   8344:        chomp($configline);
1.284     matthew  8345:        if ($configline) {
1.784     albertel 8346: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8347: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8348: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8349:        }
                   8350:     }
1.448     albertel 8351:     close($config);
1.1       albertel 8352: }
1.11      www      8353: # ------------------------------------------------------------ Read permissions
                   8354: {
1.448     albertel 8355:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8356: 
                   8357:     while (my $configline=<$config>) {
1.448     albertel 8358: 	chomp($configline);
                   8359: 	if ($configline) {
                   8360: 	    my ($role,$perm)=split(/ /,$configline);
                   8361: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8362: 	}
1.11      www      8363:     }
1.448     albertel 8364:     close($config);
1.11      www      8365: }
                   8366: 
                   8367: # -------------------------------------------- Read plain texts for permissions
                   8368: {
1.448     albertel 8369:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8370: 
                   8371:     while (my $configline=<$config>) {
1.448     albertel 8372: 	chomp($configline);
                   8373: 	if ($configline) {
1.742     raeburn  8374: 	    my ($short,@plain)=split(/:/,$configline);
                   8375:             %{$prp{$short}} = ();
                   8376: 	    if (@plain > 0) {
                   8377:                 $prp{$short}{'std'} = $plain[0];
                   8378:                 for (my $i=1; $i<@plain; $i++) {
                   8379:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8380:                 }
                   8381:             }
1.448     albertel 8382: 	}
1.135     www      8383:     }
1.448     albertel 8384:     close($config);
1.135     www      8385: }
                   8386: 
                   8387: # ---------------------------------------------------------- Read package table
                   8388: {
1.448     albertel 8389:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8390: 
                   8391:     while (my $configline=<$config>) {
1.483     albertel 8392: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8393: 	chomp($configline);
                   8394: 	my ($short,$plain)=split(/:/,$configline);
                   8395: 	my ($pack,$name)=split(/\&/,$short);
                   8396: 	if ($plain ne '') {
                   8397: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8398: 	    $packagetab{$short}=$plain; 
                   8399: 	}
1.11      www      8400:     }
1.448     albertel 8401:     close($config);
1.329     matthew  8402: }
                   8403: 
                   8404: # ------------- set up temporary directory
                   8405: {
                   8406:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8407: 
1.11      www      8408: }
                   8409: 
1.794     albertel 8410: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8411: 				'compress_threshold'=> 20_000,
                   8412:  			        });
1.185     www      8413: 
1.281     www      8414: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8415: $dumpcount=0;
1.22      www      8416: 
1.163     harris41 8417: &logtouch();
1.672     albertel 8418: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8419: $readit=1;
1.564     albertel 8420:     {
                   8421: 	use integer;
                   8422: 	my $test=(2**32)+1;
1.568     albertel 8423: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8424: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8425:     }
1.195     www      8426: }
1.1       albertel 8427: }
1.179     www      8428: 
1.1       albertel 8429: 1;
1.191     harris41 8430: __END__
                   8431: 
1.243     albertel 8432: =pod
                   8433: 
1.191     harris41 8434: =head1 NAME
                   8435: 
1.243     albertel 8436: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8437: 
                   8438: =head1 SYNOPSIS
                   8439: 
1.243     albertel 8440: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8441: 
                   8442:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8443: 
1.243     albertel 8444: Common parameters:
                   8445: 
                   8446: =over 4
                   8447: 
                   8448: =item *
                   8449: 
                   8450: $uname : an internal username (if $cname expecting a course Id specifically)
                   8451: 
                   8452: =item *
                   8453: 
                   8454: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8455: 
                   8456: =item *
                   8457: 
                   8458: $symb : a resource instance identifier
                   8459: 
                   8460: =item *
                   8461: 
                   8462: $namespace : the name of a .db file that contains the data needed or
                   8463: being set.
                   8464: 
                   8465: =back
                   8466: 
1.394     bowersj2 8467: =head1 OVERVIEW
1.191     harris41 8468: 
1.394     bowersj2 8469: lonnet provides subroutines which interact with the
                   8470: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8471: about classes, users, and resources.
1.243     albertel 8472: 
                   8473: For many of these objects you can also use this to store data about
                   8474: them or modify them in various ways.
1.191     harris41 8475: 
1.394     bowersj2 8476: =head2 Symbs
1.191     harris41 8477: 
1.394     bowersj2 8478: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8479: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8480: map, the resource number of the resource in the map, and the URL of
                   8481: the resource itself. The latter is somewhat redundant, but might help
                   8482: if maps change.
                   8483: 
                   8484: An example is
                   8485: 
                   8486:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8487: 
                   8488: The respective map entry is
                   8489: 
                   8490:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8491:   title="Problem 2">
                   8492:  </resource>
                   8493: 
                   8494: Symbs are used by the random number generator, as well as to store and
                   8495: restore data specific to a certain instance of for example a problem.
                   8496: 
                   8497: =head2 Storing And Retrieving Data
                   8498: 
                   8499: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8500: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8501: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8502: is is the non-critical message twin of cstore. These functions are for
                   8503: handlers to store a perl hash to a user's permanent data space in an
                   8504: easy manner, and to retrieve it again on another call. It is expected
                   8505: that a handler would use this once at the beginning to retrieve data,
                   8506: and then again once at the end to send only the new data back.
                   8507: 
                   8508: The data is stored in the user's data directory on the user's
                   8509: homeserver under the ID of the course.
                   8510: 
                   8511: The hash that is returned by restore will have all of the previous
                   8512: value for all of the elements of the hash.
                   8513: 
                   8514: Example:
                   8515: 
                   8516:  #creating a hash
                   8517:  my %hash;
                   8518:  $hash{'foo'}='bar';
                   8519: 
                   8520:  #storing it
                   8521:  &Apache::lonnet::cstore(\%hash);
                   8522: 
                   8523:  #changing a value
                   8524:  $hash{'foo'}='notbar';
                   8525: 
                   8526:  #adding a new value
                   8527:  $hash{'bar'}='foo';
                   8528:  &Apache::lonnet::cstore(\%hash);
                   8529: 
                   8530:  #retrieving the hash
                   8531:  my %history=&Apache::lonnet::restore();
                   8532: 
                   8533:  #print the hash
                   8534:  foreach my $key (sort(keys(%history))) {
                   8535:    print("\%history{$key} = $history{$key}");
                   8536:  }
                   8537: 
                   8538: Will print out:
1.191     harris41 8539: 
1.394     bowersj2 8540:  %history{1:foo} = bar
                   8541:  %history{1:keys} = foo:timestamp
                   8542:  %history{1:timestamp} = 990455579
                   8543:  %history{2:bar} = foo
                   8544:  %history{2:foo} = notbar
                   8545:  %history{2:keys} = foo:bar:timestamp
                   8546:  %history{2:timestamp} = 990455580
                   8547:  %history{bar} = foo
                   8548:  %history{foo} = notbar
                   8549:  %history{timestamp} = 990455580
                   8550:  %history{version} = 2
                   8551: 
                   8552: Note that the special hash entries C<keys>, C<version> and
                   8553: C<timestamp> were added to the hash. C<version> will be equal to the
                   8554: total number of versions of the data that have been stored. The
                   8555: C<timestamp> attribute will be the UNIX time the hash was
                   8556: stored. C<keys> is available in every historical section to list which
                   8557: keys were added or changed at a specific historical revision of a
                   8558: hash.
                   8559: 
                   8560: B<Warning>: do not store the hash that restore returns directly. This
                   8561: will cause a mess since it will restore the historical keys as if the
                   8562: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8563: 
1.394     bowersj2 8564: Calling convention:
1.191     harris41 8565: 
1.394     bowersj2 8566:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8567:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8568: 
1.394     bowersj2 8569: For more detailed information, see lonnet specific documentation.
1.191     harris41 8570: 
1.394     bowersj2 8571: =head1 RETURN MESSAGES
1.191     harris41 8572: 
1.394     bowersj2 8573: =over 4
1.191     harris41 8574: 
1.394     bowersj2 8575: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8576: 
1.394     bowersj2 8577: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8578: when the connection is brought back up
1.191     harris41 8579: 
1.394     bowersj2 8580: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8581: for later delivery
1.191     harris41 8582: 
1.394     bowersj2 8583: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8584: 
1.394     bowersj2 8585: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8586: that was requested
1.191     harris41 8587: 
1.243     albertel 8588: =back
1.191     harris41 8589: 
1.243     albertel 8590: =head1 PUBLIC SUBROUTINES
1.191     harris41 8591: 
1.243     albertel 8592: =head2 Session Environment Functions
1.191     harris41 8593: 
1.243     albertel 8594: =over 4
1.191     harris41 8595: 
1.394     bowersj2 8596: =item * 
                   8597: X<appenv()>
                   8598: B<appenv(%hash)>: the value of %hash is written to
                   8599: the user envirnoment file, and will be restored for each access this
1.620     albertel 8600: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8601: process
1.191     harris41 8602: 
                   8603: =item *
1.394     bowersj2 8604: X<delenv()>
                   8605: B<delenv($regexp)>: removes all items from the session
                   8606: environment file that matches the regular expression in $regexp. The
1.620     albertel 8607: values are also delted from the current processes %env.
1.191     harris41 8608: 
1.795     albertel 8609: =item * get_env_multiple($name) 
                   8610: 
                   8611: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8612: values may be defined and end up as an array ref.
                   8613: 
                   8614: returns an array of values
                   8615: 
1.243     albertel 8616: =back
                   8617: 
                   8618: =head2 User Information
1.191     harris41 8619: 
1.243     albertel 8620: =over 4
1.191     harris41 8621: 
                   8622: =item *
1.394     bowersj2 8623: X<queryauthenticate()>
                   8624: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8625: authentication scheme
                   8626: 
                   8627: =item *
1.394     bowersj2 8628: X<authenticate()>
                   8629: B<authenticate($uname,$upass,$udom)>: try to
                   8630: authenticate user from domain's lib servers (first use the current
                   8631: one). C<$upass> should be the users password.
1.191     harris41 8632: 
                   8633: =item *
1.394     bowersj2 8634: X<homeserver()>
                   8635: B<homeserver($uname,$udom)>: find the server which has
                   8636: the user's directory and files (there must be only one), this caches
                   8637: the answer, and also caches if there is a borken connection.
1.191     harris41 8638: 
                   8639: =item *
1.394     bowersj2 8640: X<idget()>
                   8641: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8642: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8643: username, and only 1 username per ID in a specific domain) (returns
                   8644: hash: id=>name,id=>name)
1.191     harris41 8645: 
                   8646: =item *
1.394     bowersj2 8647: X<idrget()>
                   8648: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8649: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8650: 
                   8651: =item *
1.394     bowersj2 8652: X<idput()>
                   8653: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8654: 
                   8655: =item *
1.394     bowersj2 8656: X<rolesinit()>
                   8657: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8658: 
                   8659: =item *
1.551     albertel 8660: X<getsection()>
                   8661: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8662: course $cname, return section name/number or '' for "not in course"
                   8663: and '-1' for "no section"
                   8664: 
                   8665: =item *
1.394     bowersj2 8666: X<userenvironment()>
                   8667: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8668: passed in @what from the requested user's environment, returns a hash
                   8669: 
1.858     raeburn  8670: =item * 
                   8671: X<userlog_query()>
1.859     albertel 8672: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8673: activity.log file. %filters defines filters applied when parsing the
                   8674: log file. These can be start or end timestamps, or the type of action
                   8675: - log to look for Login or Logout events, check for Checkin or
                   8676: Checkout, role for role selection. The response is in the form
                   8677: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8678: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8679: 
1.243     albertel 8680: =back
                   8681: 
                   8682: =head2 User Roles
                   8683: 
                   8684: =over 4
                   8685: 
                   8686: =item *
                   8687: 
1.810     raeburn  8688: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8689:  F: full access
                   8690:  U,I,K: authentication modes (cxx only)
                   8691:  '': forbidden
                   8692:  1: user needs to choose course
                   8693:  2: browse allowed
1.766     albertel 8694:  A: passphrase authentication needed
1.243     albertel 8695: 
                   8696: =item *
                   8697: 
                   8698: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8699: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8700: and course level
                   8701: 
                   8702: =item *
                   8703: 
                   8704: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8705: explanation of a user role term
                   8706: 
1.832     raeburn  8707: =item *
                   8708: 
1.858     raeburn  8709: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8710: All arguments are optional. Returns a hash of a roles, either for
                   8711: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8712: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8713: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8714: and value is set to colon-separated start and end times for the role.
                   8715: If no username and domain are specified, will default to current
                   8716: user/domain. Types, roles, and roledoms are references to arrays,
                   8717: of role statuses (active, future or previous), roles 
                   8718: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8719: to restrict the list of roles reported. If no array ref is 
                   8720: provided for types, will default to return only active roles.
1.834     albertel 8721: 
1.243     albertel 8722: =back
                   8723: 
                   8724: =head2 User Modification
                   8725: 
                   8726: =over 4
                   8727: 
                   8728: =item *
                   8729: 
                   8730: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8731: user for the level given by URL.  Optional start and end dates (leave empty
                   8732: string or zero for "no date")
1.191     harris41 8733: 
                   8734: =item *
                   8735: 
1.243     albertel 8736: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8737: change a users, password, possible return values are: ok,
                   8738: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8739: refused
1.191     harris41 8740: 
                   8741: =item *
                   8742: 
1.243     albertel 8743: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8744: 
                   8745: =item *
                   8746: 
1.243     albertel 8747: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8748: modify user
1.191     harris41 8749: 
                   8750: =item *
                   8751: 
1.286     matthew  8752: modifystudent
                   8753: 
                   8754: modify a students enrollment and identification information.
                   8755: The course id is resolved based on the current users environment.  
                   8756: This means the envoking user must be a course coordinator or otherwise
                   8757: associated with a course.
                   8758: 
1.297     matthew  8759: This call is essentially a wrapper for lonnet::modifyuser and
                   8760: lonnet::modify_student_enrollment
1.286     matthew  8761: 
                   8762: Inputs: 
                   8763: 
                   8764: =over 4
                   8765: 
                   8766: =item B<$udom> Students loncapa domain
                   8767: 
                   8768: =item B<$uname> Students loncapa login name
                   8769: 
                   8770: =item B<$uid> Students id/student number
                   8771: 
                   8772: =item B<$umode> Students authentication mode
                   8773: 
                   8774: =item B<$upass> Students password
                   8775: 
                   8776: =item B<$first> Students first name
                   8777: 
                   8778: =item B<$middle> Students middle name
                   8779: 
                   8780: =item B<$last> Students last name
                   8781: 
                   8782: =item B<$gene> Students generation
                   8783: 
                   8784: =item B<$usec> Students section in course
                   8785: 
                   8786: =item B<$end> Unix time of the roles expiration
                   8787: 
                   8788: =item B<$start> Unix time of the roles start date
                   8789: 
                   8790: =item B<$forceid> If defined, allow $uid to be changed
                   8791: 
                   8792: =item B<$desiredhome> server to use as home server for student
                   8793: 
                   8794: =back
1.297     matthew  8795: 
                   8796: =item *
                   8797: 
                   8798: modify_student_enrollment
                   8799: 
                   8800: Change a students enrollment status in a class.  The environment variable
                   8801: 'role.request.course' must be defined for this function to proceed.
                   8802: 
                   8803: Inputs:
                   8804: 
                   8805: =over 4
                   8806: 
                   8807: =item $udom, students domain
                   8808: 
                   8809: =item $uname, students name
                   8810: 
                   8811: =item $uid, students user id
                   8812: 
                   8813: =item $first, students first name
                   8814: 
                   8815: =item $middle
                   8816: 
                   8817: =item $last
                   8818: 
                   8819: =item $gene
                   8820: 
                   8821: =item $usec
                   8822: 
                   8823: =item $end
                   8824: 
                   8825: =item $start
                   8826: 
                   8827: =back
                   8828: 
1.191     harris41 8829: 
                   8830: =item *
                   8831: 
1.243     albertel 8832: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8833: custom role; give a custom role to a user for the level given by URL.  Specify
                   8834: name and domain of role author, and role name
1.191     harris41 8835: 
                   8836: =item *
                   8837: 
1.243     albertel 8838: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8839: 
                   8840: =item *
                   8841: 
1.243     albertel 8842: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8843: 
                   8844: =back
                   8845: 
                   8846: =head2 Course Infomation
                   8847: 
                   8848: =over 4
1.191     harris41 8849: 
                   8850: =item *
                   8851: 
1.631     albertel 8852: coursedescription($courseid) : returns a hash of information about the
                   8853: specified course id, including all environment settings for the
                   8854: course, the description of the course will be in the hash under the
                   8855: key 'description'
1.191     harris41 8856: 
                   8857: =item *
                   8858: 
1.624     albertel 8859: resdata($name,$domain,$type,@which) : request for current parameter
                   8860: setting for a specific $type, where $type is either 'course' or 'user',
                   8861: @what should be a list of parameters to ask about. This routine caches
                   8862: answers for 5 minutes.
1.243     albertel 8863: 
1.877     foxr     8864: =item *
                   8865: 
                   8866: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8867: data base, returning a hash that is keyed by the resource name and has
                   8868: values that are the resource value.  I believe that the timestamps and
                   8869: versions are also returned.
                   8870: 
                   8871: 
1.243     albertel 8872: =back
                   8873: 
                   8874: =head2 Course Modification
                   8875: 
                   8876: =over 4
1.191     harris41 8877: 
                   8878: =item *
                   8879: 
1.243     albertel 8880: writecoursepref($courseid,%prefs) : write preferences (environment
                   8881: database) for a course
1.191     harris41 8882: 
                   8883: =item *
                   8884: 
1.243     albertel 8885: createcourse($udom,$description,$url) : make/modify course
                   8886: 
                   8887: =back
                   8888: 
                   8889: =head2 Resource Subroutines
                   8890: 
                   8891: =over 4
1.191     harris41 8892: 
                   8893: =item *
                   8894: 
1.243     albertel 8895: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8896: 
                   8897: =item *
                   8898: 
1.243     albertel 8899: repcopy($filename) : subscribes to the requested file, and attempts to
                   8900: replicate from the owning library server, Might return
1.607     raeburn  8901: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8902: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8903: resource. Expects the local filesystem pathname
                   8904: (/home/httpd/html/res/....)
                   8905: 
                   8906: =back
                   8907: 
                   8908: =head2 Resource Information
                   8909: 
                   8910: =over 4
1.191     harris41 8911: 
                   8912: =item *
                   8913: 
1.243     albertel 8914: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8915: a vairety of different possible values, $varname should be a request
                   8916: string, and the other parameters can be used to specify who and what
                   8917: one is asking about.
                   8918: 
                   8919: Possible values for $varname are environment.lastname (or other item
                   8920: from the envirnment hash), user.name (or someother aspect about the
                   8921: user), resource.0.maxtries (or some other part and parameter of a
                   8922: resource)
1.204     albertel 8923: 
                   8924: =item *
                   8925: 
1.243     albertel 8926: directcondval($number) : get current value of a condition; reads from a state
                   8927: string
1.204     albertel 8928: 
                   8929: =item *
                   8930: 
1.243     albertel 8931: condval($condidx) : value of condition index based on state
1.204     albertel 8932: 
                   8933: =item *
                   8934: 
1.243     albertel 8935: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8936: resource's metadata, $what should be either a specific key, or either
                   8937: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8938: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8939: 
                   8940: this function automatically caches all requests
1.191     harris41 8941: 
                   8942: =item *
                   8943: 
1.243     albertel 8944: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8945: network of library servers; returns file handle of where SQL and regex results
                   8946: will be stored for query
1.191     harris41 8947: 
                   8948: =item *
                   8949: 
1.243     albertel 8950: symbread($filename) : return symbolic list entry (filename argument optional);
                   8951: returns the data handle
1.191     harris41 8952: 
                   8953: =item *
                   8954: 
1.243     albertel 8955: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8956: a possible symb for the URL in $thisfn, and if is an encryypted
                   8957: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8958: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8959: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8960: 
1.191     harris41 8961: 
                   8962: =item *
                   8963: 
1.243     albertel 8964: symbclean($symb) : removes versions numbers from a symb, returns the
                   8965: cleaned symb
1.191     harris41 8966: 
                   8967: =item *
                   8968: 
1.243     albertel 8969: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8970: course map, user must be in a course for it to work.
1.191     harris41 8971: 
                   8972: =item *
                   8973: 
1.243     albertel 8974: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8975: 
                   8976: =item *
                   8977: 
1.243     albertel 8978: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8979: a random seed, all arguments are optional, if they aren't sent it uses the
                   8980: environment to derive them. Note: if symb isn't sent and it can't get one
                   8981: from &symbread it will use the current time as its return value
1.191     harris41 8982: 
                   8983: =item *
                   8984: 
1.243     albertel 8985: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8986: unfakeable, receipt
1.191     harris41 8987: 
                   8988: =item *
                   8989: 
1.620     albertel 8990: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8991: 
                   8992: =item *
                   8993: 
1.243     albertel 8994: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8995: 
                   8996: =item *
                   8997: 
1.243     albertel 8998: 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 8999: 
                   9000: =item *
                   9001: 
1.243     albertel 9002: 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 9003: 
                   9004: =item *
                   9005: 
1.243     albertel 9006: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9007: 
                   9008: =item *
                   9009: 
1.243     albertel 9010: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9011: forcing spreadsheet to reevaluate the resource scores next time.
                   9012: 
                   9013: =back
                   9014: 
                   9015: =head2 Storing/Retreiving Data
                   9016: 
                   9017: =over 4
1.191     harris41 9018: 
                   9019: =item *
                   9020: 
1.243     albertel 9021: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9022: for this url; hashref needs to be given and should be a \%hashname; the
                   9023: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9024: be derived from the env
1.191     harris41 9025: 
                   9026: =item *
                   9027: 
1.243     albertel 9028: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9029: uses critical subroutine
1.191     harris41 9030: 
                   9031: =item *
                   9032: 
1.243     albertel 9033: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9034: all args are optional
1.191     harris41 9035: 
                   9036: =item *
                   9037: 
1.717     albertel 9038: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9039: dumps the complete (or key matching regexp) namespace into a hash
                   9040: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9041: normally &store()ed into
                   9042: 
                   9043: $range should be either an integer '100' (give me the first 100
                   9044:                                            matching records)
                   9045:               or be  two integers sperated by a - with no spaces
                   9046:                  '30-50' (give me the 30th through the 50th matching
                   9047:                           records)
                   9048: 
                   9049: 
                   9050: =item *
                   9051: 
                   9052: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9053: replaces a &store() version of data with a replacement set of data
                   9054: for a particular resource in a namespace passed in the $storehash hash 
                   9055: reference
                   9056: 
                   9057: =item *
                   9058: 
1.243     albertel 9059: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9060: works very similar to store/cstore, but all data is stored in a
                   9061: temporary location and can be reset using tmpreset, $storehash should
                   9062: be a hash reference, returns nothing on success
1.191     harris41 9063: 
                   9064: =item *
                   9065: 
1.243     albertel 9066: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9067: similar to restore, but all data is stored in a temporary location and
                   9068: can be reset using tmpreset. Returns a hash of values on success,
                   9069: error string otherwise.
1.191     harris41 9070: 
                   9071: =item *
                   9072: 
1.243     albertel 9073: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9074: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9075: 
                   9076: =item *
                   9077: 
1.243     albertel 9078: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9079: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9080: 
                   9081: =item *
                   9082: 
1.243     albertel 9083: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9084: namesp ($udom and $uname are optional)
1.191     harris41 9085: 
                   9086: =item *
                   9087: 
1.702     albertel 9088: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9089: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9090: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9091: 
1.702     albertel 9092: $range should be either an integer '100' (give me the first 100
                   9093:                                            matching records)
                   9094:               or be  two integers sperated by a - with no spaces
                   9095:                  '30-50' (give me the 30th through the 50th matching
                   9096:                           records)
1.449     matthew  9097: =item *
                   9098: 
                   9099: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9100: $store can be a scalar, an array reference, or if the amount to be 
                   9101: incremented is > 1, a hash reference.
                   9102: 
                   9103: ($udom and $uname are optional)
1.191     harris41 9104: 
                   9105: =item *
                   9106: 
1.243     albertel 9107: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9108: ($udom and $uname are optional)
1.191     harris41 9109: 
                   9110: =item *
                   9111: 
1.243     albertel 9112: cput($namespace,$storehash,$udom,$uname) : critical put
                   9113: ($udom and $uname are optional)
1.191     harris41 9114: 
                   9115: =item *
                   9116: 
1.748     albertel 9117: newput($namespace,$storehash,$udom,$uname) :
                   9118: 
                   9119: Attempts to store the items in the $storehash, but only if they don't
                   9120: currently exist, if this succeeds you can be certain that you have 
                   9121: successfully created a new key value pair in the $namespace db.
                   9122: 
                   9123: 
                   9124: Args:
                   9125:  $namespace: name of database to store values to
                   9126:  $storehash: hashref to store to the db
                   9127:  $udom: (optional) domain of user containing the db
                   9128:  $uname: (optional) name of user caontaining the db
                   9129: 
                   9130: Returns:
                   9131:  'ok' -> succeeded in storing all keys of $storehash
                   9132:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9133:                         least <key> already existed in the db (other
                   9134:                         requested keys may also already exist)
                   9135:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9136:  'con_lost' -> unable to contact request server
                   9137:  'refused' -> action was not allowed by remote machine
                   9138: 
                   9139: 
                   9140: =item *
                   9141: 
1.243     albertel 9142: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9143: reference filled in from namesp (encrypts the return communication)
                   9144: ($udom and $uname are optional)
1.191     harris41 9145: 
                   9146: =item *
                   9147: 
1.243     albertel 9148: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9149: critical subroutine
                   9150: 
1.806     raeburn  9151: =item *
                   9152: 
1.860     raeburn  9153: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9154: array reference filled in from namespace found in domain level on either
                   9155: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9156: 
                   9157: =item *
                   9158: 
1.860     raeburn  9159: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9160: domain level either on specified domain server ($uhome) or primary domain 
                   9161: server ($udom and $uhome are optional)
1.806     raeburn  9162: 
1.243     albertel 9163: =back
                   9164: 
                   9165: =head2 Network Status Functions
                   9166: 
                   9167: =over 4
1.191     harris41 9168: 
                   9169: =item *
                   9170: 
                   9171: dirlist($uri) : return directory list based on URI
                   9172: 
                   9173: =item *
                   9174: 
1.243     albertel 9175: spareserver() : find server with least workload from spare.tab
                   9176: 
                   9177: =back
                   9178: 
                   9179: =head2 Apache Request
                   9180: 
                   9181: =over 4
1.191     harris41 9182: 
                   9183: =item *
                   9184: 
1.243     albertel 9185: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9186: localhost, posts hash
                   9187: 
                   9188: =back
                   9189: 
                   9190: =head2 Data to String to Data
                   9191: 
                   9192: =over 4
1.191     harris41 9193: 
                   9194: =item *
                   9195: 
1.243     albertel 9196: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9197: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9198: 
                   9199: =item *
                   9200: 
1.243     albertel 9201: hashref2str($hashref) : convert a hashref into a string complete with
                   9202: escaping and '=' and '&' separators, supports elements that are
                   9203: arrayrefs and hashrefs
1.191     harris41 9204: 
                   9205: =item *
                   9206: 
1.243     albertel 9207: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9208: with escaping and '&' separators, supports elements that are arrayrefs
                   9209: and hashrefs
1.191     harris41 9210: 
                   9211: =item *
                   9212: 
1.243     albertel 9213: str2hash($string) : convert string to hash using unescaping and
                   9214: splitting on '=' and '&', supports elements that are arrayrefs and
                   9215: hashrefs
1.191     harris41 9216: 
                   9217: =item *
                   9218: 
1.243     albertel 9219: str2array($string) : convert string to hash using unescaping and
                   9220: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9221: 
                   9222: =back
                   9223: 
                   9224: =head2 Logging Routines
                   9225: 
                   9226: =over 4
                   9227: 
                   9228: These routines allow one to make log messages in the lonnet.log and
                   9229: lonnet.perm logfiles.
1.191     harris41 9230: 
                   9231: =item *
                   9232: 
1.243     albertel 9233: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9234: 
                   9235: =item *
                   9236: 
1.243     albertel 9237: logthis() : append message to the normal lonnet.log file, it gets
                   9238: preiodically rolled over and deleted.
1.191     harris41 9239: 
                   9240: =item *
                   9241: 
1.243     albertel 9242: logperm() : append a permanent message to lonnet.perm.log, this log
                   9243: file never gets deleted by any automated portion of the system, only
                   9244: messages of critical importance should go in here.
                   9245: 
                   9246: =back
                   9247: 
                   9248: =head2 General File Helper Routines
                   9249: 
                   9250: =over 4
1.191     harris41 9251: 
                   9252: =item *
                   9253: 
1.481     raeburn  9254: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9255: (a) files in /uploaded
                   9256:   (i) If a local copy of the file exists - 
                   9257:       compares modification date of local copy with last-modified date for 
                   9258:       definitive version stored on home server for course. If local copy is 
                   9259:       stale, requests a new version from the home server and stores it. 
                   9260:       If the original has been removed from the home server, then local copy 
                   9261:       is unlinked.
                   9262:   (ii) If local copy does not exist -
                   9263:       requests the file from the home server and stores it. 
                   9264:   
                   9265:   If $caller is 'uploadrep':  
                   9266:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9267:     for request for files originally uploaded via DOCS. 
                   9268:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9269:   
                   9270:   Otherwise:
                   9271:      This indicates a call from the content generation phase of the request.
                   9272:      -  returns the entire contents of the file or -1.
                   9273:      
                   9274: (b) files in /res
                   9275:    - returns the entire contents of a file or -1; 
                   9276:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9277: 
1.712     albertel 9278: 
                   9279: =item *
                   9280: 
                   9281: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9282:                   reference
                   9283: 
                   9284: returns either a stat() list of data about the file or an empty list
                   9285: if the file doesn't exist or couldn't find out about it (connection
                   9286: problems or user unknown)
                   9287: 
1.191     harris41 9288: =item *
                   9289: 
1.243     albertel 9290: filelocation($dir,$file) : returns file system location of a file
                   9291: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9292: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9293: and a file of ../bob will become /a/bob)
1.191     harris41 9294: 
                   9295: =item *
                   9296: 
                   9297: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9298: filelocation except for hrefs
                   9299: 
                   9300: =item *
                   9301: 
                   9302: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9303: 
1.243     albertel 9304: =back
                   9305: 
1.608     albertel 9306: =head2 Usererfile file routines (/uploaded*)
                   9307: 
                   9308: =over 4
                   9309: 
                   9310: =item *
                   9311: 
                   9312: userfileupload(): main rotine for putting a file in a user or course's
                   9313:                   filespace, arguments are,
                   9314: 
1.620     albertel 9315:  formname - required - this is the name of the element in $env where the
1.608     albertel 9316:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9317:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9318:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9319:  coursedoc - if true, store the file in the course of the active role
                   9320:              of the current user
                   9321:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9322:          if undefined, it will be placed in "unknown"
                   9323: 
                   9324:  (This routine calls clean_filename() to remove any dangerous
                   9325:  characters from the filename, and then calls finuserfileupload() to
                   9326:  complete the transaction)
                   9327: 
                   9328:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9329:  and /adm/notfound.html if unsuccessful
                   9330: 
                   9331: =item *
                   9332: 
                   9333: clean_filename(): routine for cleaing a filename up for storage in
                   9334:                  userfile space, argument is:
                   9335: 
                   9336:  filename - proposed filename
                   9337: 
                   9338: returns: the new clean filename
                   9339: 
                   9340: =item *
                   9341: 
                   9342: finishuserfileupload(): routine that creaes and sends the file to
                   9343: userspace, probably shouldn't be called directly
                   9344: 
                   9345:   docuname: username or courseid of destination for the file
                   9346:   docudom: domain of user/course of destination for the file
                   9347:   formname: same as for userfileupload()
                   9348:   fname: filename (inculding subdirectories) for the file
                   9349: 
                   9350:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9351:  and /adm/notfound.html if unsuccessful
                   9352: 
                   9353: =item *
                   9354: 
                   9355: renameuserfile(): renames an existing userfile to a new name
                   9356: 
                   9357:   Args:
                   9358:    docuname: username or courseid of destination for the file
                   9359:    docudom: domain of user/course of destination for the file
                   9360:    old: current file name (including any subdirs under userfiles)
                   9361:    new: desired file name (including any subdirs under userfiles)
                   9362: 
                   9363: =item *
                   9364: 
                   9365: mkdiruserfile(): creates a directory is a userfiles dir
                   9366: 
                   9367:   Args:
                   9368:    docuname: username or courseid of destination for the file
                   9369:    docudom: domain of user/course of destination for the file
                   9370:    dir: dir to create (including any subdirs under userfiles)
                   9371: 
                   9372: =item *
                   9373: 
                   9374: removeuserfile(): removes a file that exists in userfiles
                   9375: 
                   9376:   Args:
                   9377:    docuname: username or courseid of destination for the file
                   9378:    docudom: domain of user/course of destination for the file
                   9379:    fname: filname to delete (including any subdirs under userfiles)
                   9380: 
                   9381: =item *
                   9382: 
                   9383: removeuploadedurl(): convience function for removeuserfile()
                   9384: 
                   9385:   Args:
                   9386:    url:  a full /uploaded/... url to delete
                   9387: 
1.747     albertel 9388: =item * 
                   9389: 
                   9390: get_portfile_permissions():
                   9391:   Args:
                   9392:     domain: domain of user or course contain the portfolio files
                   9393:     user: name of user or num of course contain the portfolio files
                   9394:   Returns:
                   9395:     hashref of a dump of the proper file_permissions.db
                   9396:    
                   9397: 
                   9398: =item * 
                   9399: 
                   9400: get_access_controls():
                   9401: 
                   9402: Args:
                   9403:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9404:   group: (optional) the group you want the files associated with
                   9405:   file: (optional) the file you want access info on
                   9406: 
                   9407: Returns:
1.749     raeburn  9408:     a hash (keys are file names) of hashes containing
                   9409:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9410:         values are XML containing access control settings (see below) 
1.747     albertel 9411: 
                   9412: Internal notes:
                   9413: 
1.749     raeburn  9414:  access controls are stored in file_permissions.db as key=value pairs.
                   9415:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9416:         where scope -> public,guest,course,group,domains or users.
                   9417:               end -> UNIX time for end of access (0 -> no end date)
                   9418:               start -> UNIX time for start of access
                   9419: 
                   9420:     value -> XML description of access control
                   9421:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9422:             <start></start>
                   9423:             <end></end>
                   9424: 
                   9425:             <password></password>  for scope type = guest
                   9426: 
                   9427:             <domain></domain>     for scope type = course or group
                   9428:             <number></number>
                   9429:             <roles id="">
                   9430:              <role></role>
                   9431:              <access></access>
                   9432:              <section></section>
                   9433:              <group></group>
                   9434:             </roles>
                   9435: 
                   9436:             <dom></dom>         for scope type = domains
                   9437: 
                   9438:             <users>             for scope type = users
                   9439:              <user>
                   9440:               <uname></uname>
                   9441:               <udom></udom>
                   9442:              </user>
                   9443:             </users>
                   9444:            </scope> 
                   9445:               
                   9446:  Access data is also aggregated for each file in an additional key=value pair:
                   9447:  key -> path to file/file_name\0accesscontrol 
                   9448:  value -> reference to hash
                   9449:           hash contains key = value pairs
                   9450:           where key = uniqueID:scope_end_start
                   9451:                 value = UNIX time record was last updated
                   9452: 
                   9453:           Used to improve speed of look-ups of access controls for each file.  
                   9454:  
                   9455:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9456: 
                   9457: modify_access_controls():
                   9458: 
                   9459: Modifies access controls for a portfolio file
                   9460: Args
                   9461: 1. file name
                   9462: 2. reference to hash of required changes,
                   9463: 3. domain
                   9464: 4. username
                   9465:   where domain,username are the domain of the portfolio owner 
                   9466:   (either a user or a course) 
                   9467: 
                   9468: Returns:
                   9469: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9470: 2. result of deletions ('ok' or 'error', with error message).
                   9471: 3. reference to hash of any new or updated access controls.
                   9472: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9473:    key = integer (inbound ID)
                   9474:    value = uniqueID  
1.747     albertel 9475: 
1.608     albertel 9476: =back
                   9477: 
1.243     albertel 9478: =head2 HTTP Helper Routines
                   9479: 
                   9480: =over 4
                   9481: 
1.191     harris41 9482: =item *
                   9483: 
                   9484: escape() : unpack non-word characters into CGI-compatible hex codes
                   9485: 
                   9486: =item *
                   9487: 
                   9488: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9489: 
1.243     albertel 9490: =back
                   9491: 
                   9492: =head1 PRIVATE SUBROUTINES
                   9493: 
                   9494: =head2 Underlying communication routines (Shouldn't call)
                   9495: 
                   9496: =over 4
                   9497: 
                   9498: =item *
                   9499: 
                   9500: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9501: 
                   9502: =item *
                   9503: 
                   9504: reply() : uses subreply to send a message to remote machine, logs all failures
                   9505: 
                   9506: =item *
                   9507: 
                   9508: critical() : passes a critical message to another server; if cannot
                   9509: get through then place message in connection buffer directory and
                   9510: returns con_delayed, if incapable of saving message, returns
                   9511: con_failed
                   9512: 
                   9513: =item *
                   9514: 
                   9515: reconlonc() : tries to reconnect lonc client processes.
                   9516: 
                   9517: =back
                   9518: 
                   9519: =head2 Resource Access Logging
                   9520: 
                   9521: =over 4
                   9522: 
                   9523: =item *
                   9524: 
                   9525: flushcourselogs() : flush (save) buffer logs and access logs
                   9526: 
                   9527: =item *
                   9528: 
                   9529: courselog($what) : save message for course in hash
                   9530: 
                   9531: =item *
                   9532: 
                   9533: courseacclog($what) : save message for course using &courselog().  Perform
                   9534: special processing for specific resource types (problems, exams, quizzes, etc).
                   9535: 
1.191     harris41 9536: =item *
                   9537: 
                   9538: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9539: as a PerlChildExitHandler
1.243     albertel 9540: 
                   9541: =back
                   9542: 
                   9543: =head2 Other
                   9544: 
                   9545: =over 4
                   9546: 
                   9547: =item *
                   9548: 
                   9549: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9550: 
                   9551: =back
                   9552: 
                   9553: =cut
1.877     foxr     9554: 

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