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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.910.2.3! albertel    4: # $Id: lonnet.pm,v 1.910.2.2 2007/09/29 04:06:34 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.910.2.3! 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.910.2.3! 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.910.2.3! 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.910.2.3! 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.910.2.3! 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.910.2.2  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=
                    938:                 &reply("querysend:".&escape($query).':'.&escape($dom).':'.
                    939:                        &escape($srch->{'srchby'}).'%%'.
                    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.900     albertel  956:                 my @matches = split(/&/,$reply);
1.899     raeburn   957:                 foreach my $match (@matches) {
                    958:                     my @items = split(/:/,$match);
                    959:                     my ($uname,$udom,%userhash);
                    960:                     foreach my $entry (@items) {
                    961:                         my ($key,$value) = split(/=/,$entry);
                    962:                         $key = &unescape($key);
                    963:                         $value = &unescape($value);
                    964:                         $userhash{$key} = $value;
                    965:                         if ($key eq 'username') {
                    966:                             $uname = $value;
                    967:                         } elsif ($key eq 'domain') {
                    968:                             $udom = $value;
                    969:                         } 
                    970:                     }
                    971:                     $results{$uname.':'.$udom} = \%userhash;
                    972:                 }
                    973:             }
                    974:         }
                    975:     }
                    976:     return %results;
                    977: }
                    978: 
1.344     www       979: # --------------------------------------------------- Assign a key to a student
                    980: 
                    981: sub assign_access_key {
1.364     www       982: #
                    983: # a valid key looks like uname:udom#comments
                    984: # comments are being appended
                    985: #
1.498     www       986:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    987:     $kdom=
1.620     albertel  988:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       989:     $knum=
1.620     albertel  990:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       991:     $cdom=
1.620     albertel  992:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       993:     $cnum=
1.620     albertel  994:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    995:     $udom=$env{'user.name'} unless (defined($udom));
                    996:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       997:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       998:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  999:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1000:                                                   # assigned to this person
                   1001:                                                   # - this should not happen,
1.345     www      1002:                                                   # unless something went wrong
                   1003:                                                   # the first time around
                   1004: # ready to assign
1.364     www      1005:         $logentry=$1.'; '.$logentry;
1.496     www      1006:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1007:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1008: # key now belongs to user
1.346     www      1009: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1010:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                   1011:                 &appenv('environment.'.$envkey => $ckey);
                   1012:                 return 'ok';
                   1013:             } else {
                   1014:                 return 
                   1015:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1016: 	    }
                   1017:         } else {
                   1018:             return 'error: Could not assign key, try again later.';
                   1019:         }
1.364     www      1020:     } elsif (!$existing{$ckey}) {
1.345     www      1021: # the key does not exist
                   1022: 	return 'error: The key does not exist';
                   1023:     } else {
                   1024: # the key is somebody else's
                   1025: 	return 'error: The key is already in use';
                   1026:     }
1.344     www      1027: }
                   1028: 
1.364     www      1029: # ------------------------------------------ put an additional comment on a key
                   1030: 
                   1031: sub comment_access_key {
                   1032: #
                   1033: # a valid key looks like uname:udom#comments
                   1034: # comments are being appended
                   1035: #
                   1036:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1037:     $cdom=
1.620     albertel 1038:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1039:     $cnum=
1.620     albertel 1040:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1041:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1042:     if ($existing{$ckey}) {
                   1043:         $existing{$ckey}.='; '.$logentry;
                   1044: # ready to assign
1.367     www      1045:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1046:                                                  $cdom,$cnum) eq 'ok') {
                   1047: 	    return 'ok';
                   1048:         } else {
                   1049: 	    return 'error: Count not store comment.';
                   1050:         }
                   1051:     } else {
                   1052: # the key does not exist
                   1053: 	return 'error: The key does not exist';
                   1054:     }
                   1055: }
                   1056: 
1.344     www      1057: # ------------------------------------------------------ Generate a set of keys
                   1058: 
                   1059: sub generate_access_keys {
1.364     www      1060:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1061:     $cdom=
1.620     albertel 1062:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1063:     $cnum=
1.620     albertel 1064:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1065:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1066:     unless (($cdom) && ($cnum)) { return 0; }
                   1067:     if ($number>10000) { return 0; }
                   1068:     sleep(2); # make sure don't get same seed twice
                   1069:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1070:     my $total=0;
                   1071:     for (my $i=1;$i<=$number;$i++) {
                   1072:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1073:                   sprintf("%lx",int(100000*rand)).'-'.
                   1074:                   sprintf("%lx",int(100000*rand));
                   1075:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1076:        $newkey=~s/0/h/g; # and also 0 and O
                   1077:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1078:        if ($existing{$newkey}) {
                   1079:            $i--;
                   1080:        } else {
1.364     www      1081: 	  if (&put('accesskeys',
                   1082:               { $newkey => '# generated '.localtime().
1.620     albertel 1083:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1084:                            '; '.$logentry },
                   1085: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1086:               $total++;
                   1087: 	  }
                   1088:        }
                   1089:     }
1.620     albertel 1090:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1091:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1092:     return $total;
                   1093: }
                   1094: 
                   1095: # ------------------------------------------------------- Validate an accesskey
                   1096: 
                   1097: sub validate_access_key {
                   1098:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1099:     $cdom=
1.620     albertel 1100:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1101:     $cnum=
1.620     albertel 1102:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1103:     $udom=$env{'user.domain'} unless (defined($udom));
                   1104:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1105:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1106:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1107: }
                   1108: 
                   1109: # ------------------------------------- Find the section of student in a course
1.652     albertel 1110: sub devalidate_getsection_cache {
                   1111:     my ($udom,$unam,$courseid)=@_;
                   1112:     my $hashid="$udom:$unam:$courseid";
                   1113:     &devalidate_cache_new('getsection',$hashid);
                   1114: }
1.298     matthew  1115: 
1.815     albertel 1116: sub courseid_to_courseurl {
                   1117:     my ($courseid) = @_;
                   1118:     #already url style courseid
                   1119:     return $courseid if ($courseid =~ m{^/});
                   1120: 
                   1121:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1122: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1123: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1124: 	return "/$cdom/$cnum";
                   1125:     }
                   1126: 
                   1127:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1128:     if (exists($courseinfo{'num'})) {
                   1129: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1130:     }
                   1131: 
                   1132:     return undef;
                   1133: }
                   1134: 
1.298     matthew  1135: sub getsection {
                   1136:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1137:     my $cachetime=1800;
1.551     albertel 1138: 
                   1139:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1140:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1141:     if (defined($cached)) { return $result; }
                   1142: 
1.298     matthew  1143:     my %Pending; 
                   1144:     my %Expired;
                   1145:     #
                   1146:     # Each role can either have not started yet (pending), be active, 
                   1147:     #    or have expired.
                   1148:     #
                   1149:     # If there is an active role, we are done.
                   1150:     #
                   1151:     # If there is more than one role which has not started yet, 
                   1152:     #     choose the one which will start sooner
                   1153:     # If there is one role which has not started yet, return it.
                   1154:     #
                   1155:     # If there is more than one expired role, choose the one which ended last.
                   1156:     # If there is a role which has expired, return it.
                   1157:     #
1.815     albertel 1158:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1159:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1160:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1161:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1162:         my $section=$1;
                   1163:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1164:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1165:         my $now=time;
1.548     albertel 1166:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1167:             $Expired{$end}=$section;
                   1168:             next;
                   1169:         }
1.548     albertel 1170:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1171:             $Pending{$start}=$section;
                   1172:             next;
                   1173:         }
1.599     albertel 1174:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1175:     }
                   1176:     #
                   1177:     # Presumedly there will be few matching roles from the above
                   1178:     # loop and the sorting time will be negligible.
                   1179:     if (scalar(keys(%Pending))) {
                   1180:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1181:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1182:     } 
                   1183:     if (scalar(keys(%Expired))) {
                   1184:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1185:         my $time = pop(@sorted);
1.599     albertel 1186:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1187:     }
1.599     albertel 1188:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1189: }
1.70      www      1190: 
1.599     albertel 1191: sub save_cache {
                   1192:     &purge_remembered();
1.722     albertel 1193:     #&Apache::loncommon::validate_page();
1.620     albertel 1194:     undef(%env);
1.780     albertel 1195:     undef($env_loaded);
1.599     albertel 1196: }
1.452     albertel 1197: 
1.599     albertel 1198: my $to_remember=-1;
                   1199: my %remembered;
                   1200: my %accessed;
                   1201: my $kicks=0;
                   1202: my $hits=0;
1.849     albertel 1203: sub make_key {
                   1204:     my ($name,$id) = @_;
1.872     albertel 1205:     if (length($id) > 65 
                   1206: 	&& length(&escape($id)) > 200) {
                   1207: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1208:     }
1.849     albertel 1209:     return &escape($name.':'.$id);
                   1210: }
                   1211: 
1.599     albertel 1212: sub devalidate_cache_new {
                   1213:     my ($name,$id,$debug) = @_;
                   1214:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1215:     $id=&make_key($name,$id);
1.599     albertel 1216:     $memcache->delete($id);
                   1217:     delete($remembered{$id});
                   1218:     delete($accessed{$id});
                   1219: }
                   1220: 
                   1221: sub is_cached_new {
                   1222:     my ($name,$id,$debug) = @_;
1.849     albertel 1223:     $id=&make_key($name,$id);
1.599     albertel 1224:     if (exists($remembered{$id})) {
                   1225: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1226: 	$accessed{$id}=[&gettimeofday()];
                   1227: 	$hits++;
                   1228: 	return ($remembered{$id},1);
                   1229:     }
                   1230:     my $value = $memcache->get($id);
                   1231:     if (!(defined($value))) {
                   1232: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1233: 	return (undef,undef);
1.416     albertel 1234:     }
1.599     albertel 1235:     if ($value eq '__undef__') {
                   1236: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1237: 	$value=undef;
                   1238:     }
                   1239:     &make_room($id,$value,$debug);
                   1240:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1241:     return ($value,1);
                   1242: }
                   1243: 
                   1244: sub do_cache_new {
                   1245:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1246:     $id=&make_key($name,$id);
1.599     albertel 1247:     my $setvalue=$value;
                   1248:     if (!defined($setvalue)) {
                   1249: 	$setvalue='__undef__';
                   1250:     }
1.623     albertel 1251:     if (!defined($time) ) {
                   1252: 	$time=600;
                   1253:     }
1.599     albertel 1254:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1255:     my $result = $memcache->set($id,$setvalue,$time);
                   1256:     if (! $result) {
1.872     albertel 1257: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1258: 	$memcache->disconnect_all();
1.872     albertel 1259:     }
1.600     albertel 1260:     # need to make a copy of $value
                   1261:     #&make_room($id,$value,$debug);
1.599     albertel 1262:     return $value;
                   1263: }
                   1264: 
                   1265: sub make_room {
                   1266:     my ($id,$value,$debug)=@_;
                   1267:     $remembered{$id}=$value;
                   1268:     if ($to_remember<0) { return; }
                   1269:     $accessed{$id}=[&gettimeofday()];
                   1270:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1271:     my $to_kick;
                   1272:     my $max_time=0;
                   1273:     foreach my $other (keys(%accessed)) {
                   1274: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1275: 	    $to_kick=$other;
                   1276: 	    $max_time=&tv_interval($accessed{$other});
                   1277: 	}
                   1278:     }
                   1279:     delete($remembered{$to_kick});
                   1280:     delete($accessed{$to_kick});
                   1281:     $kicks++;
                   1282:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1283:     return;
                   1284: }
                   1285: 
1.599     albertel 1286: sub purge_remembered {
1.604     albertel 1287:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1288:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1289:     undef(%remembered);
                   1290:     undef(%accessed);
1.428     albertel 1291: }
1.70      www      1292: # ------------------------------------- Read an entry from a user's environment
                   1293: 
                   1294: sub userenvironment {
                   1295:     my ($udom,$unam,@what)=@_;
                   1296:     my %returnhash=();
                   1297:     my @answer=split(/\&/,
                   1298:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1299:                       &homeserver($unam,$udom)));
                   1300:     my $i;
                   1301:     for ($i=0;$i<=$#what;$i++) {
                   1302: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1303:     }
                   1304:     return %returnhash;
1.1       albertel 1305: }
                   1306: 
1.617     albertel 1307: # ---------------------------------------------------------- Get a studentphoto
                   1308: sub studentphoto {
                   1309:     my ($udom,$unam,$ext) = @_;
                   1310:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1311:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1312:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1313:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1314:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1315:             } else {
                   1316:                 my ($result,$perm_reqd)=
1.707     albertel 1317: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1318:                 if ($result eq 'ok') {
                   1319:                     if (!($perm_reqd eq 'yes')) {
                   1320:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1321:                     }
                   1322:                 }
                   1323:             }
                   1324:         }
                   1325:     } else {
                   1326:         my ($result,$perm_reqd) = 
1.707     albertel 1327: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1328:         if ($result eq 'ok') {
                   1329:             if (!($perm_reqd eq 'yes')) {
                   1330:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1331:             }
                   1332:         }
                   1333:     }
                   1334:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1335: }
                   1336: 
                   1337: sub retrievestudentphoto {
                   1338:     my ($udom,$unam,$ext,$type) = @_;
                   1339:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1340:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1341:     if ($ret eq 'ok') {
                   1342:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1343:         if ($type eq 'thumbnail') {
                   1344:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1345:         }
                   1346:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1347:         return $tokenurl;
                   1348:     } else {
                   1349:         if ($type eq 'thumbnail') {
                   1350:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1351:         } else { 
                   1352:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1353:         }
1.617     albertel 1354:     }
                   1355: }
                   1356: 
1.263     www      1357: # -------------------------------------------------------------------- New chat
                   1358: 
                   1359: sub chatsend {
1.724     raeburn  1360:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1361:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1362:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1363:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1364:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1365: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1366: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1367: }
                   1368: 
                   1369: # ------------------------------------------ Find current version of a resource
                   1370: 
                   1371: sub getversion {
                   1372:     my $fname=&clutter(shift);
                   1373:     unless ($fname=~/^\/res\//) { return -1; }
                   1374:     return &currentversion(&filelocation('',$fname));
                   1375: }
                   1376: 
                   1377: sub currentversion {
                   1378:     my $fname=shift;
1.599     albertel 1379:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1380:     if (defined($cached)) { return $result; }
1.292     www      1381:     my $author=$fname;
                   1382:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1383:     my ($udom,$uname)=split(/\//,$author);
                   1384:     my $home=homeserver($uname,$udom);
                   1385:     if ($home eq 'no_host') { 
                   1386:         return -1; 
                   1387:     }
                   1388:     my $answer=reply("currentversion:$fname",$home);
                   1389:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1390: 	return -1;
                   1391:     }
1.599     albertel 1392:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1393: }
                   1394: 
1.1       albertel 1395: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1396: 
1.1       albertel 1397: sub subscribe {
                   1398:     my $fname=shift;
1.761     raeburn  1399:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1400:     $fname=~s/[\n\r]//g;
1.1       albertel 1401:     my $author=$fname;
                   1402:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1403:     my ($udom,$uname)=split(/\//,$author);
                   1404:     my $home=homeserver($uname,$udom);
1.335     albertel 1405:     if ($home eq 'no_host') {
                   1406:         return 'not_found';
1.1       albertel 1407:     }
                   1408:     my $answer=reply("sub:$fname",$home);
1.64      www      1409:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1410: 	$answer.=' by '.$home;
                   1411:     }
1.1       albertel 1412:     return $answer;
                   1413: }
                   1414:     
1.8       www      1415: # -------------------------------------------------------------- Replicate file
                   1416: 
                   1417: sub repcopy {
                   1418:     my $filename=shift;
1.23      www      1419:     $filename=~s/\/+/\//g;
1.607     raeburn  1420:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1421:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1422:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1423: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1424: 	return &repcopy_userfile($filename);
                   1425:     }
1.532     albertel 1426:     $filename=~s/[\n\r]//g;
1.8       www      1427:     my $transname="$filename.in.transfer";
1.828     www      1428: # FIXME: this should flock
1.607     raeburn  1429:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1430:     my $remoteurl=subscribe($filename);
1.64      www      1431:     if ($remoteurl =~ /^con_lost by/) {
                   1432: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1433:            return 'unavailable';
1.8       www      1434:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1435: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1436: 	   return 'not_found';
1.64      www      1437:     } elsif ($remoteurl =~ /^rejected by/) {
                   1438: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1439:            return 'forbidden';
1.20      www      1440:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1441:            return 'ok';
1.8       www      1442:     } else {
1.290     www      1443:         my $author=$filename;
                   1444:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1445:         my ($udom,$uname)=split(/\//,$author);
                   1446:         my $home=homeserver($uname,$udom);
                   1447:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1448:            my @parts=split(/\//,$filename);
                   1449:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1450:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1451:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1452: 	       return 'bad_request';
1.8       www      1453:            }
                   1454:            my $count;
                   1455:            for ($count=5;$count<$#parts;$count++) {
                   1456:                $path.="/$parts[$count]";
                   1457:                if ((-e $path)!=1) {
                   1458: 		   mkdir($path,0777);
                   1459:                }
                   1460:            }
                   1461:            my $ua=new LWP::UserAgent;
                   1462:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1463:            my $response=$ua->request($request,$transname);
                   1464:            if ($response->is_error()) {
                   1465: 	       unlink($transname);
                   1466:                my $message=$response->status_line;
1.672     albertel 1467:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1468:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1469:                return 'unavailable';
1.8       www      1470:            } else {
1.16      www      1471: 	       if ($remoteurl!~/\.meta$/) {
                   1472:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1473:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1474:                   if ($mresponse->is_error()) {
                   1475: 		      unlink($filename.'.meta');
                   1476:                       &logthis(
1.672     albertel 1477:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1478:                   }
                   1479: 	       }
1.8       www      1480:                rename($transname,$filename);
1.607     raeburn  1481:                return 'ok';
1.8       www      1482:            }
1.290     www      1483:        }
1.8       www      1484:     }
1.330     www      1485: }
                   1486: 
                   1487: # ------------------------------------------------ Get server side include body
                   1488: sub ssi_body {
1.381     albertel 1489:     my ($filelink,%form)=@_;
1.606     matthew  1490:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1491:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1492:     }
1.330     www      1493:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1494:                                      &ssi($filelink,%form));
1.778     albertel 1495:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1496:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1497:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1498:     return $output;
1.8       www      1499: }
                   1500: 
1.15      www      1501: # --------------------------------------------------------- Server Side Include
                   1502: 
1.782     albertel 1503: sub absolute_url {
                   1504:     my ($host_name) = @_;
                   1505:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1506:     if ($host_name eq '') {
                   1507: 	$host_name = $ENV{'SERVER_NAME'};
                   1508:     }
                   1509:     return $protocol.$host_name;
                   1510: }
                   1511: 
1.15      www      1512: sub ssi {
                   1513: 
1.23      www      1514:     my ($fn,%form)=@_;
1.15      www      1515: 
                   1516:     my $ua=new LWP::UserAgent;
1.23      www      1517:     
                   1518:     my $request;
1.711     albertel 1519: 
                   1520:     $form{'no_update_last_known'}=1;
1.895     albertel 1521:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1522:     if (%form) {
1.782     albertel 1523:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1524:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1525:     } else {
1.782     albertel 1526:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1527:     }
                   1528: 
1.15      www      1529:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1530:     my $response=$ua->request($request);
                   1531: 
1.324     www      1532:     return $response->content;
                   1533: }
                   1534: 
                   1535: sub externalssi {
                   1536:     my ($url)=@_;
                   1537:     my $ua=new LWP::UserAgent;
                   1538:     my $request=new HTTP::Request('GET',$url);
                   1539:     my $response=$ua->request($request);
1.15      www      1540:     return $response->content;
                   1541: }
1.254     www      1542: 
1.492     albertel 1543: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1544: 
                   1545: sub allowuploaded {
                   1546:     my ($srcurl,$url)=@_;
                   1547:     $url=&clutter(&declutter($url));
                   1548:     my $dir=$url;
                   1549:     $dir=~s/\/[^\/]+$//;
                   1550:     my %httpref=();
                   1551:     my $httpurl=&hreflocation('',$url);
                   1552:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1553:     &Apache::lonnet::appenv(%httpref);
1.254     www      1554: }
1.477     raeburn  1555: 
1.478     albertel 1556: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1557: # input: action, courseID, current domain, intended
1.637     raeburn  1558: #        path to file, source of file, instruction to parse file for objects,
                   1559: #        ref to hash for embedded objects,
                   1560: #        ref to hash for codebase of java objects.
                   1561: #
1.485     raeburn  1562: # output: url to file (if action was uploaddoc), 
                   1563: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1564: #
1.478     albertel 1565: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1566: # course.
1.477     raeburn  1567: #
1.478     albertel 1568: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1569: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1570: #          course's home server.
1.477     raeburn  1571: #
1.478     albertel 1572: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1573: #          be copied from $source (current location) to 
                   1574: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1575: #         and will then be copied to
                   1576: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1577: #         course's home server.
1.485     raeburn  1578: #
1.481     raeburn  1579: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1580: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1581: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1582: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1583: #         in course's home server.
1.637     raeburn  1584: #
1.477     raeburn  1585: 
                   1586: sub process_coursefile {
1.638     albertel 1587:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1588:     my $fetchresult;
1.638     albertel 1589:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1590:     if ($action eq 'propagate') {
1.638     albertel 1591:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1592: 			     $home);
1.481     raeburn  1593:     } else {
1.477     raeburn  1594:         my $fpath = '';
                   1595:         my $fname = $file;
1.478     albertel 1596:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1597:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1598:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1599:         if ($action eq 'copy') {
                   1600:             if ($source eq '') {
                   1601:                 $fetchresult = 'no source file';
                   1602:                 return $fetchresult;
                   1603:             } else {
                   1604:                 my $destination = $filepath.'/'.$fname;
                   1605:                 rename($source,$destination);
                   1606:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1607:                                  $home);
1.481     raeburn  1608:             }
                   1609:         } elsif ($action eq 'uploaddoc') {
                   1610:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1611:             print $fh $env{'form.'.$source};
1.481     raeburn  1612:             close($fh);
1.637     raeburn  1613:             if ($parser eq 'parse') {
                   1614:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1615:                 unless ($parse_result eq 'ok') {
                   1616:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1617:                 }
                   1618:             }
1.477     raeburn  1619:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1620:                                  $home);
1.481     raeburn  1621:             if ($fetchresult eq 'ok') {
                   1622:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1623:             } else {
                   1624:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1625:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1626:                 return '/adm/notfound.html';
                   1627:             }
1.477     raeburn  1628:         }
                   1629:     }
1.485     raeburn  1630:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1631:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1632:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1633:     }
                   1634:     return $fetchresult;
                   1635: }
                   1636: 
1.637     raeburn  1637: sub build_filepath {
                   1638:     my ($fpath) = @_;
                   1639:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1640:     unless ($fpath eq '') {
                   1641:         my @parts=split('/',$fpath);
                   1642:         foreach my $part (@parts) {
                   1643:             $filepath.= '/'.$part;
                   1644:             if ((-e $filepath)!=1) {
                   1645:                 mkdir($filepath,0777);
                   1646:             }
                   1647:         }
                   1648:     }
                   1649:     return $filepath;
                   1650: }
                   1651: 
                   1652: sub store_edited_file {
1.638     albertel 1653:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1654:     my $file = $primary_url;
                   1655:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1656:     my $fpath = '';
                   1657:     my $fname = $file;
                   1658:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1659:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1660:     my $filepath = &build_filepath($fpath);
                   1661:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1662:     print $fh $content;
                   1663:     close($fh);
1.638     albertel 1664:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1665:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1666: 			  $home);
1.637     raeburn  1667:     if ($$fetchresult eq 'ok') {
                   1668:         return '/uploaded/'.$fpath.'/'.$fname;
                   1669:     } else {
1.638     albertel 1670:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1671: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1672:         return '/adm/notfound.html';
                   1673:     }
                   1674: }
                   1675: 
1.531     albertel 1676: sub clean_filename {
1.831     albertel 1677:     my ($fname,$args)=@_;
1.315     www      1678: # Replace Windows backslashes by forward slashes
1.257     www      1679:     $fname=~s/\\/\//g;
1.831     albertel 1680:     if (!$args->{'keep_path'}) {
                   1681:         # Get rid of everything but the actual filename
                   1682: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1683:     }
1.315     www      1684: # Replace spaces by underscores
                   1685:     $fname=~s/\s+/\_/g;
                   1686: # Replace all other weird characters by nothing
1.831     albertel 1687:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1688: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1689: # numbers
                   1690:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1691:     return $fname;
                   1692: }
                   1693: 
1.608     albertel 1694: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1695: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1696: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1697: #        $coursedoc - if true up to the current course
                   1698: #                     if false
                   1699: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1700: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1701: #        $allfiles - reference to hash for embedded objects
                   1702: #        $codebase - reference to hash for codebase of java objects
                   1703: #        $desuname - username for permanent storage of uploaded file
                   1704: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1705: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1706: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1707: # 
1.686     albertel 1708: # output: url of file in userspace, or error: <message> 
                   1709: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1710: 
                   1711: 
1.531     albertel 1712: sub userfileupload {
1.860     raeburn  1713:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1714:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1715:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1716:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1717:     $fname=&clean_filename($fname);
1.315     www      1718: # See if there is anything left
1.257     www      1719:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1720:     chop($env{'form.'.$formname});
1.523     raeburn  1721:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1722:         my $now = time;
                   1723:         my $filepath = 'tmp/helprequests/'.$now;
                   1724:         my @parts=split(/\//,$filepath);
                   1725:         my $fullpath = $perlvar{'lonDaemons'};
                   1726:         for (my $i=0;$i<@parts;$i++) {
                   1727:             $fullpath .= '/'.$parts[$i];
                   1728:             if ((-e $fullpath)!=1) {
                   1729:                 mkdir($fullpath,0777);
                   1730:             }
                   1731:         }
                   1732:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1733:         print $fh $env{'form.'.$formname};
1.523     raeburn  1734:         close($fh);
1.741     raeburn  1735:         return $fullpath.'/'.$fname;
                   1736:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1737:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1738:                        '_'.$env{'user.domain'}.'/pending';
                   1739:         my @parts=split(/\//,$filepath);
                   1740:         my $fullpath = $perlvar{'lonDaemons'};
                   1741:         for (my $i=0;$i<@parts;$i++) {
                   1742:             $fullpath .= '/'.$parts[$i];
                   1743:             if ((-e $fullpath)!=1) {
                   1744:                 mkdir($fullpath,0777);
                   1745:             }
                   1746:         }
                   1747:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1748:         print $fh $env{'form.'.$formname};
                   1749:         close($fh);
                   1750:         return $fullpath.'/'.$fname;
1.523     raeburn  1751:     }
1.719     banghart 1752:     
1.258     www      1753: # Create the directory if not present
1.493     albertel 1754:     $fname="$subdir/$fname";
1.259     www      1755:     if ($coursedoc) {
1.638     albertel 1756: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1757: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1758:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1759:             return &finishuserfileupload($docuname,$docudom,
                   1760: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1761: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1762:         } else {
1.620     albertel 1763:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1764:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1765: 				       $fname,$formname,$parser,
                   1766: 				       $allfiles,$codebase);
1.481     raeburn  1767:         }
1.719     banghart 1768:     } elsif (defined($destuname)) {
                   1769:         my $docuname=$destuname;
                   1770:         my $docudom=$destudom;
1.860     raeburn  1771: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1772: 				     $parser,$allfiles,$codebase,
                   1773:                                      $thumbwidth,$thumbheight);
1.719     banghart 1774:         
1.259     www      1775:     } else {
1.638     albertel 1776:         my $docuname=$env{'user.name'};
                   1777:         my $docudom=$env{'user.domain'};
1.714     raeburn  1778:         if (exists($env{'form.group'})) {
                   1779:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1780:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1781:         }
1.860     raeburn  1782: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1783: 				     $parser,$allfiles,$codebase,
                   1784:                                      $thumbwidth,$thumbheight);
1.259     www      1785:     }
1.271     www      1786: }
                   1787: 
                   1788: sub finishuserfileupload {
1.860     raeburn  1789:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1790:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1791:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1792:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1793:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1794:     $file=$fname;
                   1795:     if ($fname=~m|/|) {
                   1796:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1797: 	$path.=$fnamepath.'/';
                   1798:     }
1.259     www      1799:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1800:     my $count;
                   1801:     for ($count=4;$count<=$#parts;$count++) {
                   1802:         $filepath.="/$parts[$count]";
                   1803:         if ((-e $filepath)!=1) {
                   1804: 	    mkdir($filepath,0777);
                   1805:         }
                   1806:     }
                   1807: # Save the file
                   1808:     {
1.701     albertel 1809: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1810: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1811: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1812: 	    return '/adm/notfound.html';
                   1813: 	}
                   1814: 	if (!print FH ($env{'form.'.$formname})) {
                   1815: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1816: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1817: 	    return '/adm/notfound.html';
                   1818: 	}
1.570     albertel 1819: 	close(FH);
1.258     www      1820:     }
1.637     raeburn  1821:     if ($parser eq 'parse') {
1.638     albertel 1822:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1823: 						   $codebase);
1.637     raeburn  1824:         unless ($parse_result eq 'ok') {
1.638     albertel 1825:             &logthis('Failed to parse '.$filepath.$file.
                   1826: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1827:         }
                   1828:     }
1.860     raeburn  1829:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1830:         my $input = $filepath.'/'.$file;
                   1831:         my $output = $filepath.'/'.'tn-'.$file;
                   1832:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1833:         system("convert -sample $thumbsize $input $output");
                   1834:         if (-e $filepath.'/'.'tn-'.$file) {
                   1835:             $fetchthumb  = 1; 
                   1836:         }
                   1837:     }
1.858     raeburn  1838:  
1.259     www      1839: # Notify homeserver to grep it
                   1840: #
1.638     albertel 1841:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1842:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1843:     if ($fetchresult eq 'ok') {
1.860     raeburn  1844:         if ($fetchthumb) {
                   1845:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1846:             if ($thumbresult ne 'ok') {
                   1847:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1848:                          $docuhome.': '.$thumbresult);
                   1849:             }
                   1850:         }
1.259     www      1851: #
1.258     www      1852: # Return the URL to it
1.494     albertel 1853:         return '/uploaded/'.$path.$file;
1.263     www      1854:     } else {
1.494     albertel 1855:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1856: 		 ': '.$fetchresult);
1.263     www      1857:         return '/adm/notfound.html';
1.858     raeburn  1858:     }
1.493     albertel 1859: }
                   1860: 
1.637     raeburn  1861: sub extract_embedded_items {
1.648     raeburn  1862:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1863:     my @state = ();
                   1864:     my %javafiles = (
                   1865:                       codebase => '',
                   1866:                       code => '',
                   1867:                       archive => ''
                   1868:                     );
                   1869:     my %mediafiles = (
                   1870:                       src => '',
                   1871:                       movie => '',
                   1872:                      );
1.648     raeburn  1873:     my $p;
                   1874:     if ($content) {
                   1875:         $p = HTML::LCParser->new($content);
                   1876:     } else {
                   1877:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1878:     }
1.641     albertel 1879:     while (my $t=$p->get_token()) {
1.640     albertel 1880: 	if ($t->[0] eq 'S') {
                   1881: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 1882: 	    push(@state, $tagname);
1.648     raeburn  1883:             if (lc($tagname) eq 'allow') {
                   1884:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1885:             }
1.640     albertel 1886: 	    if (lc($tagname) eq 'img') {
                   1887: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1888: 	    }
1.886     albertel 1889: 	    if (lc($tagname) eq 'a') {
                   1890: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   1891: 	    }
1.645     raeburn  1892:             if (lc($tagname) eq 'script') {
                   1893:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1894:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1895:                 } else {
                   1896:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1897:                 }
                   1898:             }
                   1899:             if (lc($tagname) eq 'link') {
                   1900:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1901:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1902:                 }
                   1903:             }
1.640     albertel 1904: 	    if (lc($tagname) eq 'object' ||
                   1905: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1906: 		foreach my $item (keys(%javafiles)) {
                   1907: 		    $javafiles{$item} = '';
                   1908: 		}
                   1909: 	    }
                   1910: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1911: 		my $name = lc($attr->{'name'});
                   1912: 		foreach my $item (keys(%javafiles)) {
                   1913: 		    if ($name eq $item) {
                   1914: 			$javafiles{$item} = $attr->{'value'};
                   1915: 			last;
                   1916: 		    }
                   1917: 		}
                   1918: 		foreach my $item (keys(%mediafiles)) {
                   1919: 		    if ($name eq $item) {
                   1920: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1921: 			last;
                   1922: 		    }
                   1923: 		}
                   1924: 	    }
                   1925: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1926: 		foreach my $item (keys(%javafiles)) {
                   1927: 		    if ($attr->{$item}) {
                   1928: 			$javafiles{$item} = $attr->{$item};
                   1929: 			last;
                   1930: 		    }
                   1931: 		}
                   1932: 		foreach my $item (keys(%mediafiles)) {
                   1933: 		    if ($attr->{$item}) {
                   1934: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1935: 			last;
                   1936: 		    }
                   1937: 		}
                   1938: 	    }
                   1939: 	} elsif ($t->[0] eq 'E') {
                   1940: 	    my ($tagname) = ($t->[1]);
                   1941: 	    if ($javafiles{'codebase'} ne '') {
                   1942: 		$javafiles{'codebase'} .= '/';
                   1943: 	    }  
                   1944: 	    if (lc($tagname) eq 'applet' ||
                   1945: 		lc($tagname) eq 'object' ||
                   1946: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1947: 		) {
                   1948: 		foreach my $item (keys(%javafiles)) {
                   1949: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1950: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1951: 			&add_filetype($allfiles,$file,$item);
                   1952: 		    }
                   1953: 		}
                   1954: 	    } 
                   1955: 	    pop @state;
                   1956: 	}
                   1957:     }
1.637     raeburn  1958:     return 'ok';
                   1959: }
                   1960: 
1.639     albertel 1961: sub add_filetype {
                   1962:     my ($allfiles,$file,$type)=@_;
                   1963:     if (exists($allfiles->{$file})) {
                   1964: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1965: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1966: 	}
                   1967:     } else {
                   1968: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1969:     }
                   1970: }
                   1971: 
1.493     albertel 1972: sub removeuploadedurl {
                   1973:     my ($url)=@_;
                   1974:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1975:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1976: }
                   1977: 
                   1978: sub removeuserfile {
                   1979:     my ($docuname,$docudom,$fname)=@_;
                   1980:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1981:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1982:     if ($result eq 'ok') {
                   1983:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1984:             my $metafile = $fname.'.meta';
                   1985:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1986: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1987:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1988:             my $sqlresult = 
1.823     albertel 1989:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1990:                                         'portfolio_metadata',$group,
                   1991:                                         'delete');
1.798     raeburn  1992:         }
                   1993:     }
                   1994:     return $result;
1.257     www      1995: }
1.15      www      1996: 
1.530     albertel 1997: sub mkdiruserfile {
                   1998:     my ($docuname,$docudom,$dir)=@_;
                   1999:     my $home=&homeserver($docuname,$docudom);
                   2000:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2001: }
                   2002: 
1.531     albertel 2003: sub renameuserfile {
                   2004:     my ($docuname,$docudom,$old,$new)=@_;
                   2005:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2006:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2007:                         &escape("$old").':'.&escape("$new"),$home);
                   2008:     if ($result eq 'ok') {
                   2009:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2010:             my $oldmeta = $old.'.meta';
                   2011:             my $newmeta = $new.'.meta';
                   2012:             my $metaresult = 
                   2013:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2014: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2015:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2016:             my $sqlresult = 
1.823     albertel 2017:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2018:                                         'portfolio_metadata',$group,
                   2019:                                         'delete');
1.798     raeburn  2020:         }
                   2021:     }
                   2022:     return $result;
1.531     albertel 2023: }
                   2024: 
1.14      www      2025: # ------------------------------------------------------------------------- Log
                   2026: 
                   2027: sub log {
                   2028:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2029:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2030: }
                   2031: 
                   2032: # ------------------------------------------------------------------ Course Log
1.352     www      2033: #
                   2034: # This routine flushes several buffers of non-mission-critical nature
                   2035: #
1.157     www      2036: 
                   2037: sub flushcourselogs {
1.352     www      2038:     &logthis('Flushing log buffers');
                   2039: #
                   2040: # course logs
                   2041: # This is a log of all transactions in a course, which can be used
                   2042: # for data mining purposes
                   2043: #
                   2044: # It also collects the courseid database, which lists last transaction
                   2045: # times and course titles for all courseids
                   2046: #
                   2047:     my %courseidbuffer=();
1.800     albertel 2048:     foreach my $crsid (keys %courselogs) {
1.352     www      2049:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2050: 		          &escape($courselogs{$crsid}),
                   2051: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2052: 	    delete $courselogs{$crsid};
                   2053:         } else {
                   2054:             &logthis('Failed to flush log buffer for '.$crsid);
                   2055:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2056:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2057:                         " exceeded maximum size, deleting.</font>");
                   2058:                delete $courselogs{$crsid};
                   2059:             }
1.352     www      2060:         }
                   2061:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2062:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2063: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2064:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2065:         } else {
                   2066:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2067: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2068:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2069:         }
1.191     harris41 2070:     }
1.352     www      2071: #
                   2072: # Write course id database (reverse lookup) to homeserver of courses 
                   2073: # Is used in pickcourse
                   2074: #
1.840     albertel 2075:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2076:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2077: 		     $crs_home);
1.352     www      2078:     }
                   2079: #
                   2080: # File accesses
                   2081: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2082: #
1.449     matthew  2083:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2084:         if ($entry =~ /___count$/) {
                   2085:             my ($dom,$name);
1.807     albertel 2086:             ($dom,$name,undef)=
1.811     albertel 2087: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2088:             if (! defined($dom) || $dom eq '' || 
                   2089:                 ! defined($name) || $name eq '') {
1.620     albertel 2090:                 my $cid = $env{'request.course.id'};
                   2091:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2092:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2093:             }
1.450     matthew  2094:             my $value = $accesshash{$entry};
                   2095:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2096:             my %temphash=($url => $value);
1.449     matthew  2097:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2098:             if ($result eq 'ok') {
                   2099:                 delete $accesshash{$entry};
                   2100:             } elsif ($result eq 'unknown_cmd') {
                   2101:                 # Target server has old code running on it.
1.450     matthew  2102:                 my %temphash=($entry => $value);
1.449     matthew  2103:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2104:                     delete $accesshash{$entry};
                   2105:                 }
                   2106:             }
                   2107:         } else {
1.811     albertel 2108:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2109:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2110:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2111:                 delete $accesshash{$entry};
                   2112:             }
1.185     www      2113:         }
1.191     harris41 2114:     }
1.352     www      2115: #
                   2116: # Roles
                   2117: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2118: #
1.800     albertel 2119:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2120:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2121: 	    split(/\:/,$entry);
                   2122:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2123:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2124:                 $rudom,$runame) eq 'ok') {
                   2125: 	    delete $userrolehash{$entry};
                   2126:         }
                   2127:     }
1.662     raeburn  2128: #
                   2129: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2130: #
                   2131:     my %domrolebuffer = ();
                   2132:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2133:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2134:         if ($domrolebuffer{$rudom}) {
                   2135:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2136:                       '='.&escape($domainrolehash{$entry});
                   2137:         } else {
                   2138:             $domrolebuffer{$rudom}.=&escape($entry).
                   2139:                       '='.&escape($domainrolehash{$entry});
                   2140:         }
                   2141:         delete $domainrolehash{$entry};
                   2142:     }
                   2143:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2144: 	my %servers = &get_servers($dom,'library');
                   2145: 	foreach my $tryserver (keys(%servers)) {
                   2146: 	    unless (&reply('domroleput:'.$dom.':'.
                   2147: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2148: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2149: 	    }
1.662     raeburn  2150:         }
                   2151:     }
1.186     www      2152:     $dumpcount++;
1.157     www      2153: }
                   2154: 
                   2155: sub courselog {
                   2156:     my $what=shift;
1.158     www      2157:     $what=time.':'.$what;
1.620     albertel 2158:     unless ($env{'request.course.id'}) { return ''; }
                   2159:     $coursedombuf{$env{'request.course.id'}}=
                   2160:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2161:     $coursenumbuf{$env{'request.course.id'}}=
                   2162:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2163:     $coursehombuf{$env{'request.course.id'}}=
                   2164:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2165:     $coursedescrbuf{$env{'request.course.id'}}=
                   2166:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2167:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2168:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2169:     $courseownerbuf{$env{'request.course.id'}}=
                   2170:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2171:     $coursetypebuf{$env{'request.course.id'}}=
                   2172:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2173:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2174: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2175:     } else {
1.620     albertel 2176: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2177:     }
1.620     albertel 2178:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2179: 	&flushcourselogs();
                   2180:     }
1.158     www      2181: }
                   2182: 
                   2183: sub courseacclog {
                   2184:     my $fnsymb=shift;
1.620     albertel 2185:     unless ($env{'request.course.id'}) { return ''; }
                   2186:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2187:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2188:         $what.=':POST';
1.583     matthew  2189:         # FIXME: Probably ought to escape things....
1.800     albertel 2190: 	foreach my $key (keys(%env)) {
                   2191:             if ($key=~/^form\.(.*)/) {
                   2192: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2193:             }
1.191     harris41 2194:         }
1.583     matthew  2195:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2196:         # FIXME: We should not be depending on a form parameter that someone
                   2197:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2198:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2199:             $what.= ':POST';
                   2200:             # FIXME: Probably ought to escape things....
                   2201:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2202:                                  'crsdiscuss') {
1.620     albertel 2203:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2204:             }
                   2205:         }
1.158     www      2206:     }
                   2207:     &courselog($what);
1.149     www      2208: }
                   2209: 
1.185     www      2210: sub countacc {
                   2211:     my $url=&declutter(shift);
1.458     matthew  2212:     return if (! defined($url) || $url eq '');
1.620     albertel 2213:     unless ($env{'request.course.id'}) { return ''; }
                   2214:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2215:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2216:     $accesshash{$key}++;
1.185     www      2217: }
1.349     www      2218: 
1.361     www      2219: sub linklog {
                   2220:     my ($from,$to)=@_;
                   2221:     $from=&declutter($from);
                   2222:     $to=&declutter($to);
                   2223:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2224:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2225: }
                   2226:   
1.349     www      2227: sub userrolelog {
                   2228:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2229:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2230:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2231:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2232:         ($trole=~/^ta/)) {
1.350     www      2233:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2234:        $userrolehash
                   2235:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2236:                     =$tend.':'.$tstart;
1.662     raeburn  2237:     }
1.898     albertel 2238:     if (($env{'request.role'} =~ /dc\./) &&
                   2239: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2240: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2241: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2242:        $userrolehash
                   2243:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2244:                     =$tend.':'.$tstart;
                   2245:     }
1.662     raeburn  2246:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2247:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2248:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2249:         ($trole=~/^sc/)) {
                   2250:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2251:        $domainrolehash
                   2252:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2253:                     = $tend.':'.$tstart;
                   2254:     }
1.351     www      2255: }
                   2256: 
                   2257: sub get_course_adv_roles {
                   2258:     my $cid=shift;
1.620     albertel 2259:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2260:     my %coursehash=&coursedescription($cid);
1.470     www      2261:     my %nothide=();
1.800     albertel 2262:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2263: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2264:     }
1.351     www      2265:     my %returnhash=();
                   2266:     my %dumphash=
                   2267:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2268:     my $now=time;
1.800     albertel 2269:     foreach my $entry (keys %dumphash) {
                   2270: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2271:         if (($tstart) && ($tstart<0)) { next; }
                   2272:         if (($tend) && ($tend<$now)) { next; }
                   2273:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2274:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2275: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2276: 	if ((&privileged($username,$domain)) && 
                   2277: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2278: 	if ($role eq 'cr') { next; }
1.351     www      2279:         my $key=&plaintext($role);
                   2280:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2281:         if ($returnhash{$key}) {
                   2282: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2283:         } else {
                   2284:             $returnhash{$key}=$username.':'.$domain;
                   2285:         }
1.400     www      2286:      }
                   2287:     return %returnhash;
                   2288: }
                   2289: 
                   2290: sub get_my_roles {
1.858     raeburn  2291:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2292:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2293:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2294:     my %dumphash;
                   2295:     if ($context eq 'userroles') { 
                   2296:         %dumphash = &dump('roles',$udom,$uname);
                   2297:     } else {
                   2298:         %dumphash=
1.400     www      2299:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2300:     }
1.400     www      2301:     my %returnhash=();
                   2302:     my $now=time;
1.800     albertel 2303:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2304:         my ($role,$tend,$tstart);
                   2305:         if ($context eq 'userroles') {
                   2306: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2307:         } else {
                   2308:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2309:         }
1.400     www      2310:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2311:         my $status = 'active';
                   2312:         if (($tend) && ($tend<$now)) {
                   2313:             $status = 'previous';
                   2314:         } 
                   2315:         if (($tstart) && ($now<$tstart)) {
                   2316:             $status = 'future';
                   2317:         }
                   2318:         if (ref($types) eq 'ARRAY') {
                   2319:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2320:                 next;
                   2321:             } 
                   2322:         } else {
                   2323:             if ($status ne 'active') {
                   2324:                 next;
                   2325:             }
                   2326:         }
1.867     raeburn  2327:         my ($rolecode,$username,$domain,$section,$area);
                   2328:         if ($context eq 'userroles') {
                   2329:             ($area,$rolecode) = split(/_/,$entry);
                   2330:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2331:         } else {
                   2332:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2333:         }
1.832     raeburn  2334:         if (ref($roledoms) eq 'ARRAY') {
                   2335:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2336:                 next;
                   2337:             }
                   2338:         }
                   2339:         if (ref($roles) eq 'ARRAY') {
                   2340:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2341:                 next;
                   2342:             }
1.867     raeburn  2343:         }
1.400     www      2344: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2345:     }
1.373     www      2346:     return %returnhash;
1.399     www      2347: }
                   2348: 
                   2349: # ----------------------------------------------------- Frontpage Announcements
                   2350: #
                   2351: #
                   2352: 
                   2353: sub postannounce {
                   2354:     my ($server,$text)=@_;
1.844     albertel 2355:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2356:     unless ($text=~/\w/) { $text=''; }
                   2357:     return &reply('setannounce:'.&escape($text),$server);
                   2358: }
                   2359: 
                   2360: sub getannounce {
1.448     albertel 2361: 
                   2362:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2363: 	my $announcement='';
1.800     albertel 2364: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2365: 	close($fh);
1.399     www      2366: 	if ($announcement=~/\w/) { 
                   2367: 	    return 
                   2368:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2369:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2370: 	} else {
                   2371: 	    return '';
                   2372: 	}
                   2373:     } else {
                   2374: 	return '';
                   2375:     }
1.351     www      2376: }
1.353     www      2377: 
                   2378: # ---------------------------------------------------------- Course ID routines
                   2379: # Deal with domain's nohist_courseid.db files
                   2380: #
                   2381: 
                   2382: sub courseidput {
                   2383:     my ($domain,$what,$coursehome)=@_;
                   2384:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2385: }
                   2386: 
                   2387: sub courseiddump {
1.791     raeburn  2388:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2389:     my %returnhash=();
1.355     www      2390:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2391:     my %libserv = &all_library();
                   2392:     foreach my $tryserver (keys(%libserv)) {
                   2393:         if ( (  $hostidflag == 1 
                   2394: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2395: 	     || (!defined($hostidflag)) ) {
                   2396: 
                   2397: 	    if ($domfilter eq ''
                   2398: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2399: 	        foreach my $line (
1.844     albertel 2400:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2401: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2402:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2403:                                $tryserver))) {
1.800     albertel 2404: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2405:                     if (($key) && ($value)) {
1.516     raeburn  2406: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2407:                     }
1.353     www      2408:                 }
                   2409:             }
                   2410:         }
                   2411:     }
                   2412:     return %returnhash;
                   2413: }
                   2414: 
1.658     raeburn  2415: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2416: 
                   2417: sub dcmailput {
1.685     raeburn  2418:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2419:     my $status = &Apache::lonnet::critical(
1.740     www      2420:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2421:        &escape($message),$server);
1.662     raeburn  2422:     return $status;
                   2423: }
                   2424: 
1.658     raeburn  2425: sub dcmaildump {
                   2426:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2427:     my %returnhash=();
1.846     albertel 2428: 
                   2429:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2430:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2431:                                                          &escape($enddate).':';
                   2432: 	my @esc_senders=map { &escape($_)} @$senders;
                   2433: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2434: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2435:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2436:             if (($key) && ($value)) {
                   2437:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2438:             }
                   2439:         }
                   2440:     }
                   2441:     return %returnhash;
                   2442: }
1.662     raeburn  2443: # ---------------------------------------------------------- Domain roles
                   2444: 
                   2445: sub get_domain_roles {
                   2446:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2447:     if (undef($startdate) || $startdate eq '') {
                   2448:         $startdate = '.';
                   2449:     }
                   2450:     if (undef($enddate) || $enddate eq '') {
                   2451:         $enddate = '.';
                   2452:     }
                   2453:     my $rolelist = join(':',@{$roles});
                   2454:     my %personnel = ();
1.841     albertel 2455: 
                   2456:     my %servers = &get_servers($dom,'library');
                   2457:     foreach my $tryserver (keys(%servers)) {
                   2458: 	%{$personnel{$tryserver}}=();
                   2459: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2460: 					    &escape($startdate).':'.
                   2461: 					    &escape($enddate).':'.
                   2462: 					    &escape($rolelist), $tryserver))) {
                   2463: 	    my ($key,$value) = split(/\=/,$line,2);
                   2464: 	    if (($key) && ($value)) {
                   2465: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2466: 	    }
                   2467: 	}
1.662     raeburn  2468:     }
                   2469:     return %personnel;
                   2470: }
1.658     raeburn  2471: 
1.149     www      2472: # ----------------------------------------------------------- Check out an item
                   2473: 
1.504     albertel 2474: sub get_first_access {
                   2475:     my ($type,$argsymb)=@_;
1.790     albertel 2476:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2477:     if ($argsymb) { $symb=$argsymb; }
                   2478:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2479:     if ($type eq 'map') {
                   2480: 	$res=&symbread($map);
                   2481:     } else {
                   2482: 	$res=$symb;
                   2483:     }
                   2484:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2485:     return $times{"$courseid\0$res"};
1.504     albertel 2486: }
                   2487: 
                   2488: sub set_first_access {
                   2489:     my ($type)=@_;
1.790     albertel 2490:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2491:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2492:     if ($type eq 'map') {
                   2493: 	$res=&symbread($map);
                   2494:     } else {
                   2495: 	$res=$symb;
                   2496:     }
                   2497:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2498:     if (!$firstaccess) {
1.588     albertel 2499: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2500:     }
                   2501:     return 'already_set';
1.504     albertel 2502: }
                   2503: 
1.149     www      2504: sub checkout {
                   2505:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2506:     my $now=time;
                   2507:     my $lonhost=$perlvar{'lonHostID'};
                   2508:     my $infostr=&escape(
1.234     www      2509:                  'CHECKOUTTOKEN&'.
1.149     www      2510:                  $tuname.'&'.
                   2511:                  $tudom.'&'.
                   2512:                  $tcrsid.'&'.
                   2513:                  $symb.'&'.
                   2514: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2515:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2516:     if ($token=~/^error\:/) { 
1.672     albertel 2517:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2518:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2519:                  "</font>");
                   2520:         return ''; 
                   2521:     }
                   2522: 
1.149     www      2523:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2524:     $token=~tr/a-z/A-Z/;
                   2525: 
1.153     www      2526:     my %infohash=('resource.0.outtoken' => $token,
                   2527:                   'resource.0.checkouttime' => $now,
                   2528:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2529: 
                   2530:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2531:        return '';
1.151     www      2532:     } else {
1.672     albertel 2533:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2534:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2535:                  "</font>");
1.149     www      2536:     }    
                   2537: 
                   2538:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2539:                          &escape('Checkout '.$infostr.' - '.
                   2540:                                                  $token)) ne 'ok') {
                   2541: 	return '';
1.151     www      2542:     } else {
1.672     albertel 2543:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2544:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2545:                  "</font>");
1.149     www      2546:     }
1.151     www      2547:     return $token;
1.149     www      2548: }
                   2549: 
                   2550: # ------------------------------------------------------------ Check in an item
                   2551: 
                   2552: sub checkin {
                   2553:     my $token=shift;
1.150     www      2554:     my $now=time;
                   2555:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2556:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2557:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2558:     $dtoken=~s/\W/\_/g;
1.234     www      2559:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2560:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2561: 
1.154     www      2562:     unless (($tuname) && ($tudom)) {
                   2563:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2564:         return '';
                   2565:     }
                   2566:     
                   2567:     unless (&allowed('mgr',$tcrsid)) {
                   2568:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2569:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2570:         return '';
                   2571:     }
                   2572: 
1.153     www      2573:     my %infohash=('resource.0.intoken' => $token,
                   2574:                   'resource.0.checkintime' => $now,
                   2575:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2576: 
                   2577:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2578:        return '';
                   2579:     }    
                   2580: 
                   2581:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2582:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2583: 	return '';
                   2584:     }
                   2585: 
                   2586:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2587: }
                   2588: 
                   2589: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2590: 
                   2591: sub expirespread {
                   2592:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2593:     my $cid=$env{'request.course.id'}; 
1.110     www      2594:     if ($cid) {
                   2595:        my $now=time;
                   2596:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2597:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2598:                             $env{'course.'.$cid.'.num'}.
1.110     www      2599: 	        	    ':nohist_expirationdates:'.
                   2600:                             &escape($key).'='.$now,
1.620     albertel 2601:                             $env{'course.'.$cid.'.home'})
1.110     www      2602:     }
                   2603:     return 'ok';
1.14      www      2604: }
                   2605: 
1.109     www      2606: # ----------------------------------------------------- Devalidate Spreadsheets
                   2607: 
                   2608: sub devalidate {
1.325     www      2609:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2610:     my $cid=$env{'request.course.id'}; 
1.109     www      2611:     if ($cid) {
1.391     matthew  2612:         # delete the stored spreadsheets for
                   2613:         # - the student level sheet of this user in course's homespace
                   2614:         # - the assessment level sheet for this resource 
                   2615:         #   for this user in user's homespace
1.553     albertel 2616: 	# - current conditional state info
1.325     www      2617: 	my $key=$uname.':'.$udom.':';
1.109     www      2618:         my $status=
1.299     matthew  2619: 	    &del('nohist_calculatedsheets',
1.391     matthew  2620: 		 [$key.'studentcalc:'],
1.620     albertel 2621: 		 $env{'course.'.$cid.'.domain'},
                   2622: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2623: 		.' '.
                   2624: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2625: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2626:         unless ($status eq 'ok ok') {
                   2627:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2628:                     $uname.' at '.$udom.' for '.
1.109     www      2629: 		    $symb.': '.$status);
1.133     albertel 2630:         }
1.553     albertel 2631: 	&delenv('user.state.'.$cid);
1.109     www      2632:     }
                   2633: }
                   2634: 
1.265     albertel 2635: sub get_scalar {
                   2636:     my ($string,$end) = @_;
                   2637:     my $value;
                   2638:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2639: 	$value = $1;
                   2640:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2641: 	$value = $1;
                   2642:     }
                   2643:     return &unescape($value);
                   2644: }
                   2645: 
                   2646: sub array2str {
                   2647:   my (@array) = @_;
                   2648:   my $result=&arrayref2str(\@array);
                   2649:   $result=~s/^__ARRAY_REF__//;
                   2650:   $result=~s/__END_ARRAY_REF__$//;
                   2651:   return $result;
                   2652: }
                   2653: 
1.204     albertel 2654: sub arrayref2str {
                   2655:   my ($arrayref) = @_;
1.265     albertel 2656:   my $result='__ARRAY_REF__';
1.204     albertel 2657:   foreach my $elem (@$arrayref) {
1.265     albertel 2658:     if(ref($elem) eq 'ARRAY') {
                   2659:       $result.=&arrayref2str($elem).'&';
                   2660:     } elsif(ref($elem) eq 'HASH') {
                   2661:       $result.=&hashref2str($elem).'&';
                   2662:     } elsif(ref($elem)) {
                   2663:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2664:     } else {
                   2665:       $result.=&escape($elem).'&';
                   2666:     }
                   2667:   }
                   2668:   $result=~s/\&$//;
1.265     albertel 2669:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2670:   return $result;
                   2671: }
                   2672: 
1.168     albertel 2673: sub hash2str {
1.204     albertel 2674:   my (%hash) = @_;
                   2675:   my $result=&hashref2str(\%hash);
1.265     albertel 2676:   $result=~s/^__HASH_REF__//;
                   2677:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2678:   return $result;
                   2679: }
                   2680: 
                   2681: sub hashref2str {
                   2682:   my ($hashref)=@_;
1.265     albertel 2683:   my $result='__HASH_REF__';
1.800     albertel 2684:   foreach my $key (sort(keys(%$hashref))) {
                   2685:     if (ref($key) eq 'ARRAY') {
                   2686:       $result.=&arrayref2str($key).'=';
                   2687:     } elsif (ref($key) eq 'HASH') {
                   2688:       $result.=&hashref2str($key).'=';
                   2689:     } elsif (ref($key)) {
1.265     albertel 2690:       $result.='=';
1.800     albertel 2691:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2692:     } else {
1.800     albertel 2693: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2694:     }
                   2695: 
1.800     albertel 2696:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2697:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2698:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2699:       $result.=&hashref2str($hashref->{$key}).'&';
                   2700:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2701:        $result.='&';
1.800     albertel 2702:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2703:     } else {
1.800     albertel 2704:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2705:     }
                   2706:   }
1.168     albertel 2707:   $result=~s/\&$//;
1.265     albertel 2708:   $result .= '__END_HASH_REF__';
1.168     albertel 2709:   return $result;
                   2710: }
                   2711: 
                   2712: sub str2hash {
1.265     albertel 2713:     my ($string)=@_;
                   2714:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2715:     return %$hash;
                   2716: }
                   2717: 
                   2718: sub str2hashref {
1.168     albertel 2719:   my ($string) = @_;
1.265     albertel 2720: 
                   2721:   my %hash;
                   2722: 
                   2723:   if($string !~ /^__HASH_REF__/) {
                   2724:       if (! ($string eq '' || !defined($string))) {
                   2725: 	  $hash{'error'}='Not hash reference';
                   2726:       }
                   2727:       return (\%hash, $string);
                   2728:   }
                   2729: 
                   2730:   $string =~ s/^__HASH_REF__//;
                   2731: 
                   2732:   while($string !~ /^__END_HASH_REF__/) {
                   2733:       #key
                   2734:       my $key='';
                   2735:       if($string =~ /^__HASH_REF__/) {
                   2736:           ($key, $string)=&str2hashref($string);
                   2737:           if(defined($key->{'error'})) {
                   2738:               $hash{'error'}='Bad data';
                   2739:               return (\%hash, $string);
                   2740:           }
                   2741:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2742:           ($key, $string)=&str2arrayref($string);
                   2743:           if($key->[0] eq 'Array reference error') {
                   2744:               $hash{'error'}='Bad data';
                   2745:               return (\%hash, $string);
                   2746:           }
                   2747:       } else {
                   2748:           $string =~ s/^(.*?)=//;
1.267     albertel 2749: 	  $key=&unescape($1);
1.265     albertel 2750:       }
                   2751:       $string =~ s/^=//;
                   2752: 
                   2753:       #value
                   2754:       my $value='';
                   2755:       if($string =~ /^__HASH_REF__/) {
                   2756:           ($value, $string)=&str2hashref($string);
                   2757:           if(defined($value->{'error'})) {
                   2758:               $hash{'error'}='Bad data';
                   2759:               return (\%hash, $string);
                   2760:           }
                   2761:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2762:           ($value, $string)=&str2arrayref($string);
                   2763:           if($value->[0] eq 'Array reference error') {
                   2764:               $hash{'error'}='Bad data';
                   2765:               return (\%hash, $string);
                   2766:           }
                   2767:       } else {
                   2768: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2769:       }
                   2770:       $string =~ s/^&//;
                   2771: 
                   2772:       $hash{$key}=$value;
1.204     albertel 2773:   }
1.265     albertel 2774: 
                   2775:   $string =~ s/^__END_HASH_REF__//;
                   2776: 
                   2777:   return (\%hash, $string);
1.204     albertel 2778: }
                   2779: 
                   2780: sub str2array {
1.265     albertel 2781:     my ($string)=@_;
                   2782:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2783:     return @$array;
                   2784: }
                   2785: 
                   2786: sub str2arrayref {
1.204     albertel 2787:   my ($string) = @_;
1.265     albertel 2788:   my @array;
                   2789: 
                   2790:   if($string !~ /^__ARRAY_REF__/) {
                   2791:       if (! ($string eq '' || !defined($string))) {
                   2792: 	  $array[0]='Array reference error';
                   2793:       }
                   2794:       return (\@array, $string);
                   2795:   }
                   2796: 
                   2797:   $string =~ s/^__ARRAY_REF__//;
                   2798: 
                   2799:   while($string !~ /^__END_ARRAY_REF__/) {
                   2800:       my $value='';
                   2801:       if($string =~ /^__HASH_REF__/) {
                   2802:           ($value, $string)=&str2hashref($string);
                   2803:           if(defined($value->{'error'})) {
                   2804:               $array[0] ='Array reference error';
                   2805:               return (\@array, $string);
                   2806:           }
                   2807:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2808:           ($value, $string)=&str2arrayref($string);
                   2809:           if($value->[0] eq 'Array reference error') {
                   2810:               $array[0] ='Array reference error';
                   2811:               return (\@array, $string);
                   2812:           }
                   2813:       } else {
                   2814: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2815:       }
                   2816:       $string =~ s/^&//;
                   2817: 
                   2818:       push(@array, $value);
1.191     harris41 2819:   }
1.265     albertel 2820: 
                   2821:   $string =~ s/^__END_ARRAY_REF__//;
                   2822: 
                   2823:   return (\@array, $string);
1.168     albertel 2824: }
                   2825: 
1.167     albertel 2826: # -------------------------------------------------------------------Temp Store
                   2827: 
1.168     albertel 2828: sub tmpreset {
                   2829:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2830:   if (!$symb) {
                   2831:     $symb=&symbread();
1.620     albertel 2832:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2833:   }
                   2834:   $symb=escape($symb);
                   2835: 
1.620     albertel 2836:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2837:   $namespace=~s/\//\_/g;
                   2838:   $namespace=~s/\W//g;
                   2839: 
1.620     albertel 2840:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2841:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2842:   if ($domain eq 'public' && $stuname eq 'public') {
                   2843:       $stuname=$ENV{'REMOTE_ADDR'};
                   2844:   }
1.168     albertel 2845:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2846:   my %hash;
                   2847:   if (tie(%hash,'GDBM_File',
                   2848: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2849: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2850:     foreach my $key (keys %hash) {
1.180     albertel 2851:       if ($key=~ /:$symb/) {
1.168     albertel 2852: 	delete($hash{$key});
                   2853:       }
                   2854:     }
                   2855:   }
                   2856: }
                   2857: 
1.167     albertel 2858: sub tmpstore {
1.168     albertel 2859:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2860: 
                   2861:   if (!$symb) {
                   2862:     $symb=&symbread();
1.620     albertel 2863:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2864:   }
                   2865:   $symb=escape($symb);
                   2866: 
                   2867:   if (!$namespace) {
                   2868:     # I don't think we would ever want to store this for a course.
                   2869:     # it seems this will only be used if we don't have a course.
1.620     albertel 2870:     #$namespace=$env{'request.course.id'};
1.168     albertel 2871:     #if (!$namespace) {
1.620     albertel 2872:       $namespace=$env{'request.state'};
1.168     albertel 2873:     #}
                   2874:   }
                   2875:   $namespace=~s/\//\_/g;
                   2876:   $namespace=~s/\W//g;
1.620     albertel 2877:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2878:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2879:   if ($domain eq 'public' && $stuname eq 'public') {
                   2880:       $stuname=$ENV{'REMOTE_ADDR'};
                   2881:   }
1.168     albertel 2882:   my $now=time;
                   2883:   my %hash;
                   2884:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2885:   if (tie(%hash,'GDBM_File',
                   2886: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2887: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2888:     $hash{"version:$symb"}++;
                   2889:     my $version=$hash{"version:$symb"};
                   2890:     my $allkeys=''; 
                   2891:     foreach my $key (keys(%$storehash)) {
                   2892:       $allkeys.=$key.':';
1.591     albertel 2893:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2894:     }
                   2895:     $hash{"$version:$symb:timestamp"}=$now;
                   2896:     $allkeys.='timestamp';
                   2897:     $hash{"$version:keys:$symb"}=$allkeys;
                   2898:     if (untie(%hash)) {
                   2899:       return 'ok';
                   2900:     } else {
                   2901:       return "error:$!";
                   2902:     }
                   2903:   } else {
                   2904:     return "error:$!";
                   2905:   }
                   2906: }
1.167     albertel 2907: 
1.168     albertel 2908: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2909: 
1.168     albertel 2910: sub tmprestore {
                   2911:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2912: 
1.168     albertel 2913:   if (!$symb) {
                   2914:     $symb=&symbread();
1.620     albertel 2915:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2916:   }
                   2917:   $symb=escape($symb);
                   2918: 
1.620     albertel 2919:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2920: 
1.620     albertel 2921:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2922:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2923:   if ($domain eq 'public' && $stuname eq 'public') {
                   2924:       $stuname=$ENV{'REMOTE_ADDR'};
                   2925:   }
1.168     albertel 2926:   my %returnhash;
                   2927:   $namespace=~s/\//\_/g;
                   2928:   $namespace=~s/\W//g;
                   2929:   my %hash;
                   2930:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2931:   if (tie(%hash,'GDBM_File',
                   2932: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2933: 	  &GDBM_READER(),0640)) {
1.168     albertel 2934:     my $version=$hash{"version:$symb"};
                   2935:     $returnhash{'version'}=$version;
                   2936:     my $scope;
                   2937:     for ($scope=1;$scope<=$version;$scope++) {
                   2938:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2939:       my @keys=split(/:/,$vkeys);
                   2940:       my $key;
                   2941:       $returnhash{"$scope:keys"}=$vkeys;
                   2942:       foreach $key (@keys) {
1.591     albertel 2943: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2944: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2945:       }
                   2946:     }
1.168     albertel 2947:     if (!(untie(%hash))) {
                   2948:       return "error:$!";
                   2949:     }
                   2950:   } else {
                   2951:     return "error:$!";
                   2952:   }
                   2953:   return %returnhash;
1.167     albertel 2954: }
                   2955: 
1.9       www      2956: # ----------------------------------------------------------------------- Store
                   2957: 
                   2958: sub store {
1.124     www      2959:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2960:     my $home='';
                   2961: 
1.168     albertel 2962:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2963: 
1.213     www      2964:     $symb=&symbclean($symb);
1.122     albertel 2965:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2966: 
1.620     albertel 2967:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2968:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2969: 
                   2970:     &devalidate($symb,$stuname,$domain);
1.109     www      2971: 
                   2972:     $symb=escape($symb);
1.187     www      2973:     if (!$namespace) { 
1.620     albertel 2974:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2975:           return ''; 
                   2976:        } 
                   2977:     }
1.620     albertel 2978:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2979: 
                   2980:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2981:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2982: 
1.12      www      2983:     my $namevalue='';
1.800     albertel 2984:     foreach my $key (keys(%$storehash)) {
                   2985:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2986:     }
1.12      www      2987:     $namevalue=~s/\&$//;
1.187     www      2988:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2989:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2990: }
                   2991: 
1.47      www      2992: # -------------------------------------------------------------- Critical Store
                   2993: 
                   2994: sub cstore {
1.124     www      2995:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2996:     my $home='';
                   2997: 
1.168     albertel 2998:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2999: 
1.213     www      3000:     $symb=&symbclean($symb);
1.122     albertel 3001:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3002: 
1.620     albertel 3003:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3004:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3005: 
                   3006:     &devalidate($symb,$stuname,$domain);
1.109     www      3007: 
                   3008:     $symb=escape($symb);
1.187     www      3009:     if (!$namespace) { 
1.620     albertel 3010:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3011:           return ''; 
                   3012:        } 
                   3013:     }
1.620     albertel 3014:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3015: 
                   3016:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3017:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3018: 
1.47      www      3019:     my $namevalue='';
1.800     albertel 3020:     foreach my $key (keys(%$storehash)) {
                   3021:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3022:     }
1.47      www      3023:     $namevalue=~s/\&$//;
1.187     www      3024:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3025:     return critical
                   3026:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3027: }
                   3028: 
1.9       www      3029: # --------------------------------------------------------------------- Restore
                   3030: 
                   3031: sub restore {
1.124     www      3032:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3033:     my $home='';
                   3034: 
1.168     albertel 3035:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3036: 
1.122     albertel 3037:     if (!$symb) {
                   3038:       unless ($symb=escape(&symbread())) { return ''; }
                   3039:     } else {
1.213     www      3040:       $symb=&escape(&symbclean($symb));
1.122     albertel 3041:     }
1.188     www      3042:     if (!$namespace) { 
1.620     albertel 3043:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3044:           return ''; 
                   3045:        } 
                   3046:     }
1.620     albertel 3047:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3048:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3049:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3050:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3051: 
1.12      www      3052:     my %returnhash=();
1.800     albertel 3053:     foreach my $line (split(/\&/,$answer)) {
                   3054: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3055:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3056:     }
1.75      www      3057:     my $version;
                   3058:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3059:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3060:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3061:        }
1.75      www      3062:     }
1.13      www      3063:     return %returnhash;
1.34      www      3064: }
                   3065: 
                   3066: # ---------------------------------------------------------- Course Description
                   3067: 
                   3068: sub coursedescription {
1.731     albertel 3069:     my ($courseid,$args)=@_;
1.34      www      3070:     $courseid=~s/^\///;
1.49      www      3071:     $courseid=~s/\_/\//g;
1.34      www      3072:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3073:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3074:     my $normalid=$cdomain.'_'.$cnum;
                   3075:     # need to always cache even if we get errors otherwise we keep 
                   3076:     # trying and trying and trying to get the course description.
                   3077:     my %envhash=();
                   3078:     my %returnhash=();
1.731     albertel 3079:     
                   3080:     my $expiretime=600;
                   3081:     if ($env{'request.course.id'} eq $normalid) {
                   3082: 	$expiretime=120;
                   3083:     }
                   3084: 
                   3085:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3086:     if (!$args->{'freshen_cache'}
                   3087: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3088: 	foreach my $key (keys(%env)) {
                   3089: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3090: 	    my ($setting) = $1;
                   3091: 	    $returnhash{$setting} = $env{$key};
                   3092: 	}
                   3093: 	return %returnhash;
                   3094:     }
                   3095: 
                   3096:     # get the data agin
                   3097:     if (!$args->{'one_time'}) {
                   3098: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3099:     }
1.811     albertel 3100: 
1.34      www      3101:     if ($chome ne 'no_host') {
1.302     albertel 3102:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3103:        if (!exists($returnhash{'con_lost'})) {
                   3104:            $returnhash{'home'}= $chome;
                   3105: 	   $returnhash{'domain'} = $cdomain;
                   3106: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3107:            if (!defined($returnhash{'type'})) {
                   3108:                $returnhash{'type'} = 'Course';
                   3109:            }
1.130     albertel 3110:            while (my ($name,$value) = each %returnhash) {
1.53      www      3111:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3112:            }
1.270     www      3113:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3114:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3115: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3116:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3117:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3118:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3119:        }
                   3120:     }
1.731     albertel 3121:     if (!$args->{'one_time'}) {
                   3122: 	&appenv(%envhash);
                   3123:     }
1.302     albertel 3124:     return %returnhash;
1.461     www      3125: }
                   3126: 
                   3127: # -------------------------------------------------See if a user is privileged
                   3128: 
                   3129: sub privileged {
                   3130:     my ($username,$domain)=@_;
                   3131:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3132: 			&homeserver($username,$domain));
                   3133:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3134:     my $now=time;
                   3135:     if ($rolesdump ne '') {
1.800     albertel 3136:         foreach my $entry (split(/&/,$rolesdump)) {
                   3137: 	    if ($entry!~/^rolesdef_/) {
                   3138: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3139: 		$area=~s/\_\w\w$//;
                   3140: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3141: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3142: 		    my $active=1;
                   3143: 		    if ($tend) {
                   3144: 			if ($tend<$now) { $active=0; }
                   3145: 		    }
                   3146: 		    if ($tstart) {
                   3147: 			if ($tstart>$now) { $active=0; }
                   3148: 		    }
                   3149: 		    if ($active) { return 1; }
                   3150: 		}
                   3151: 	    }
                   3152: 	}
                   3153:     }
                   3154:     return 0;
1.9       www      3155: }
1.1       albertel 3156: 
1.103     harris41 3157: # -------------------------------------------------------- Get user privileges
1.11      www      3158: 
                   3159: sub rolesinit {
                   3160:     my ($domain,$username,$authhost)=@_;
                   3161:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3162:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3163:     my %allroles=();
1.678     raeburn  3164:     my %allgroups=();   
1.11      www      3165:     my $now=time;
1.743     albertel 3166:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3167:     my $group_privs;
1.11      www      3168: 
                   3169:     if ($rolesdump ne '') {
1.800     albertel 3170:         foreach my $entry (split(/&/,$rolesdump)) {
                   3171: 	  if ($entry!~/^rolesdef_/) {
                   3172:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3173: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3174:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3175: 	    if ($role=~/^cr/) { 
1.807     albertel 3176: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3177: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3178: 		    ($tend,$tstart)=split('_',$trest);
                   3179: 		} else {
                   3180: 		    $trole=$role;
                   3181: 		}
1.678     raeburn  3182:             } elsif ($role =~ m|^gr/|) {
                   3183:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3184:                 ($trole,$group_privs) = split(/\//,$trole);
                   3185:                 $group_privs = &unescape($group_privs);
1.587     albertel 3186: 	    } else {
                   3187: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3188: 	    }
1.743     albertel 3189: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3190: 					 $username);
                   3191: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3192:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3193:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3194:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3195: 		my $spec=$trole.'.'.$area;
                   3196: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3197: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3198:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3199:                 } elsif ($trole eq 'gr') {
                   3200:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3201: 		} else {
1.567     raeburn  3202:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3203: 		}
1.12      www      3204:             }
1.662     raeburn  3205:           }
1.191     harris41 3206:         }
1.743     albertel 3207:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3208:         $userroles{'user.adv'}    = $adv;
                   3209: 	$userroles{'user.author'} = $author;
1.620     albertel 3210:         $env{'user.adv'}=$adv;
1.11      www      3211:     }
1.743     albertel 3212:     return \%userroles;  
1.11      www      3213: }
                   3214: 
1.567     raeburn  3215: sub set_arearole {
                   3216:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3217: # log the associated role with the area
                   3218:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3219:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3220: }
                   3221: 
                   3222: sub custom_roleprivs {
                   3223:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3224:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3225:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3226:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3227:         my ($rdummy,$roledef)=
                   3228:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3229:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3230:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3231:             if (defined($syspriv)) {
                   3232:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3233:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3234:             }
                   3235:             if ($tdomain ne '') {
                   3236:                 if (defined($dompriv)) {
                   3237:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3238:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3239:                 }
                   3240:                 if (($trest ne '') && (defined($coursepriv))) {
                   3241:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3242:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3243:                 }
                   3244:             }
                   3245:         }
                   3246:     }
                   3247: }
                   3248: 
1.678     raeburn  3249: sub group_roleprivs {
                   3250:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3251:     my $access = 1;
                   3252:     my $now = time;
                   3253:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3254:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3255:     if ($access) {
1.811     albertel 3256:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3257:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3258:     }
                   3259: }
1.567     raeburn  3260: 
                   3261: sub standard_roleprivs {
                   3262:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3263:     if (defined($pr{$trole.':s'})) {
                   3264:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3265:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3266:     }
                   3267:     if ($tdomain ne '') {
                   3268:         if (defined($pr{$trole.':d'})) {
                   3269:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3270:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3271:         }
                   3272:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3273:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3274:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3275:         }
                   3276:     }
                   3277: }
                   3278: 
                   3279: sub set_userprivs {
1.678     raeburn  3280:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3281:     my $author=0;
                   3282:     my $adv=0;
1.678     raeburn  3283:     my %grouproles = ();
                   3284:     if (keys(%{$allgroups}) > 0) {
                   3285:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3286:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3287:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3288:                 $trole = $1;
                   3289:                 $area = $2;
1.681     raeburn  3290:                 $sec = $3;
                   3291:                 $extendedarea = $area.$sec;
                   3292:                 if (exists($$allgroups{$area})) {
                   3293:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3294:                         my $spec = $trole.'.'.$extendedarea;
                   3295:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3296:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3297:                     }
                   3298:                 }
                   3299:             }
                   3300:         }
                   3301:     }
1.800     albertel 3302:     foreach my $group (keys(%grouproles)) {
                   3303:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3304:     }
1.800     albertel 3305:     foreach my $role (keys(%{$allroles})) {
                   3306:         my %thesepriv;
                   3307:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3308:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3309:             if ($item ne '') {
                   3310:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3311:                 if ($restrictions eq '') {
                   3312:                     $thesepriv{$privilege}='F';
                   3313:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3314:                     $thesepriv{$privilege}.=$restrictions;
                   3315:                 }
                   3316:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3317:             }
                   3318:         }
                   3319:         my $thesestr='';
1.800     albertel 3320:         foreach my $priv (keys(%thesepriv)) {
                   3321: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3322: 	}
                   3323:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3324:     }
                   3325:     return ($author,$adv);
                   3326: }
                   3327: 
1.12      www      3328: # --------------------------------------------------------------- get interface
                   3329: 
                   3330: sub get {
1.131     albertel 3331:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3332:    my $items='';
1.800     albertel 3333:    foreach my $item (@$storearr) {
                   3334:        $items.=&escape($item).'&';
1.191     harris41 3335:    }
1.12      www      3336:    $items=~s/\&$//;
1.620     albertel 3337:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3338:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3339:    my $uhome=&homeserver($uname,$udomain);
                   3340: 
1.133     albertel 3341:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3342:    my @pairs=split(/\&/,$rep);
1.273     albertel 3343:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3344:      return @pairs;
                   3345:    }
1.15      www      3346:    my %returnhash=();
1.42      www      3347:    my $i=0;
1.800     albertel 3348:    foreach my $item (@$storearr) {
                   3349:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3350:       $i++;
1.191     harris41 3351:    }
1.15      www      3352:    return %returnhash;
1.27      www      3353: }
                   3354: 
                   3355: # --------------------------------------------------------------- del interface
                   3356: 
                   3357: sub del {
1.133     albertel 3358:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3359:    my $items='';
1.800     albertel 3360:    foreach my $item (@$storearr) {
                   3361:        $items.=&escape($item).'&';
1.191     harris41 3362:    }
1.27      www      3363:    $items=~s/\&$//;
1.620     albertel 3364:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3365:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3366:    my $uhome=&homeserver($uname,$udomain);
                   3367: 
                   3368:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3369: }
                   3370: 
                   3371: # -------------------------------------------------------------- dump interface
                   3372: 
                   3373: sub dump {
1.755     albertel 3374:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3375:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3376:     if (!$uname) { $uname=$env{'user.name'}; }
                   3377:     my $uhome=&homeserver($uname,$udomain);
                   3378:     if ($regexp) {
                   3379: 	$regexp=&escape($regexp);
                   3380:     } else {
                   3381: 	$regexp='.';
                   3382:     }
                   3383:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3384:     my @pairs=split(/\&/,$rep);
                   3385:     my %returnhash=();
                   3386:     foreach my $item (@pairs) {
                   3387: 	my ($key,$value)=split(/=/,$item,2);
                   3388: 	$key = &unescape($key);
                   3389: 	next if ($key =~ /^error: 2 /);
                   3390: 	$returnhash{$key}=&thaw_unescape($value);
                   3391:     }
                   3392:     return %returnhash;
1.407     www      3393: }
                   3394: 
1.717     albertel 3395: # --------------------------------------------------------- dumpstore interface
                   3396: 
                   3397: sub dumpstore {
                   3398:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3399:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3400:    if (!$uname) { $uname=$env{'user.name'}; }
                   3401:    my $uhome=&homeserver($uname,$udomain);
                   3402:    if ($regexp) {
                   3403:        $regexp=&escape($regexp);
                   3404:    } else {
                   3405:        $regexp='.';
                   3406:    }
                   3407:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3408:    my @pairs=split(/\&/,$rep);
                   3409:    my %returnhash=();
                   3410:    foreach my $item (@pairs) {
                   3411:        my ($key,$value)=split(/=/,$item,2);
                   3412:        next if ($key =~ /^error: 2 /);
                   3413:        $returnhash{$key}=&thaw_unescape($value);
                   3414:    }
                   3415:    return %returnhash;
1.717     albertel 3416: }
                   3417: 
1.407     www      3418: # -------------------------------------------------------------- keys interface
                   3419: 
                   3420: sub getkeys {
                   3421:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3422:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3423:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3424:    my $uhome=&homeserver($uname,$udomain);
                   3425:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3426:    my @keyarray=();
1.800     albertel 3427:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3428:       next if ($key =~ /^error: 2 /);
1.800     albertel 3429:       push(@keyarray,&unescape($key));
1.407     www      3430:    }
                   3431:    return @keyarray;
1.318     matthew  3432: }
                   3433: 
1.319     matthew  3434: # --------------------------------------------------------------- currentdump
                   3435: sub currentdump {
1.328     matthew  3436:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3437:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3438:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3439:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3440:    my $uhome = &homeserver($sname,$sdom);
                   3441:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3442:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3443:    #
1.318     matthew  3444:    my %returnhash=();
1.319     matthew  3445:    #
                   3446:    if ($rep eq "unknown_cmd") { 
                   3447:        # an old lond will not know currentdump
                   3448:        # Do a dump and make it look like a currentdump
1.822     albertel 3449:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3450:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3451:        my %hash = @tmp;
                   3452:        @tmp=();
1.424     matthew  3453:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3454:    } else {
                   3455:        my @pairs=split(/\&/,$rep);
1.800     albertel 3456:        foreach my $pair (@pairs) {
                   3457:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3458:            my ($symb,$param) = split(/:/,$key);
                   3459:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3460:                                                         &thaw_unescape($value);
1.319     matthew  3461:        }
1.191     harris41 3462:    }
1.12      www      3463:    return %returnhash;
1.424     matthew  3464: }
                   3465: 
                   3466: sub convert_dump_to_currentdump{
                   3467:     my %hash = %{shift()};
                   3468:     my %returnhash;
                   3469:     # Code ripped from lond, essentially.  The only difference
                   3470:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3471:     # we might run in to problems with parameter names =~ /^v\./
                   3472:     while (my ($key,$value) = each(%hash)) {
                   3473:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3474: 	$symb  = &unescape($symb);
                   3475: 	$param = &unescape($param);
1.424     matthew  3476:         next if ($v eq 'version' || $symb eq 'keys');
                   3477:         next if (exists($returnhash{$symb}) &&
                   3478:                  exists($returnhash{$symb}->{$param}) &&
                   3479:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3480:         $returnhash{$symb}->{$param}=$value;
                   3481:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3482:     }
                   3483:     #
                   3484:     # Remove all of the keys in the hashes which keep track of
                   3485:     # the version of the parameter.
                   3486:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3487:         # use a foreach because we are going to delete from the hash.
                   3488:         foreach my $key (keys(%$param_hash)) {
                   3489:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3490:         }
                   3491:     }
                   3492:     return \%returnhash;
1.12      www      3493: }
                   3494: 
1.627     albertel 3495: # ------------------------------------------------------ critical inc interface
                   3496: 
                   3497: sub cinc {
                   3498:     return &inc(@_,'critical');
                   3499: }
                   3500: 
1.449     matthew  3501: # --------------------------------------------------------------- inc interface
                   3502: 
                   3503: sub inc {
1.627     albertel 3504:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3505:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3506:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3507:     my $uhome=&homeserver($uname,$udomain);
                   3508:     my $items='';
                   3509:     if (! ref($store)) {
                   3510:         # got a single value, so use that instead
                   3511:         $items = &escape($store).'=&';
                   3512:     } elsif (ref($store) eq 'SCALAR') {
                   3513:         $items = &escape($$store).'=&';        
                   3514:     } elsif (ref($store) eq 'ARRAY') {
                   3515:         $items = join('=&',map {&escape($_);} @{$store});
                   3516:     } elsif (ref($store) eq 'HASH') {
                   3517:         while (my($key,$value) = each(%{$store})) {
                   3518:             $items.= &escape($key).'='.&escape($value).'&';
                   3519:         }
                   3520:     }
                   3521:     $items=~s/\&$//;
1.627     albertel 3522:     if ($critical) {
                   3523: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3524:     } else {
                   3525: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3526:     }
1.449     matthew  3527: }
                   3528: 
1.12      www      3529: # --------------------------------------------------------------- put interface
                   3530: 
                   3531: sub put {
1.134     albertel 3532:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3533:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3534:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3535:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3536:    my $items='';
1.800     albertel 3537:    foreach my $item (keys(%$storehash)) {
                   3538:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3539:    }
1.12      www      3540:    $items=~s/\&$//;
1.134     albertel 3541:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3542: }
                   3543: 
1.631     albertel 3544: # ------------------------------------------------------------ newput interface
                   3545: 
                   3546: sub newput {
                   3547:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3548:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3549:    if (!$uname) { $uname=$env{'user.name'}; }
                   3550:    my $uhome=&homeserver($uname,$udomain);
                   3551:    my $items='';
                   3552:    foreach my $key (keys(%$storehash)) {
                   3553:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3554:    }
                   3555:    $items=~s/\&$//;
                   3556:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3557: }
                   3558: 
                   3559: # ---------------------------------------------------------  putstore interface
                   3560: 
1.524     raeburn  3561: sub putstore {
1.715     albertel 3562:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3563:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3564:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3565:    my $uhome=&homeserver($uname,$udomain);
                   3566:    my $items='';
1.715     albertel 3567:    foreach my $key (keys(%$storehash)) {
                   3568:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3569:    }
1.715     albertel 3570:    $items=~s/\&$//;
1.716     albertel 3571:    my $esc_symb=&escape($symb);
                   3572:    my $esc_v=&escape($version);
1.715     albertel 3573:    my $reply =
1.716     albertel 3574:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3575: 	      $uhome);
                   3576:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3577:        # gfall back to way things use to be done
1.715     albertel 3578:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3579: 			    $uname);
1.524     raeburn  3580:    }
1.715     albertel 3581:    return $reply;
                   3582: }
                   3583: 
                   3584: sub old_putstore {
1.716     albertel 3585:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3586:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3587:     if (!$uname) { $uname=$env{'user.name'}; }
                   3588:     my $uhome=&homeserver($uname,$udomain);
                   3589:     my %newstorehash;
1.800     albertel 3590:     foreach my $item (keys(%$storehash)) {
                   3591: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3592: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3593:     }
                   3594:     my $items='';
                   3595:     my %allitems = ();
1.800     albertel 3596:     foreach my $item (keys(%newstorehash)) {
                   3597: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3598: 	    my $key = $1.':keys:'.$2;
                   3599: 	    $allitems{$key} .= $3.':';
                   3600: 	}
1.800     albertel 3601: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3602:     }
1.800     albertel 3603:     foreach my $item (keys(%allitems)) {
                   3604: 	$allitems{$item} =~ s/\:$//;
                   3605: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3606:     }
                   3607:     $items=~s/\&$//;
                   3608:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3609: }
                   3610: 
1.47      www      3611: # ------------------------------------------------------ critical put interface
                   3612: 
                   3613: sub cput {
1.134     albertel 3614:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3615:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3616:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3617:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3618:    my $items='';
1.800     albertel 3619:    foreach my $item (keys(%$storehash)) {
                   3620:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3621:    }
1.47      www      3622:    $items=~s/\&$//;
1.134     albertel 3623:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3624: }
                   3625: 
                   3626: # -------------------------------------------------------------- eget interface
                   3627: 
                   3628: sub eget {
1.133     albertel 3629:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3630:    my $items='';
1.800     albertel 3631:    foreach my $item (@$storearr) {
                   3632:        $items.=&escape($item).'&';
1.191     harris41 3633:    }
1.12      www      3634:    $items=~s/\&$//;
1.620     albertel 3635:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3636:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3637:    my $uhome=&homeserver($uname,$udomain);
                   3638:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3639:    my @pairs=split(/\&/,$rep);
                   3640:    my %returnhash=();
1.42      www      3641:    my $i=0;
1.800     albertel 3642:    foreach my $item (@$storearr) {
                   3643:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3644:       $i++;
1.191     harris41 3645:    }
1.12      www      3646:    return %returnhash;
                   3647: }
                   3648: 
1.667     albertel 3649: # ------------------------------------------------------------ tmpput interface
                   3650: sub tmpput {
1.802     raeburn  3651:     my ($storehash,$server,$context)=@_;
1.667     albertel 3652:     my $items='';
1.800     albertel 3653:     foreach my $item (keys(%$storehash)) {
                   3654: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3655:     }
                   3656:     $items=~s/\&$//;
1.802     raeburn  3657:     if (defined($context)) {
                   3658:         $items .= ':'.&escape($context);
                   3659:     }
1.667     albertel 3660:     return &reply("tmpput:$items",$server);
                   3661: }
                   3662: 
                   3663: # ------------------------------------------------------------ tmpget interface
                   3664: sub tmpget {
1.688     albertel 3665:     my ($token,$server)=@_;
                   3666:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3667:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3668:     my %returnhash;
                   3669:     foreach my $item (split(/\&/,$rep)) {
                   3670: 	my ($key,$value)=split(/=/,$item);
                   3671: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3672:     }
                   3673:     return %returnhash;
                   3674: }
                   3675: 
1.688     albertel 3676: # ------------------------------------------------------------ tmpget interface
                   3677: sub tmpdel {
                   3678:     my ($token,$server)=@_;
                   3679:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3680:     return &reply("tmpdel:$token",$server);
                   3681: }
                   3682: 
1.765     albertel 3683: # -------------------------------------------------- portfolio access checking
                   3684: 
                   3685: sub portfolio_access {
1.766     albertel 3686:     my ($requrl) = @_;
1.765     albertel 3687:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3688:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3689:     if ($result) {
                   3690:         my %setters;
                   3691:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3692:             my ($startblock,$endblock) =
                   3693:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3694:             if ($startblock && $endblock) {
                   3695:                 return 'B';
                   3696:             }
                   3697:         } else {
                   3698:             my ($startblock,$endblock) =
                   3699:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3700:             if ($startblock && $endblock) {
                   3701:                 return 'B';
                   3702:             }
                   3703:         }
                   3704:     }
1.765     albertel 3705:     if ($result eq 'ok') {
1.766     albertel 3706:        return 'F';
1.765     albertel 3707:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3708:        return 'A';
1.765     albertel 3709:     }
1.766     albertel 3710:     return '';
1.765     albertel 3711: }
                   3712: 
                   3713: sub get_portfolio_access {
1.767     albertel 3714:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3715: 
                   3716:     if (!ref($access_hash)) {
                   3717: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3718: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3719: 						   $file_name);
                   3720: 	$access_hash = $access_controls{$file_name};
                   3721:     }
                   3722: 
1.765     albertel 3723:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3724:     my $now = time;
                   3725:     if (ref($access_hash) eq 'HASH') {
                   3726:         foreach my $key (keys(%{$access_hash})) {
                   3727:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3728:             if ($start > $now) {
                   3729:                 next;
                   3730:             }
                   3731:             if ($end && $end<$now) {
                   3732:                 next;
                   3733:             }
                   3734:             if ($scope eq 'public') {
                   3735:                 $public = $key;
                   3736:                 last;
                   3737:             } elsif ($scope eq 'guest') {
                   3738:                 $guest = $key;
                   3739:             } elsif ($scope eq 'domains') {
                   3740:                 push(@domains,$key);
                   3741:             } elsif ($scope eq 'users') {
                   3742:                 push(@users,$key);
                   3743:             } elsif ($scope eq 'course') {
                   3744:                 push(@courses,$key);
                   3745:             } elsif ($scope eq 'group') {
                   3746:                 push(@groups,$key);
                   3747:             }
                   3748:         }
                   3749:         if ($public) {
                   3750:             return 'ok';
                   3751:         }
                   3752:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3753:             if ($guest) {
                   3754:                 return $guest;
                   3755:             }
                   3756:         } else {
                   3757:             if (@domains > 0) {
                   3758:                 foreach my $domkey (@domains) {
                   3759:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3760:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3761:                             return 'ok';
                   3762:                         }
                   3763:                     }
                   3764:                 }
                   3765:             }
                   3766:             if (@users > 0) {
                   3767:                 foreach my $userkey (@users) {
1.865     raeburn  3768:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3769:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3770:                             if (ref($item) eq 'HASH') {
                   3771:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3772:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3773:                                     return 'ok';
                   3774:                                 }
                   3775:                             }
                   3776:                         }
                   3777:                     } 
1.765     albertel 3778:                 }
                   3779:             }
                   3780:             my %roleshash;
                   3781:             my @courses_and_groups = @courses;
                   3782:             push(@courses_and_groups,@groups); 
                   3783:             if (@courses_and_groups > 0) {
                   3784:                 my (%allgroups,%allroles); 
                   3785:                 my ($start,$end,$role,$sec,$group);
                   3786:                 foreach my $envkey (%env) {
1.811     albertel 3787:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3788:                         my $cid = $2.'_'.$3; 
                   3789:                         if ($1 eq 'gr') {
                   3790:                             $group = $4;
                   3791:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3792:                         } else {
                   3793:                             if ($4 eq '') {
                   3794:                                 $sec = 'none';
                   3795:                             } else {
                   3796:                                 $sec = $4;
                   3797:                             }
                   3798:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3799:                         }
1.811     albertel 3800:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3801:                         my $cid = $2.'_'.$3;
                   3802:                         if ($4 eq '') {
                   3803:                             $sec = 'none';
                   3804:                         } else {
                   3805:                             $sec = $4;
                   3806:                         }
                   3807:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3808:                     }
                   3809:                 }
                   3810:                 if (keys(%allroles) == 0) {
                   3811:                     return;
                   3812:                 }
                   3813:                 foreach my $key (@courses_and_groups) {
                   3814:                     my %content = %{$$access_hash{$key}};
                   3815:                     my $cnum = $content{'number'};
                   3816:                     my $cdom = $content{'domain'};
                   3817:                     my $cid = $cdom.'_'.$cnum;
                   3818:                     if (!exists($allroles{$cid})) {
                   3819:                         next;
                   3820:                     }    
                   3821:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3822:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3823:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3824:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3825:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3826:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3827:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3828:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3829:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3830:                                         if (grep/^all$/,@sections) {
                   3831:                                             return 'ok';
                   3832:                                         } else {
                   3833:                                             if (grep/^$sec$/,@sections) {
                   3834:                                                 return 'ok';
                   3835:                                             }
                   3836:                                         }
                   3837:                                     }
                   3838:                                 }
                   3839:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3840:                                     if (grep/^none$/,@groups) {
                   3841:                                         return 'ok';
                   3842:                                     }
                   3843:                                 } else {
                   3844:                                     if (grep/^all$/,@groups) {
                   3845:                                         return 'ok';
                   3846:                                     } 
                   3847:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3848:                                         if (grep/^$group$/,@groups) {
                   3849:                                             return 'ok';
                   3850:                                         }
                   3851:                                     }
                   3852:                                 } 
                   3853:                             }
                   3854:                         }
                   3855:                     }
                   3856:                 }
                   3857:             }
                   3858:             if ($guest) {
                   3859:                 return $guest;
                   3860:             }
                   3861:         }
                   3862:     }
                   3863:     return;
                   3864: }
                   3865: 
                   3866: sub course_group_datechecker {
                   3867:     my ($dates,$now,$status) = @_;
                   3868:     my ($start,$end) = split(/\./,$dates);
                   3869:     if (!$start && !$end) {
                   3870:         return 'ok';
                   3871:     }
                   3872:     if (grep/^active$/,@{$status}) {
                   3873:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3874:             return 'ok';
                   3875:         }
                   3876:     }
                   3877:     if (grep/^previous$/,@{$status}) {
                   3878:         if ($end > $now ) {
                   3879:             return 'ok';
                   3880:         }
                   3881:     }
                   3882:     if (grep/^future$/,@{$status}) {
                   3883:         if ($start > $now) {
                   3884:             return 'ok';
                   3885:         }
                   3886:     }
                   3887:     return; 
                   3888: }
                   3889: 
                   3890: sub parse_portfolio_url {
                   3891:     my ($url) = @_;
                   3892: 
                   3893:     my ($type,$udom,$unum,$group,$file_name);
                   3894:     
1.823     albertel 3895:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3896: 	$type = 1;
                   3897:         $udom = $1;
                   3898:         $unum = $2;
                   3899:         $file_name = $3;
1.823     albertel 3900:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3901: 	$type = 2;
                   3902:         $udom = $1;
                   3903:         $unum = $2;
                   3904:         $group = $3;
                   3905:         $file_name = $3.'/'.$4;
                   3906:     }
                   3907:     if (wantarray) {
                   3908: 	return ($type,$udom,$unum,$file_name,$group);
                   3909:     }
                   3910:     return $type;
                   3911: }
                   3912: 
                   3913: sub is_portfolio_url {
                   3914:     my ($url) = @_;
                   3915:     return scalar(&parse_portfolio_url($url));
                   3916: }
                   3917: 
1.798     raeburn  3918: sub is_portfolio_file {
                   3919:     my ($file) = @_;
1.820     raeburn  3920:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3921:         return 1;
                   3922:     }
                   3923:     return;
                   3924: }
                   3925: 
                   3926: 
1.341     www      3927: # ---------------------------------------------- Custom access rule evaluation
                   3928: 
                   3929: sub customaccess {
                   3930:     my ($priv,$uri)=@_;
1.807     albertel 3931:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3932:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3933:     $udom = &LONCAPA::clean_domain($udom);
                   3934:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3935:     my $access=0;
1.800     albertel 3936:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 3937: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   3938: 	if ($type eq 'user') {
                   3939: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 3940: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 3941: 		if ($tdom) {
                   3942: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   3943: 		}
1.896     albertel 3944: 		if ($tuname) {
                   3945: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 3946: 		}
                   3947: 		$access=($effect eq 'allow');
                   3948: 		last;
                   3949: 	    }
                   3950: 	} else {
                   3951: 	    if ($role) {
                   3952: 		if ($role ne $urole) { next; }
                   3953: 	    }
                   3954: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3955: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   3956: 		if ($tdom) {
                   3957: 		    if ($tdom ne $udom) { next; }
                   3958: 		}
                   3959: 		if ($tcrs) {
                   3960: 		    if ($tcrs ne $ucrs) { next; }
                   3961: 		}
                   3962: 		if ($tsec) {
                   3963: 		    if ($tsec ne $usec) { next; }
                   3964: 		}
                   3965: 		$access=($effect eq 'allow');
                   3966: 		last;
                   3967: 	    }
                   3968: 	    if ($realm eq '' && $role eq '') {
                   3969: 		$access=($effect eq 'allow');
                   3970: 	    }
1.402     bowersj2 3971: 	}
1.341     www      3972:     }
                   3973:     return $access;
                   3974: }
                   3975: 
1.103     harris41 3976: # ------------------------------------------------- Check for a user privilege
1.12      www      3977: 
                   3978: sub allowed {
1.810     raeburn  3979:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3980:     my $ver_orguri=$uri;
1.439     www      3981:     $uri=&deversion($uri);
1.152     www      3982:     my $orguri=$uri;
1.52      www      3983:     $uri=&declutter($uri);
1.809     raeburn  3984: 
1.810     raeburn  3985:     if ($priv eq 'evb') {
                   3986: # Evade communication block restrictions for specified role in a course
                   3987:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3988:             return $1;
                   3989:         } else {
                   3990:             return;
                   3991:         }
                   3992:     }
                   3993: 
1.620     albertel 3994:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3995: # Free bre access to adm and meta resources
1.775     albertel 3996:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3997: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3998: 	&& ($priv eq 'bre')) {
1.14      www      3999: 	return 'F';
1.159     www      4000:     }
                   4001: 
1.545     banghart 4002: # Free bre access to user's own portfolio contents
1.714     raeburn  4003:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4004:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4005: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4006:         my %setters;
                   4007:         my ($startblock,$endblock) = 
                   4008:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4009:         if ($startblock && $endblock) {
                   4010:             return 'B';
                   4011:         } else {
                   4012:             return 'F';
                   4013:         }
1.545     banghart 4014:     }
                   4015: 
1.762     raeburn  4016: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4017:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4018:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4019:         if (exists($env{'request.course.id'})) {
                   4020:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4021:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4022:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4023:                 my $courseprivid=$env{'request.course.id'};
                   4024:                 $courseprivid=~s/\_/\//;
                   4025:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4026:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4027:                     return $1; 
1.762     raeburn  4028:                 } else {
                   4029:                     if ($env{'request.course.sec'}) {
                   4030:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4031:                     }
                   4032:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4033:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4034:                         return $2;
                   4035:                     }
1.714     raeburn  4036:                 }
                   4037:             }
                   4038:         }
                   4039:     }
                   4040: 
1.159     www      4041: # Free bre to public access
                   4042: 
                   4043:     if ($priv eq 'bre') {
1.238     www      4044:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4045: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4046:            return 'F'; 
                   4047:         }
1.238     www      4048:         if ($copyright eq 'priv') {
                   4049:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4050: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4051: 		return '';
                   4052:             }
                   4053:         }
                   4054:         if ($copyright eq 'domain') {
                   4055:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4056: 	    unless (($env{'user.domain'} eq $1) ||
                   4057:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4058: 		return '';
                   4059:             }
1.262     matthew  4060:         }
1.620     albertel 4061:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4062:             # Library role, so allow browsing of resources in this domain.
                   4063:             return 'F';
1.238     www      4064:         }
1.341     www      4065:         if ($copyright eq 'custom') {
                   4066: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4067:         }
1.14      www      4068:     }
1.264     matthew  4069:     # Domain coordinator is trying to create a course
1.620     albertel 4070:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4071:         # uri is the requested domain in this case.
                   4072:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4073:         # a role of dc for the domain in question.
1.620     albertel 4074:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4075:     }
1.29      www      4076: 
1.52      www      4077:     my $thisallowed='';
                   4078:     my $statecond=0;
                   4079:     my $courseprivid='';
                   4080: 
                   4081: # Course
                   4082: 
1.620     albertel 4083:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4084:        $thisallowed.=$1;
                   4085:     }
1.29      www      4086: 
1.52      www      4087: # Domain
                   4088: 
1.620     albertel 4089:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4090:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4091:        $thisallowed.=$1;
                   4092:     }
1.52      www      4093: 
                   4094: # Course: uri itself is a course
1.66      www      4095:     my $courseuri=$uri;
                   4096:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4097:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4098: 
1.620     albertel 4099:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4100:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4101:        $thisallowed.=$1;
                   4102:     }
1.29      www      4103: 
1.665     albertel 4104: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4105: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4106:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4107: 	$thisallowed='';
1.671     raeburn  4108:         my ($match)=&is_on_map($uri);
                   4109:         if ($match) {
                   4110:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4111:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4112:                 $thisallowed.=$1;
                   4113:             }
                   4114:         } else {
1.705     albertel 4115:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4116:             if ($refuri) {
                   4117:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4118:                     $thisallowed='F';
1.671     raeburn  4119:                 } else {
                   4120:                     $refuri=&declutter($refuri);
                   4121:                     my ($match) = &is_on_map($refuri);
                   4122:                     if ($match) {
                   4123:                         $thisallowed='F';
                   4124:                     }
1.669     raeburn  4125:                 }
1.671     raeburn  4126:             }
                   4127:         }
1.314     www      4128:     }
1.492     albertel 4129: 
1.766     albertel 4130:     if ($priv eq 'bre'
                   4131: 	&& $thisallowed ne 'F' 
                   4132: 	&& $thisallowed ne '2'
                   4133: 	&& &is_portfolio_url($uri)) {
                   4134: 	$thisallowed = &portfolio_access($uri);
                   4135:     }
                   4136:     
1.52      www      4137: # Full access at system, domain or course-wide level? Exit.
1.29      www      4138: 
                   4139:     if ($thisallowed=~/F/) {
                   4140: 	return 'F';
                   4141:     }
                   4142: 
1.52      www      4143: # If this is generating or modifying users, exit with special codes
1.29      www      4144: 
1.643     www      4145:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4146: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4147: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4148: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4149: 	    unless ($auname) { return $thisallowed; }
                   4150: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4151: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4152: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4153: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4154: 	}
1.52      www      4155: 	return $thisallowed;
                   4156:     }
                   4157: #
1.103     harris41 4158: # Gathered so far: system, domain and course wide privileges
1.52      www      4159: #
                   4160: # Course: See if uri or referer is an individual resource that is part of 
                   4161: # the course
                   4162: 
1.620     albertel 4163:     if ($env{'request.course.id'}) {
1.232     www      4164: 
1.620     albertel 4165:        $courseprivid=$env{'request.course.id'};
                   4166:        if ($env{'request.course.sec'}) {
                   4167:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4168:        }
                   4169:        $courseprivid=~s/\_/\//;
                   4170:        my $checkreferer=1;
1.232     www      4171:        my ($match,$cond)=&is_on_map($uri);
                   4172:        if ($match) {
                   4173:            $statecond=$cond;
1.620     albertel 4174:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4175:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4176:                $thisallowed.=$1;
                   4177:                $checkreferer=0;
                   4178:            }
1.29      www      4179:        }
1.83      www      4180:        
1.148     www      4181:        if ($checkreferer) {
1.620     albertel 4182: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4183:             unless ($refuri) {
1.800     albertel 4184:                 foreach my $key (keys(%env)) {
                   4185: 		    if ($key=~/^httpref\..*\*/) {
                   4186: 			my $pattern=$key;
1.156     www      4187:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4188:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4189:                         $pattern=~s/\//\\\//g;
1.152     www      4190:                         if ($orguri=~/$pattern/) {
1.800     albertel 4191: 			    $refuri=$env{$key};
1.148     www      4192:                         }
                   4193:                     }
1.191     harris41 4194:                 }
1.148     www      4195:             }
1.232     www      4196: 
1.148     www      4197:          if ($refuri) { 
1.152     www      4198: 	  $refuri=&declutter($refuri);
1.232     www      4199:           my ($match,$cond)=&is_on_map($refuri);
                   4200:             if ($match) {
                   4201:               my $refstatecond=$cond;
1.620     albertel 4202:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4203:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4204:                   $thisallowed.=$1;
1.53      www      4205:                   $uri=$refuri;
                   4206:                   $statecond=$refstatecond;
1.52      www      4207:               }
                   4208:           }
1.148     www      4209:         }
1.29      www      4210:        }
1.52      www      4211:    }
1.29      www      4212: 
1.52      www      4213: #
1.103     harris41 4214: # Gathered now: all privileges that could apply, and condition number
1.52      www      4215: # 
                   4216: #
                   4217: # Full or no access?
                   4218: #
1.29      www      4219: 
1.52      www      4220:     if ($thisallowed=~/F/) {
                   4221: 	return 'F';
                   4222:     }
1.29      www      4223: 
1.52      www      4224:     unless ($thisallowed) {
                   4225:         return '';
                   4226:     }
1.29      www      4227: 
1.52      www      4228: # Restrictions exist, deal with them
                   4229: #
                   4230: #   C:according to course preferences
                   4231: #   R:according to resource settings
                   4232: #   L:unless locked
                   4233: #   X:according to user session state
                   4234: #
                   4235: 
                   4236: # Possibly locked functionality, check all courses
1.54      www      4237: # Locks might take effect only after 10 minutes cache expiration for other
                   4238: # courses, and 2 minutes for current course
1.52      www      4239: 
                   4240:     my $envkey;
                   4241:     if ($thisallowed=~/L/) {
1.620     albertel 4242:         foreach $envkey (keys %env) {
1.54      www      4243:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4244:                my $courseid=$2;
                   4245:                my $roleid=$1.'.'.$2;
1.92      www      4246:                $courseid=~s/^\///;
1.54      www      4247:                my $expiretime=600;
1.620     albertel 4248:                if ($env{'request.role'} eq $roleid) {
1.54      www      4249: 		  $expiretime=120;
                   4250:                }
                   4251: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4252:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4253:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4254: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4255:                }
1.620     albertel 4256:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4257:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4258: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4259:                        &log($env{'user.domain'},$env{'user.name'},
                   4260:                             $env{'user.home'},
1.57      www      4261:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4262:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4263:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4264: 		       return '';
                   4265:                    }
                   4266:                }
1.620     albertel 4267:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4268:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4269: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4270:                        &log($env{'user.domain'},$env{'user.name'},
                   4271:                             $env{'user.home'},
1.57      www      4272:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4273:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4274:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4275: 		       return '';
                   4276:                    }
                   4277:                }
                   4278: 	   }
1.29      www      4279:        }
1.52      www      4280:     }
                   4281:    
                   4282: #
                   4283: # Rest of the restrictions depend on selected course
                   4284: #
                   4285: 
1.620     albertel 4286:     unless ($env{'request.course.id'}) {
1.766     albertel 4287: 	if ($thisallowed eq 'A') {
                   4288: 	    return 'A';
1.814     raeburn  4289:         } elsif ($thisallowed eq 'B') {
                   4290:             return 'B';
1.766     albertel 4291: 	} else {
                   4292: 	    return '1';
                   4293: 	}
1.52      www      4294:     }
1.29      www      4295: 
1.52      www      4296: #
                   4297: # Now user is definitely in a course
                   4298: #
1.53      www      4299: 
                   4300: 
                   4301: # Course preferences
                   4302: 
                   4303:    if ($thisallowed=~/C/) {
1.620     albertel 4304:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4305:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4306:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4307: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4308: 	   if ($priv ne 'pch') { 
                   4309: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4310: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4311: 			$env{'request.course.id'});
                   4312: 	   }
1.237     www      4313:            return '';
                   4314:        }
                   4315: 
1.620     albertel 4316:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4317: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4318: 	   if ($priv ne 'pch') { 
                   4319: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4320: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4321: 			$env{'request.course.id'});
                   4322: 	   }
1.54      www      4323:            return '';
                   4324:        }
1.53      www      4325:    }
                   4326: 
                   4327: # Resource preferences
                   4328: 
                   4329:    if ($thisallowed=~/R/) {
1.620     albertel 4330:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4331:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4332: 	   if ($priv ne 'pch') { 
                   4333: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4334: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4335: 	   }
                   4336: 	   return '';
1.54      www      4337:        }
1.53      www      4338:    }
1.30      www      4339: 
1.246     www      4340: # Restricted by state or randomout?
1.30      www      4341: 
1.52      www      4342:    if ($thisallowed=~/X/) {
1.620     albertel 4343:       if ($env{'acc.randomout'}) {
1.579     albertel 4344: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4345:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4346:             return ''; 
                   4347:          }
1.247     www      4348:       }
                   4349:       if (&condval($statecond)) {
1.52      www      4350: 	 return '2';
                   4351:       } else {
                   4352:          return '';
                   4353:       }
                   4354:    }
1.30      www      4355: 
1.766     albertel 4356:     if ($thisallowed eq 'A') {
                   4357: 	return 'A';
1.814     raeburn  4358:     } elsif ($thisallowed eq 'B') {
                   4359:         return 'B';
1.766     albertel 4360:     }
1.52      www      4361:    return 'F';
1.232     www      4362: }
                   4363: 
1.710     albertel 4364: sub split_uri_for_cond {
                   4365:     my $uri=&deversion(&declutter(shift));
                   4366:     my @uriparts=split(/\//,$uri);
                   4367:     my $filename=pop(@uriparts);
                   4368:     my $pathname=join('/',@uriparts);
                   4369:     return ($pathname,$filename);
                   4370: }
1.232     www      4371: # --------------------------------------------------- Is a resource on the map?
                   4372: 
                   4373: sub is_on_map {
1.710     albertel 4374:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4375:     #Trying to find the conditional for the file
1.620     albertel 4376:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4377: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4378:     if ($match) {
1.289     bowersj2 4379: 	return (1,$1);
                   4380:     } else {
1.434     www      4381: 	return (0,0);
1.289     bowersj2 4382:     }
1.12      www      4383: }
                   4384: 
1.427     www      4385: # --------------------------------------------------------- Get symb from alias
                   4386: 
                   4387: sub get_symb_from_alias {
                   4388:     my $symb=shift;
                   4389:     my ($map,$resid,$url)=&decode_symb($symb);
                   4390: # Already is a symb
                   4391:     if ($url) { return $symb; }
                   4392: # Must be an alias
                   4393:     my $aliassymb='';
                   4394:     my %bighash;
1.620     albertel 4395:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4396:                             &GDBM_READER(),0640)) {
                   4397:         my $rid=$bighash{'mapalias_'.$symb};
                   4398: 	if ($rid) {
                   4399: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4400: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4401: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4402: 	}
                   4403:         untie %bighash;
                   4404:     }
                   4405:     return $aliassymb;
                   4406: }
                   4407: 
1.12      www      4408: # ----------------------------------------------------------------- Define Role
                   4409: 
                   4410: sub definerole {
                   4411:   if (allowed('mcr','/')) {
                   4412:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4413:     foreach my $role (split(':',$sysrole)) {
                   4414: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4415:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4416:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4417: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4418:                return "refused:s:$crole&$cqual"; 
                   4419:             }
                   4420:         }
1.191     harris41 4421:     }
1.800     albertel 4422:     foreach my $role (split(':',$domrole)) {
                   4423: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4424:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4425:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4426: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4427:                return "refused:d:$crole&$cqual"; 
                   4428:             }
                   4429:         }
1.191     harris41 4430:     }
1.800     albertel 4431:     foreach my $role (split(':',$courole)) {
                   4432: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4433:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4434:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4435: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4436:                return "refused:c:$crole&$cqual"; 
                   4437:             }
                   4438:         }
1.191     harris41 4439:     }
1.620     albertel 4440:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4441:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4442: 	        "rolesdef_$rolename=".
                   4443:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4444:     return reply($command,$env{'user.home'});
1.12      www      4445:   } else {
                   4446:     return 'refused';
                   4447:   }
1.105     harris41 4448: }
                   4449: 
                   4450: # ---------------- Make a metadata query against the network of library servers
                   4451: 
                   4452: sub metadata_query {
1.244     matthew  4453:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4454:     my %rhash;
1.845     albertel 4455:     my %libserv = &all_library();
1.244     matthew  4456:     my @server_list = (defined($server_array) ? @$server_array
                   4457:                                               : keys(%libserv) );
                   4458:     for my $server (@server_list) {
1.118     harris41 4459: 	unless ($custom or $customshow) {
                   4460: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4461: 	    $rhash{$server}=$reply;
                   4462: 	}
                   4463: 	else {
                   4464: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4465: 			     &escape($custom).':'.&escape($customshow),
                   4466: 			     $server);
                   4467: 	    $rhash{$server}=$reply;
                   4468: 	}
1.112     harris41 4469:     }
1.118     harris41 4470:     return \%rhash;
1.240     www      4471: }
                   4472: 
                   4473: # ----------------------------------------- Send log queries and wait for reply
                   4474: 
                   4475: sub log_query {
                   4476:     my ($uname,$udom,$query,%filters)=@_;
                   4477:     my $uhome=&homeserver($uname,$udom);
                   4478:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4479:     my $uhost=&hostname($uhome);
1.800     albertel 4480:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4481:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4482:                        $uhome);
1.479     albertel 4483:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4484:     return get_query_reply($queryid);
                   4485: }
                   4486: 
1.818     raeburn  4487: # -------------------------- Update MySQL table for portfolio file
                   4488: 
                   4489: sub update_portfolio_table {
1.821     raeburn  4490:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4491:     my $homeserver = &homeserver($uname,$udom);
                   4492:     my $queryid=
1.821     raeburn  4493:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4494:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4495:     my $reply = &get_query_reply($queryid);
                   4496:     return $reply;
                   4497: }
                   4498: 
1.899     raeburn  4499: # -------------------------- Update MySQL allusers table
                   4500: 
                   4501: sub update_allusers_table {
                   4502:     my ($uname,$udom,$names) = @_;
                   4503:     my $homeserver = &homeserver($uname,$udom);
                   4504:     my $queryid=
                   4505:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4506:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4507:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4508:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4509:                'generation='.&escape($names->{'generation'}).'%%'.
                   4510:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4511:                'id='.&escape($names->{'id'}),$homeserver);
                   4512:     my $reply = &get_query_reply($queryid);
                   4513:     return $reply;
                   4514: }
                   4515: 
1.508     raeburn  4516: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4517: 
                   4518: sub fetch_enrollment_query {
1.511     raeburn  4519:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4520:     my $homeserver;
1.547     raeburn  4521:     my $maxtries = 1;
1.508     raeburn  4522:     if ($context eq 'automated') {
                   4523:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4524:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4525:     } else {
                   4526:         $homeserver = &homeserver($cnum,$dom);
                   4527:     }
1.838     albertel 4528:     my $host=&hostname($homeserver);
1.506     raeburn  4529:     my $cmd = '';
1.800     albertel 4530:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4531:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4532:     }
                   4533:     $cmd =~ s/%%$//;
                   4534:     $cmd = &escape($cmd);
                   4535:     my $query = 'fetchenrollment';
1.620     albertel 4536:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4537:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4538:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4539:         return 'error: '.$queryid;
                   4540:     }
1.506     raeburn  4541:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4542:     my $tries = 1;
                   4543:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4544:         $reply = &get_query_reply($queryid);
                   4545:         $tries ++;
                   4546:     }
1.526     raeburn  4547:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4548:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4549:     } else {
1.901     albertel 4550:         my @responses = split(/:/,$reply);
1.515     raeburn  4551:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4552:             foreach my $line (@responses) {
                   4553:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4554:                 $$replyref{$key} = $value;
                   4555:             }
                   4556:         } else {
1.506     raeburn  4557:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4558:             foreach my $line (@responses) {
                   4559:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4560:                 $$replyref{$key} = $value;
                   4561:                 if ($value > 0) {
1.800     albertel 4562:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4563:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4564:                         my $destname = $pathname.'/'.$filename;
                   4565:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4566:                         if ($xml_classlist =~ /^error/) {
                   4567:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4568:                         } else {
1.506     raeburn  4569:                             if ( open(FILE,">$destname") ) {
                   4570:                                 print FILE &unescape($xml_classlist);
                   4571:                                 close(FILE);
1.526     raeburn  4572:                             } else {
                   4573:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4574:                             }
                   4575:                         }
                   4576:                     }
                   4577:                 }
                   4578:             }
                   4579:         }
                   4580:         return 'ok';
                   4581:     }
                   4582:     return 'error';
                   4583: }
                   4584: 
1.242     www      4585: sub get_query_reply {
                   4586:     my $queryid=shift;
1.240     www      4587:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4588:     my $reply='';
                   4589:     for (1..100) {
                   4590: 	sleep 2;
                   4591:         if (-e $replyfile.'.end') {
1.448     albertel 4592: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4593: 		$reply = join('',<$fh>);
                   4594: 		close($fh);
1.240     www      4595: 	   } else { return 'error: reply_file_error'; }
1.242     www      4596:            return &unescape($reply);
                   4597: 	}
1.240     www      4598:     }
1.242     www      4599:     return 'timeout:'.$queryid;
1.240     www      4600: }
                   4601: 
                   4602: sub courselog_query {
1.241     www      4603: #
                   4604: # possible filters:
                   4605: # url: url or symb
                   4606: # username
                   4607: # domain
                   4608: # action: view, submit, grade
                   4609: # start: timestamp
                   4610: # end: timestamp
                   4611: #
1.240     www      4612:     my (%filters)=@_;
1.620     albertel 4613:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4614:     if ($filters{'url'}) {
                   4615: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4616:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4617:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4618:     }
1.620     albertel 4619:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4620:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4621:     return &log_query($cname,$cdom,'courselog',%filters);
                   4622: }
                   4623: 
                   4624: sub userlog_query {
1.858     raeburn  4625: #
                   4626: # possible filters:
                   4627: # action: log check role
                   4628: # start: timestamp
                   4629: # end: timestamp
                   4630: #
1.240     www      4631:     my ($uname,$udom,%filters)=@_;
                   4632:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4633: }
                   4634: 
1.506     raeburn  4635: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4636: 
                   4637: sub auto_run {
1.508     raeburn  4638:     my ($cnum,$cdom) = @_;
1.876     raeburn  4639:     my $response = 0;
                   4640:     my $settings;
                   4641:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4642:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4643:         $settings = $domconfig{'autoenroll'};
                   4644:         if ($settings->{'run'} eq '1') {
                   4645:             $response = 1;
                   4646:         }
                   4647:     } else {
                   4648:         my $homeserver = &homeserver($cnum,$cdom);
                   4649:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4650:     }
1.506     raeburn  4651:     return $response;
                   4652: }
1.776     albertel 4653: 
1.506     raeburn  4654: sub auto_get_sections {
1.508     raeburn  4655:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4656:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4657:     my @secs = ();
1.511     raeburn  4658:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4659:     unless ($response eq 'refused') {
1.901     albertel 4660:         @secs = split(/:/,$response);
1.506     raeburn  4661:     }
                   4662:     return @secs;
                   4663: }
1.776     albertel 4664: 
1.506     raeburn  4665: sub auto_new_course {
1.508     raeburn  4666:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4667:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4668:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4669:     return $response;
                   4670: }
1.776     albertel 4671: 
1.506     raeburn  4672: sub auto_validate_courseID {
1.508     raeburn  4673:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4674:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4675:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4676:     return $response;
                   4677: }
1.776     albertel 4678: 
1.506     raeburn  4679: sub auto_create_password {
1.873     raeburn  4680:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4681:     my ($homeserver,$response);
1.506     raeburn  4682:     my $create_passwd = 0;
                   4683:     my $authchk = '';
1.873     raeburn  4684:     if ($udom =~ /^$match_domain$/) {
                   4685:         $homeserver = &domain($udom,'primary');
                   4686:     }
                   4687:     if ($homeserver eq '') {
                   4688:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4689:             $homeserver = &homeserver($cnum,$cdom);
                   4690:         }
                   4691:     }
                   4692:     if ($homeserver eq '') {
                   4693:         $authchk = 'nodomain';
1.506     raeburn  4694:     } else {
1.873     raeburn  4695:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4696:         if ($response eq 'refused') {
                   4697:             $authchk = 'refused';
                   4698:         } else {
1.901     albertel 4699:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4700:         }
1.506     raeburn  4701:     }
                   4702:     return ($authparam,$create_passwd,$authchk);
                   4703: }
                   4704: 
1.706     raeburn  4705: sub auto_photo_permission {
                   4706:     my ($cnum,$cdom,$students) = @_;
                   4707:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4708:     my ($outcome,$perm_reqd,$conditions) = 
                   4709: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4710:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4711: 	return (undef,undef);
                   4712:     }
1.706     raeburn  4713:     return ($outcome,$perm_reqd,$conditions);
                   4714: }
                   4715: 
                   4716: sub auto_checkphotos {
                   4717:     my ($uname,$udom,$pid) = @_;
                   4718:     my $homeserver = &homeserver($uname,$udom);
                   4719:     my ($result,$resulttype);
                   4720:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4721: 				   &escape($uname).':'.&escape($pid),
                   4722: 				   $homeserver));
1.709     albertel 4723:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4724: 	return (undef,undef);
                   4725:     }
1.706     raeburn  4726:     if ($outcome) {
                   4727:         ($result,$resulttype) = split(/:/,$outcome);
                   4728:     } 
                   4729:     return ($result,$resulttype);
                   4730: }
                   4731: 
                   4732: sub auto_photochoice {
                   4733:     my ($cnum,$cdom) = @_;
                   4734:     my $homeserver = &homeserver($cnum,$cdom);
                   4735:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4736: 						       &escape($cdom),
                   4737: 						       $homeserver)));
1.709     albertel 4738:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4739: 	return (undef,undef);
                   4740:     }
1.706     raeburn  4741:     return ($update,$comment);
                   4742: }
                   4743: 
                   4744: sub auto_photoupdate {
                   4745:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4746:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4747:     my $host=&hostname($homeserver);
1.706     raeburn  4748:     my $cmd = '';
                   4749:     my $maxtries = 1;
1.800     albertel 4750:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4751:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4752:     }
                   4753:     $cmd =~ s/%%$//;
                   4754:     $cmd = &escape($cmd);
                   4755:     my $query = 'institutionalphotos';
                   4756:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4757:     unless ($queryid=~/^\Q$host\E\_/) {
                   4758:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4759:         return 'error: '.$queryid;
                   4760:     }
                   4761:     my $reply = &get_query_reply($queryid);
                   4762:     my $tries = 1;
                   4763:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4764:         $reply = &get_query_reply($queryid);
                   4765:         $tries ++;
                   4766:     }
                   4767:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4768:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4769:     } else {
                   4770:         my @responses = split(/:/,$reply);
                   4771:         my $outcome = shift(@responses); 
                   4772:         foreach my $item (@responses) {
                   4773:             my ($key,$value) = split(/=/,$item);
                   4774:             $$photo{$key} = $value;
                   4775:         }
                   4776:         return $outcome;
                   4777:     }
                   4778:     return 'error';
                   4779: }
                   4780: 
1.521     raeburn  4781: sub auto_instcode_format {
1.793     albertel 4782:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4783: 	$cat_order) = @_;
1.521     raeburn  4784:     my $courses = '';
1.772     raeburn  4785:     my @homeservers;
1.521     raeburn  4786:     if ($caller eq 'global') {
1.841     albertel 4787: 	my %servers = &get_servers($codedom,'library');
                   4788: 	foreach my $tryserver (keys(%servers)) {
                   4789: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4790: 		push(@homeservers,$tryserver);
                   4791: 	    }
1.584     raeburn  4792:         }
1.521     raeburn  4793:     } else {
1.772     raeburn  4794:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4795:     }
1.793     albertel 4796:     foreach my $code (keys(%{$instcodes})) {
                   4797:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4798:     }
                   4799:     chop($courses);
1.772     raeburn  4800:     my $ok_response = 0;
                   4801:     my $response;
                   4802:     while (@homeservers > 0 && $ok_response == 0) {
                   4803:         my $server = shift(@homeservers); 
                   4804:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4805:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4806:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4807: 		split(/:/,$response);
1.772     raeburn  4808:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4809:             push(@{$codetitles},&str2array($codetitles_str));
                   4810:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4811:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4812:             $ok_response = 1;
                   4813:         }
                   4814:     }
                   4815:     if ($ok_response) {
1.521     raeburn  4816:         return 'ok';
1.772     raeburn  4817:     } else {
                   4818:         return $response;
1.521     raeburn  4819:     }
                   4820: }
                   4821: 
1.792     raeburn  4822: sub auto_instcode_defaults {
                   4823:     my ($domain,$returnhash,$code_order) = @_;
                   4824:     my @homeservers;
1.841     albertel 4825: 
                   4826:     my %servers = &get_servers($domain,'library');
                   4827:     foreach my $tryserver (keys(%servers)) {
                   4828: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4829: 	    push(@homeservers,$tryserver);
                   4830: 	}
1.792     raeburn  4831:     }
1.841     albertel 4832: 
1.792     raeburn  4833:     my $response;
1.841     albertel 4834:     foreach my $server (@homeservers) {
1.792     raeburn  4835:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4836:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4837: 	
                   4838: 	foreach my $pair (split(/\&/,$response)) {
                   4839: 	    my ($name,$value)=split(/\=/,$pair);
                   4840: 	    if ($name eq 'code_order') {
                   4841: 		@{$code_order} = split(/\&/,&unescape($value));
                   4842: 	    } else {
                   4843: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4844: 	    }
                   4845: 	}
                   4846: 	return 'ok';
1.792     raeburn  4847:     }
1.841     albertel 4848: 
                   4849:     return $response;
1.792     raeburn  4850: } 
                   4851: 
1.777     albertel 4852: sub auto_validate_class_sec {
1.773     raeburn  4853:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4854:     my $homeserver = &homeserver($cnum,$cdom);
                   4855:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4856:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4857:     return $response;
                   4858: }
                   4859: 
1.679     raeburn  4860: # ------------------------------------------------------- Course Group routines
                   4861: 
                   4862: sub get_coursegroups {
1.809     raeburn  4863:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4864:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4865: }
                   4866: 
1.679     raeburn  4867: sub modify_coursegroup {
                   4868:     my ($cdom,$cnum,$groupsettings) = @_;
                   4869:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4870: }
                   4871: 
1.809     raeburn  4872: sub toggle_coursegroup_status {
                   4873:     my ($cdom,$cnum,$group,$action) = @_;
                   4874:     my ($from_namespace,$to_namespace);
                   4875:     if ($action eq 'delete') {
                   4876:         $from_namespace = 'coursegroups';
                   4877:         $to_namespace = 'deleted_groups';
                   4878:     } else {
                   4879:         $from_namespace = 'deleted_groups';
                   4880:         $to_namespace = 'coursegroups';
                   4881:     }
                   4882:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4883:     if (my $tmp = &error(%curr_group)) {
                   4884:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4885:         return ('read error',$tmp);
                   4886:     } else {
                   4887:         my %savedsettings = %curr_group; 
1.809     raeburn  4888:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4889:         my $deloutcome;
                   4890:         if ($result eq 'ok') {
1.809     raeburn  4891:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4892:         } else {
                   4893:             return ('write error',$result);
                   4894:         }
                   4895:         if ($deloutcome eq 'ok') {
                   4896:             return 'ok';
                   4897:         } else {
                   4898:             return ('delete error',$deloutcome);
                   4899:         }
                   4900:     }
                   4901: }
                   4902: 
1.679     raeburn  4903: sub modify_group_roles {
                   4904:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4905:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4906:     my $role = 'gr/'.&escape($userprivs);
                   4907:     my ($uname,$udom) = split(/:/,$user);
                   4908:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4909:     if ($result eq 'ok') {
                   4910:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4911:     }
1.679     raeburn  4912:     return $result;
                   4913: }
                   4914: 
                   4915: sub modify_coursegroup_membership {
                   4916:     my ($cdom,$cnum,$membership) = @_;
                   4917:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4918:     return $result;
                   4919: }
                   4920: 
1.682     raeburn  4921: sub get_active_groups {
                   4922:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4923:     my $now = time;
                   4924:     my %groups = ();
                   4925:     foreach my $key (keys(%env)) {
1.811     albertel 4926:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4927:             my ($start,$end) = split(/\./,$env{$key});
                   4928:             if (($end!=0) && ($end<$now)) { next; }
                   4929:             if (($start!=0) && ($start>$now)) { next; }
                   4930:             if ($1 eq $cdom && $2 eq $cnum) {
                   4931:                 $groups{$3} = $env{$key} ;
                   4932:             }
                   4933:         }
                   4934:     }
                   4935:     return %groups;
                   4936: }
                   4937: 
1.683     raeburn  4938: sub get_group_membership {
                   4939:     my ($cdom,$cnum,$group) = @_;
                   4940:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4941: }
                   4942: 
                   4943: sub get_users_groups {
                   4944:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4945:     my @usersgroups;
1.683     raeburn  4946:     my $cachetime=1800;
                   4947: 
                   4948:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4949:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4950:     if (defined($cached)) {
1.734     albertel 4951:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4952:     } else {  
                   4953:         $grouplist = '';
1.816     raeburn  4954:         my $courseurl = &courseid_to_courseurl($courseid);
                   4955:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4956:         my $access_end = $env{'course.'.$courseid.
                   4957:                               '.default_enrollment_end_date'};
                   4958:         my $now = time;
                   4959:         foreach my $key (keys(%roleshash)) {
                   4960:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4961:                 my $group = $1;
                   4962:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4963:                     my $start = $2;
                   4964:                     my $end = $1;
                   4965:                     if ($start == -1) { next; } # deleted from group
                   4966:                     if (($start!=0) && ($start>$now)) { next; }
                   4967:                     if (($end!=0) && ($end<$now)) {
                   4968:                         if ($access_end && $access_end < $now) {
                   4969:                             if ($access_end - $end < 86400) {
                   4970:                                 push(@usersgroups,$group);
1.733     raeburn  4971:                             }
                   4972:                         }
1.817     raeburn  4973:                         next;
1.733     raeburn  4974:                     }
1.817     raeburn  4975:                     push(@usersgroups,$group);
1.683     raeburn  4976:                 }
                   4977:             }
                   4978:         }
1.817     raeburn  4979:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4980:         $grouplist = join(':',@usersgroups);
                   4981:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4982:     }
1.733     raeburn  4983:     return @usersgroups;
1.683     raeburn  4984: }
                   4985: 
                   4986: sub devalidate_getgroups_cache {
                   4987:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4988:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4989: 
1.683     raeburn  4990:     my $hashid="$udom:$uname:$courseid";
                   4991:     &devalidate_cache_new('getgroups',$hashid);
                   4992: }
                   4993: 
1.12      www      4994: # ------------------------------------------------------------------ Plain Text
                   4995: 
                   4996: sub plaintext {
1.742     raeburn  4997:     my ($short,$type,$cid) = @_;
1.758     albertel 4998:     if ($short =~ /^cr/) {
                   4999: 	return (split('/',$short))[-1];
                   5000:     }
1.742     raeburn  5001:     if (!defined($cid)) {
                   5002:         $cid = $env{'request.course.id'};
                   5003:     }
                   5004:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5005:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5006:                                           '.plaintext'});
                   5007:     }
                   5008:     my %rolenames = (
                   5009:                       Course => 'std',
                   5010:                       Group => 'alt1',
                   5011:                     );
                   5012:     if (defined($type) && 
                   5013:          defined($rolenames{$type}) && 
                   5014:          defined($prp{$short}{$rolenames{$type}})) {
                   5015:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5016:     } else {
                   5017:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5018:     }
1.12      www      5019: }
                   5020: 
                   5021: # ----------------------------------------------------------------- Assign Role
                   5022: 
                   5023: sub assignrole {
1.357     www      5024:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5025:     my $mrole;
                   5026:     if ($role =~ /^cr\//) {
1.393     www      5027:         my $cwosec=$url;
1.811     albertel 5028:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5029: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5030:            &logthis('Refused custom assignrole: '.
                   5031:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5032: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5033:            return 'refused'; 
                   5034:         }
1.21      www      5035:         $mrole='cr';
1.678     raeburn  5036:     } elsif ($role =~ /^gr\//) {
                   5037:         my $cwogrp=$url;
1.811     albertel 5038:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5039:         unless (&allowed('mdg',$cwogrp)) {
                   5040:             &logthis('Refused group assignrole: '.
                   5041:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5042:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5043:             return 'refused';
                   5044:         }
                   5045:         $mrole='gr';
1.21      www      5046:     } else {
1.82      www      5047:         my $cwosec=$url;
1.811     albertel 5048:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5049:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5050:            &logthis('Refused assignrole: '.
                   5051:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5052: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5053:            return 'refused'; 
                   5054:         }
1.21      www      5055:         $mrole=$role;
                   5056:     }
1.620     albertel 5057:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5058:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5059:     if ($end) { $command.='_'.$end; }
1.21      www      5060:     if ($start) {
                   5061: 	if ($end) { 
1.81      www      5062:            $command.='_'.$start; 
1.21      www      5063:         } else {
1.81      www      5064:            $command.='_0_'.$start;
1.21      www      5065:         }
                   5066:     }
1.739     raeburn  5067:     my $origstart = $start;
                   5068:     my $origend = $end;
1.357     www      5069: # actually delete
                   5070:     if ($deleteflag) {
1.373     www      5071: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5072: # modify command to delete the role
1.620     albertel 5073:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5074:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5075: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5076: # set start and finish to negative values for userrolelog
                   5077:            $start=-1;
                   5078:            $end=-1;
                   5079:         }
                   5080:     }
                   5081: # send command
1.349     www      5082:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5083: # log new user role if status is ok
1.349     www      5084:     if ($answer eq 'ok') {
1.663     raeburn  5085: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5086: # for course roles, perform group memberships changes triggered by role change.
                   5087:         unless ($role =~ /^gr/) {
                   5088:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5089:                                              $origstart);
                   5090:         }
1.349     www      5091:     }
                   5092:     return $answer;
1.169     harris41 5093: }
                   5094: 
                   5095: # -------------------------------------------------- Modify user authentication
1.197     www      5096: # Overrides without validation
                   5097: 
1.169     harris41 5098: sub modifyuserauth {
                   5099:     my ($udom,$uname,$umode,$upass)=@_;
                   5100:     my $uhome=&homeserver($uname,$udom);
1.197     www      5101:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5102:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5103:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5104:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5105:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5106: 		     &escape($upass),$uhome);
1.620     albertel 5107:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5108:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5109:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5110:     &log($udom,,$uname,$uhome,
1.620     albertel 5111:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5112:                                      $env{'user.name'}.', '.$umode.
1.197     www      5113:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5114:     unless ($reply eq 'ok') {
1.197     www      5115:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5116: 	return 'error: '.$reply;
                   5117:     }   
1.170     harris41 5118:     return 'ok';
1.80      www      5119: }
                   5120: 
1.81      www      5121: # --------------------------------------------------------------- Modify a user
1.80      www      5122: 
1.81      www      5123: sub modifyuser {
1.206     matthew  5124:     my ($udom,    $uname, $uid,
                   5125:         $umode,   $upass, $first,
                   5126:         $middle,  $last,  $gene,
1.387     www      5127:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5128:     $udom= &LONCAPA::clean_domain($udom);
                   5129:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5130:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5131:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5132: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5133:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5134:                                      ' desiredhome not specified'). 
1.620     albertel 5135:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5136:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5137:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5138: # ----------------------------------------------------------------- Create User
1.406     albertel 5139:     if (($uhome eq 'no_host') && 
                   5140: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5141:         my $unhome='';
1.844     albertel 5142:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5143:             $unhome = $desiredhome;
1.620     albertel 5144: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5145: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5146:         } else { # load balancing routine for determining $unhome
1.81      www      5147:             my $loadm=10000000;
1.841     albertel 5148: 	    my %servers = &get_servers($udom,'library');
                   5149: 	    foreach my $tryserver (keys(%servers)) {
                   5150: 		my $answer=reply('load',$tryserver);
                   5151: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5152: 		    $loadm=$answer;
                   5153: 		    $unhome=$tryserver;
                   5154: 		}
1.80      www      5155: 	    }
                   5156:         }
                   5157:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5158: 	    return 'error: unable to find a home server for '.$uname.
                   5159:                    ' in domain '.$udom;
1.80      www      5160:         }
                   5161:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5162:                          &escape($upass),$unhome);
                   5163: 	unless ($reply eq 'ok') {
                   5164:             return 'error: '.$reply;
                   5165:         }   
1.230     stredwic 5166:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5167:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5168: 	    return 'error: unable verify users home machine.';
1.80      www      5169:         }
1.209     matthew  5170:     }   # End of creation of new user
1.80      www      5171: # ---------------------------------------------------------------------- Add ID
                   5172:     if ($uid) {
                   5173:        $uid=~tr/A-Z/a-z/;
                   5174:        my %uidhash=&idrget($udom,$uname);
1.196     www      5175:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5176:          && (!$forceid)) {
1.80      www      5177: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5178: 	      return 'error: user id "'.$uid.'" does not match '.
                   5179:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5180:           }
                   5181:        } else {
                   5182: 	  &idput($udom,($uname => $uid));
                   5183:        }
                   5184:     }
                   5185: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5186:     my @tmp=&get('environment',
1.899     raeburn  5187: 		   ['firstname','middlename','lastname','generation','id',
                   5188:                     'permanentemail'],
1.134     albertel 5189: 		   $udom,$uname);
1.313     matthew  5190:     my %names;
                   5191:     if ($tmp[0] =~ m/^error:.*/) { 
                   5192:         %names=(); 
                   5193:     } else {
                   5194:         %names = @tmp;
                   5195:     }
1.388     www      5196: #
                   5197: # Make sure to not trash student environment if instructor does not bother
                   5198: # to supply name and email information
                   5199: #
                   5200:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5201:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5202:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5203:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5204:     if ($email) {
                   5205:        $email=~s/[^\w\@\.\-\,]//gs;
                   5206:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5207: 			   $names{'critnotification'} = $email;
                   5208: 			   $names{'permanentemail'} = $email; }
                   5209:     }
1.899     raeburn  5210:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5211:     my $reply = &put('environment', \%names, $udom,$uname);
                   5212:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5213:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5214:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5215:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5216:              $umode.', '.$first.', '.$middle.', '.
                   5217: 	     $last.', '.$gene.' by '.
1.620     albertel 5218:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5219:     return 'ok';
1.80      www      5220: }
                   5221: 
1.81      www      5222: # -------------------------------------------------------------- Modify student
1.80      www      5223: 
1.81      www      5224: sub modifystudent {
                   5225:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5226:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5227:     if (!$cid) {
1.620     albertel 5228: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5229: 	    return 'not_in_class';
                   5230: 	}
1.80      www      5231:     }
                   5232: # --------------------------------------------------------------- Make the user
1.81      www      5233:     my $reply=&modifyuser
1.209     matthew  5234: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5235:          $desiredhome,$email);
1.80      www      5236:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5237:     # This will cause &modify_student_enrollment to get the uid from the
                   5238:     # students environment
                   5239:     $uid = undef if (!$forceid);
1.455     albertel 5240:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5241: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5242:     return $reply;
                   5243: }
                   5244: 
                   5245: sub modify_student_enrollment {
1.515     raeburn  5246:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5247:     my ($cdom,$cnum,$chome);
                   5248:     if (!$cid) {
1.620     albertel 5249: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5250: 	    return 'not_in_class';
                   5251: 	}
1.620     albertel 5252: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5253: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5254:     } else {
                   5255: 	($cdom,$cnum)=split(/_/,$cid);
                   5256:     }
1.620     albertel 5257:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5258:     if (!$chome) {
1.457     raeburn  5259: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5260:     }
1.455     albertel 5261:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5262:     # Make sure the user exists
1.81      www      5263:     my $uhome=&homeserver($uname,$udom);
                   5264:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5265: 	return 'error: no such user';
                   5266:     }
1.297     matthew  5267:     # Get student data if we were not given enough information
                   5268:     if (!defined($first)  || $first  eq '' || 
                   5269:         !defined($last)   || $last   eq '' || 
                   5270:         !defined($uid)    || $uid    eq '' || 
                   5271:         !defined($middle) || $middle eq '' || 
                   5272:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5273:         # They did not supply us with enough data to enroll the student, so
                   5274:         # we need to pick up more information.
1.297     matthew  5275:         my %tmp = &get('environment',
1.294     matthew  5276:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5277:                        ,$udom,$uname);
                   5278: 
1.800     albertel 5279:         #foreach my $key (keys(%tmp)) {
                   5280:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5281:         #}
1.294     matthew  5282:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5283:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5284:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5285:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5286:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5287:     }
1.556     albertel 5288:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5289:     my $reply=cput('classlist',
                   5290: 		   {"$uname:$udom" => 
1.515     raeburn  5291: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5292: 		   $cdom,$cnum);
1.81      www      5293:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5294: 	return 'error: '.$reply;
1.652     albertel 5295:     } else {
                   5296: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5297:     }
1.297     matthew  5298:     # Add student role to user
1.83      www      5299:     my $uurl='/'.$cid;
1.81      www      5300:     $uurl=~s/\_/\//g;
                   5301:     if ($usec) {
                   5302: 	$uurl.='/'.$usec;
                   5303:     }
                   5304:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5305: }
                   5306: 
1.556     albertel 5307: sub format_name {
                   5308:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5309:     my $name;
                   5310:     if ($first ne 'lastname') {
                   5311: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5312:     } else {
                   5313: 	if ($lastname=~/\S/) {
                   5314: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5315: 	    $name=~s/\s+,/,/;
                   5316: 	} else {
                   5317: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5318: 	}
                   5319:     }
                   5320:     $name=~s/^\s+//;
                   5321:     $name=~s/\s+$//;
                   5322:     $name=~s/\s+/ /g;
                   5323:     return $name;
                   5324: }
                   5325: 
1.84      www      5326: # ------------------------------------------------- Write to course preferences
                   5327: 
                   5328: sub writecoursepref {
                   5329:     my ($courseid,%prefs)=@_;
                   5330:     $courseid=~s/^\///;
                   5331:     $courseid=~s/\_/\//g;
                   5332:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5333:     my $chome=homeserver($cnum,$cdomain);
                   5334:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5335: 	return 'error: no such course';
                   5336:     }
                   5337:     my $cstring='';
1.800     albertel 5338:     foreach my $pref (keys(%prefs)) {
                   5339: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5340:     }
1.84      www      5341:     $cstring=~s/\&$//;
                   5342:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5343: }
                   5344: 
                   5345: # ---------------------------------------------------------- Make/modify course
                   5346: 
                   5347: sub createcourse {
1.741     raeburn  5348:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5349:         $course_owner,$crstype)=@_;
1.84      www      5350:     $url=&declutter($url);
                   5351:     my $cid='';
1.264     matthew  5352:     unless (&allowed('ccc',$udom)) {
1.84      www      5353:         return 'refused';
                   5354:     }
                   5355: # ------------------------------------------------------------------- Create ID
1.674     www      5356:    my $uname=int(1+rand(9)).
                   5357:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5358:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5359:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5360: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5361:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5362:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5363:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5364:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5365:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5366:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5367:            return 'error: unable to generate unique course-ID';
                   5368:        } 
                   5369:    }
1.264     matthew  5370: # ------------------------------------------------ Check supplied server name
1.620     albertel 5371:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5372:     if (! &is_library($course_server)) {
1.264     matthew  5373:         return 'error:bad server name '.$course_server;
                   5374:     }
1.84      www      5375: # ------------------------------------------------------------- Make the course
                   5376:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5377:                       $course_server);
1.84      www      5378:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5379:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5380:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5381: 	return 'error: no such course';
                   5382:     }
1.271     www      5383: # ----------------------------------------------------------------- Course made
1.516     raeburn  5384: # log existence
                   5385:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5386:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5387:                   &escape($crstype),$uhome);
1.358     www      5388:     &flushcourselogs();
                   5389: # set toplevel url
1.271     www      5390:     my $topurl=$url;
                   5391:     unless ($nonstandard) {
                   5392: # ------------------------------------------ For standard courses, make top url
                   5393:         my $mapurl=&clutter($url);
1.278     www      5394:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5395:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5396: <map>
                   5397: <resource id="1" type="start"></resource>
                   5398: <resource id="2" src="$mapurl"></resource>
                   5399: <resource id="3" type="finish"></resource>
                   5400: <link index="1" from="1" to="2"></link>
                   5401: <link index="2" from="2" to="3"></link>
                   5402: </map>
                   5403: ENDINITMAP
                   5404:         $topurl=&declutter(
1.638     albertel 5405:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5406:                           );
                   5407:     }
                   5408: # ----------------------------------------------------------- Write preferences
1.84      www      5409:     &writecoursepref($udom.'_'.$uname,
                   5410:                      ('description' => $description,
1.271     www      5411:                       'url'         => $topurl));
1.84      www      5412:     return '/'.$udom.'/'.$uname;
                   5413: }
                   5414: 
1.813     albertel 5415: sub is_course {
                   5416:     my ($cdom,$cnum) = @_;
                   5417:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5418: 				undef,'.');
                   5419:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5420:         return 1;
                   5421:     }
                   5422:     return 0;
                   5423: }
                   5424: 
1.21      www      5425: # ---------------------------------------------------------- Assign Custom Role
                   5426: 
                   5427: sub assigncustomrole {
1.357     www      5428:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5429:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5430:                        $end,$start,$deleteflag);
1.21      www      5431: }
                   5432: 
                   5433: # ----------------------------------------------------------------- Revoke Role
                   5434: 
                   5435: sub revokerole {
1.357     www      5436:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5437:     my $now=time;
1.357     www      5438:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5439: }
                   5440: 
                   5441: # ---------------------------------------------------------- Revoke Custom Role
                   5442: 
                   5443: sub revokecustomrole {
1.357     www      5444:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5445:     my $now=time;
1.357     www      5446:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5447:            $deleteflag);
1.17      www      5448: }
                   5449: 
1.533     banghart 5450: # ------------------------------------------------------------ Disk usage
1.535     albertel 5451: sub diskusage {
1.533     banghart 5452:     my ($udom,$uname,$directoryRoot)=@_;
                   5453:     $directoryRoot =~ s/\/$//;
1.535     albertel 5454:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5455:     return $listing;
1.512     banghart 5456: }
                   5457: 
1.566     banghart 5458: sub is_locked {
                   5459:     my ($file_name, $domain, $user) = @_;
                   5460:     my @check;
                   5461:     my $is_locked;
                   5462:     push @check, $file_name;
1.613     albertel 5463:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5464: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5465:     my ($tmp)=keys(%locked);
                   5466:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5467:     
1.566     banghart 5468:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5469:         $is_locked = 'false';
                   5470:         foreach my $entry (@{$locked{$file_name}}) {
                   5471:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5472:                $is_locked = 'true';
                   5473:                last;
1.745     raeburn  5474:            }
                   5475:        }
1.566     banghart 5476:     } else {
                   5477:         $is_locked = 'false';
                   5478:     }
                   5479: }
                   5480: 
1.759     albertel 5481: sub declutter_portfile {
                   5482:     my ($file) = @_;
1.833     albertel 5483:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5484:     return $file;
                   5485: }
                   5486: 
1.559     banghart 5487: # ------------------------------------------------------------- Mark as Read Only
                   5488: 
                   5489: sub mark_as_readonly {
                   5490:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5491:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5492:     my ($tmp)=keys(%current_permissions);
                   5493:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5494:     foreach my $file (@{$files}) {
1.759     albertel 5495: 	$file = &declutter_portfile($file);
1.561     banghart 5496:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5497:     }
1.613     albertel 5498:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5499:     return;
                   5500: }
                   5501: 
1.572     banghart 5502: # ------------------------------------------------------------Save Selected Files
                   5503: 
                   5504: sub save_selected_files {
                   5505:     my ($user, $path, @files) = @_;
                   5506:     my $filename = $user."savedfiles";
1.573     banghart 5507:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5508:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5509:     foreach my $file (@files) {
1.620     albertel 5510:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5511:     }
                   5512:     foreach my $file (@other_files) {
1.574     banghart 5513:         print (OUT $file."\n");
1.572     banghart 5514:     }
1.574     banghart 5515:     close (OUT);
1.572     banghart 5516:     return 'ok';
                   5517: }
                   5518: 
1.574     banghart 5519: sub clear_selected_files {
                   5520:     my ($user) = @_;
                   5521:     my $filename = $user."savedfiles";
                   5522:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5523:     print (OUT undef);
                   5524:     close (OUT);
                   5525:     return ("ok");    
                   5526: }
                   5527: 
1.572     banghart 5528: sub files_in_path {
                   5529:     my ($user, $path) = @_;
                   5530:     my $filename = $user."savedfiles";
                   5531:     my %return_files;
1.574     banghart 5532:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5533:     while (my $line_in = <IN>) {
1.574     banghart 5534:         chomp ($line_in);
                   5535:         my @paths_and_file = split (m!/!, $line_in);
                   5536:         my $file_part = pop (@paths_and_file);
                   5537:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5538:         $path_part.='/';
                   5539:         my $path_and_file = $path_part.$file_part;
                   5540:         if ($path_part eq $path) {
                   5541:             $return_files{$file_part}= 'selected';
                   5542:         }
                   5543:     }
1.574     banghart 5544:     close (IN);
                   5545:     return (\%return_files);
1.572     banghart 5546: }
                   5547: 
                   5548: # called in portfolio select mode, to show files selected NOT in current directory
                   5549: sub files_not_in_path {
                   5550:     my ($user, $path) = @_;
                   5551:     my $filename = $user."savedfiles";
                   5552:     my @return_files;
                   5553:     my $path_part;
1.800     albertel 5554:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5555:     while (my $line = <IN>) {
1.572     banghart 5556:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5557:         my @paths_and_file = split(m|/|, $line);
                   5558:         my $file_part = pop(@paths_and_file);
                   5559:         chomp($file_part);
                   5560:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5561:         $path_part .= '/';
                   5562:         my $path_and_file = $path_part.$file_part;
                   5563:         if ($path_part ne $path) {
1.800     albertel 5564:             push(@return_files, ($path_and_file));
1.572     banghart 5565:         }
                   5566:     }
1.800     albertel 5567:     close(OUT);
1.574     banghart 5568:     return (@return_files);
1.572     banghart 5569: }
                   5570: 
1.745     raeburn  5571: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5572: 
1.745     raeburn  5573: sub get_portfile_permissions {
                   5574:     my ($domain,$user) = @_;
1.613     albertel 5575:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5576:     my ($tmp)=keys(%current_permissions);
                   5577:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5578:     return \%current_permissions;
                   5579: }
                   5580: 
                   5581: #---------------------------------------------Get portfolio file access controls
                   5582: 
1.749     raeburn  5583: sub get_access_controls {
1.745     raeburn  5584:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5585:     my %access;
                   5586:     my $real_file = $file;
                   5587:     $file =~ s/\.meta$//;
1.745     raeburn  5588:     if (defined($file)) {
1.749     raeburn  5589:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5590:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5591:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5592:             }
                   5593:         }
1.745     raeburn  5594:     } else {
1.749     raeburn  5595:         foreach my $key (keys(%{$current_permissions})) {
                   5596:             if ($key =~ /\0accesscontrol$/) {
                   5597:                 if (defined($group)) {
                   5598:                     if ($key !~ m-^\Q$group\E/-) {
                   5599:                         next;
                   5600:                     }
                   5601:                 }
                   5602:                 my ($fullpath) = split(/\0/,$key);
                   5603:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5604:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5605:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5606:                     }
                   5607:                 }
                   5608:             }
                   5609:         }
                   5610:     }
                   5611:     return %access;
                   5612: }
                   5613: 
                   5614: sub modify_access_controls {
                   5615:     my ($file_name,$changes,$domain,$user)=@_;
                   5616:     my ($outcome,$deloutcome);
                   5617:     my %store_permissions;
                   5618:     my %new_values;
                   5619:     my %new_control;
                   5620:     my %translation;
                   5621:     my @deletions = ();
                   5622:     my $now = time;
                   5623:     if (exists($$changes{'activate'})) {
                   5624:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5625:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5626:             my $numnew = scalar(@newitems);
                   5627:             for (my $i=0; $i<$numnew; $i++) {
                   5628:                 my $newkey = $newitems[$i];
                   5629:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5630:                 if ($newkey =~ /^\d+:/) { 
                   5631:                     $newkey =~ s/^(\d+)/$newid/;
                   5632:                     $translation{$1} = $newid;
                   5633:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5634:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5635:                     $translation{$1} = $newid;
                   5636:                 }
1.749     raeburn  5637:                 $new_values{$file_name."\0".$newkey} = 
                   5638:                                           $$changes{'activate'}{$newitems[$i]};
                   5639:                 $new_control{$newkey} = $now;
                   5640:             }
                   5641:         }
                   5642:     }
                   5643:     my %todelete;
                   5644:     my %changed_items;
                   5645:     foreach my $action ('delete','update') {
                   5646:         if (exists($$changes{$action})) {
                   5647:             if (ref($$changes{$action}) eq 'HASH') {
                   5648:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5649:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5650:                     if ($action eq 'delete') { 
                   5651:                         $todelete{$itemnum} = 1;
                   5652:                     } else {
                   5653:                         $changed_items{$itemnum} = $key;
                   5654:                     }
                   5655:                 }
1.745     raeburn  5656:             }
                   5657:         }
1.749     raeburn  5658:     }
                   5659:     # get lock on access controls for file.
                   5660:     my $lockhash = {
                   5661:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5662:                                                        ':'.$env{'user.domain'},
                   5663:                    }; 
                   5664:     my $tries = 0;
                   5665:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5666:    
                   5667:     while (($gotlock ne 'ok') && $tries <3) {
                   5668:         $tries ++;
                   5669:         sleep 1;
                   5670:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5671:     }
                   5672:     if ($gotlock eq 'ok') {
                   5673:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5674:         my ($tmp)=keys(%curr_permissions);
                   5675:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5676:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5677:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5678:             if (ref($curr_controls) eq 'HASH') {
                   5679:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5680:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5681:                     if (defined($todelete{$itemnum})) {
                   5682:                         push(@deletions,$file_name."\0".$control_item);
                   5683:                     } else {
                   5684:                         if (defined($changed_items{$itemnum})) {
                   5685:                             $new_control{$changed_items{$itemnum}} = $now;
                   5686:                             push(@deletions,$file_name."\0".$control_item);
                   5687:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5688:                         } else {
                   5689:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5690:                         }
                   5691:                     }
1.745     raeburn  5692:                 }
                   5693:             }
                   5694:         }
1.749     raeburn  5695:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5696:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5697:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5698:         #  remove lock
                   5699:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5700:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5701:         my ($file,$group);
                   5702:         if (&is_course($domain,$user)) {
                   5703:             ($group,$file) = split(/\//,$file_name,2);
                   5704:         } else {
                   5705:             $file = $file_name;
                   5706:         }
                   5707:         my $sqlresult =
                   5708:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5709:                                     $group);
1.749     raeburn  5710:     } else {
                   5711:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5712:     }
1.749     raeburn  5713:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5714: }
                   5715: 
1.827     raeburn  5716: sub make_public_indefinitely {
                   5717:     my ($requrl) = @_;
                   5718:     my $now = time;
                   5719:     my $action = 'activate';
                   5720:     my $aclnum = 0;
                   5721:     if (&is_portfolio_url($requrl)) {
                   5722:         my (undef,$udom,$unum,$file_name,$group) =
                   5723:             &parse_portfolio_url($requrl);
                   5724:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5725:         my %access_controls = &get_access_controls($current_perms,
                   5726:                                                    $group,$file_name);
                   5727:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5728:             my ($num,$scope,$end,$start) = 
                   5729:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5730:             if ($scope eq 'public') {
                   5731:                 if ($start <= $now && $end == 0) {
                   5732:                     $action = 'none';
                   5733:                 } else {
                   5734:                     $action = 'update';
                   5735:                     $aclnum = $num;
                   5736:                 }
                   5737:                 last;
                   5738:             }
                   5739:         }
                   5740:         if ($action eq 'none') {
                   5741:              return 'ok';
                   5742:         } else {
                   5743:             my %changes;
                   5744:             my $newend = 0;
                   5745:             my $newstart = $now;
                   5746:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5747:             $changes{$action}{$newkey} = {
                   5748:                 type => 'public',
                   5749:                 time => {
                   5750:                     start => $newstart,
                   5751:                     end   => $newend,
                   5752:                 },
                   5753:             };
                   5754:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5755:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5756:             return $outcome;
                   5757:         }
                   5758:     } else {
                   5759:         return 'invalid';
                   5760:     }
                   5761: }
                   5762: 
1.745     raeburn  5763: #------------------------------------------------------Get Marked as Read Only
                   5764: 
                   5765: sub get_marked_as_readonly {
                   5766:     my ($domain,$user,$what,$group) = @_;
                   5767:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5768:     my @readonly_files;
1.629     banghart 5769:     my $cmp1=$what;
                   5770:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5771:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5772:         if (defined($group)) {
                   5773:             if ($file_name !~ m-^\Q$group\E/-) {
                   5774:                 next;
                   5775:             }
                   5776:         }
1.561     banghart 5777:         if (ref($value) eq "ARRAY"){
                   5778:             foreach my $stored_what (@{$value}) {
1.629     banghart 5779:                 my $cmp2=$stored_what;
1.759     albertel 5780:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5781:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5782:                 }
1.629     banghart 5783:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5784:                     push(@readonly_files, $file_name);
1.745     raeburn  5785:                     last;
1.563     banghart 5786:                 } elsif (!defined($what)) {
                   5787:                     push(@readonly_files, $file_name);
1.745     raeburn  5788:                     last;
1.561     banghart 5789:                 }
                   5790:             }
1.745     raeburn  5791:         }
1.561     banghart 5792:     }
                   5793:     return @readonly_files;
                   5794: }
1.577     banghart 5795: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5796: 
1.577     banghart 5797: sub get_marked_as_readonly_hash {
1.745     raeburn  5798:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5799:     my %readonly_files;
1.745     raeburn  5800:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5801:         if (defined($group)) {
                   5802:             if ($file_name !~ m-^\Q$group\E/-) {
                   5803:                 next;
                   5804:             }
                   5805:         }
1.577     banghart 5806:         if (ref($value) eq "ARRAY"){
                   5807:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5808:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5809:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5810:                         if ($lock_descriptor eq 'graded') {
                   5811:                             $readonly_files{$file_name} = 'graded';
                   5812:                         } elsif ($lock_descriptor eq 'handback') {
                   5813:                             $readonly_files{$file_name} = 'handback';
                   5814:                         } else {
                   5815:                             if (!exists($readonly_files{$file_name})) {
                   5816:                                 $readonly_files{$file_name} = 'locked';
                   5817:                             }
                   5818:                         }
1.745     raeburn  5819:                     }
1.750     banghart 5820:                 } 
1.577     banghart 5821:             }
                   5822:         } 
                   5823:     }
                   5824:     return %readonly_files;
                   5825: }
1.559     banghart 5826: # ------------------------------------------------------------ Unmark as Read Only
                   5827: 
                   5828: sub unmark_as_readonly {
1.629     banghart 5829:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5830:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5831:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5832:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5833:     my $symb_crs = $what;
                   5834:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5835:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5836:     my ($tmp)=keys(%current_permissions);
                   5837:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5838:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5839:     foreach my $file (@readonly_files) {
1.759     albertel 5840: 	my $clean_file = &declutter_portfile($file);
                   5841: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5842: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5843:         my @new_locks;
                   5844:         my @del_keys;
                   5845:         if (ref($current_locks) eq "ARRAY"){
                   5846:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5847:                 my $compare=$locker;
1.749     raeburn  5848:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5849:                     $compare=join('',@{$locker});
1.746     raeburn  5850:                     if ($compare ne $symb_crs) {
                   5851:                         push(@new_locks, $locker);
                   5852:                     }
1.563     banghart 5853:                 }
                   5854:             }
1.650     albertel 5855:             if (scalar(@new_locks) > 0) {
1.563     banghart 5856:                 $current_permissions{$file} = \@new_locks;
                   5857:             } else {
                   5858:                 push(@del_keys, $file);
1.613     albertel 5859:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5860:                 delete($current_permissions{$file});
1.563     banghart 5861:             }
                   5862:         }
1.561     banghart 5863:     }
1.613     albertel 5864:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5865:     return;
                   5866: }
1.512     banghart 5867: 
1.17      www      5868: # ------------------------------------------------------------ Directory lister
                   5869: 
                   5870: sub dirlist {
1.253     stredwic 5871:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5872: 
1.18      www      5873:     $uri=~s/^\///;
                   5874:     $uri=~s/\/$//;
1.253     stredwic 5875:     my ($udom, $uname);
                   5876:     (undef,$udom,$uname)=split(/\//,$uri);
                   5877:     if(defined($userdomain)) {
                   5878:         $udom = $userdomain;
                   5879:     }
                   5880:     if(defined($username)) {
                   5881:         $uname = $username;
                   5882:     }
                   5883: 
                   5884:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5885:     if(defined($alternateDirectoryRoot)) {
                   5886:         $dirRoot = $alternateDirectoryRoot;
                   5887:         $dirRoot =~ s/\/$//;
1.751     banghart 5888:     }
1.253     stredwic 5889: 
                   5890:     if($udom) {
                   5891:         if($uname) {
1.800     albertel 5892:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5893: 				 &homeserver($uname,$udom));
1.605     matthew  5894:             my @listing_results;
                   5895:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5896:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5897: 				  &homeserver($uname,$udom));
1.605     matthew  5898:                 @listing_results = split(/:/,$listing);
                   5899:             } else {
                   5900:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5901:             }
                   5902:             return @listing_results;
1.253     stredwic 5903:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5904:             my %allusers;
1.841     albertel 5905: 	    my %servers = &get_servers($udom,'library');
                   5906: 	    foreach my $tryserver (keys(%servers)) {
                   5907: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5908: 				     $udom, $tryserver);
                   5909: 		my @listing_results;
                   5910: 		if ($listing eq 'unknown_cmd') {
                   5911: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5912: 				      $udom, $tryserver);
                   5913: 		    @listing_results = split(/:/,$listing);
                   5914: 		} else {
                   5915: 		    @listing_results =
                   5916: 			map { &unescape($_); } split(/:/,$listing);
                   5917: 		}
                   5918: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5919: 		    $listing_results[0] ne 'empty'       &&
                   5920: 		    $listing_results[0] ne 'con_lost') {
                   5921: 		    foreach my $line (@listing_results) {
                   5922: 			my ($entry) = split(/&/,$line,2);
                   5923: 			$allusers{$entry} = 1;
                   5924: 		    }
                   5925: 		}
1.253     stredwic 5926:             }
                   5927:             my $alluserstr='';
1.800     albertel 5928:             foreach my $user (sort(keys(%allusers))) {
                   5929:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5930:             }
                   5931:             $alluserstr=~s/:$//;
                   5932:             return split(/:/,$alluserstr);
                   5933:         } else {
1.800     albertel 5934:             return ('missing user name');
1.253     stredwic 5935:         }
                   5936:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5937:         my @all_domains = sort(&all_domains());
                   5938:          foreach my $domain (@all_domains) {
                   5939:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5940:          }
                   5941:          return @all_domains;
                   5942:      } else {
1.800     albertel 5943:         return ('missing domain');
1.275     stredwic 5944:     }
                   5945: }
                   5946: 
                   5947: # --------------------------------------------- GetFileTimestamp
                   5948: # This function utilizes dirlist and returns the date stamp for
                   5949: # when it was last modified.  It will also return an error of -1
                   5950: # if an error occurs
                   5951: 
1.410     matthew  5952: ##
                   5953: ## FIXME: This subroutine assumes its caller knows something about the
                   5954: ## directory structure of the home server for the student ($root).
                   5955: ## Not a good assumption to make.  Since this is for looking up files
                   5956: ## in user directories, the full path should be constructed by lond, not
                   5957: ## whatever machine we request data from.
                   5958: ##
1.275     stredwic 5959: sub GetFileTimestamp {
                   5960:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5961:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5962:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5963:     my $subdir=$studentName.'__';
                   5964:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5965:     my $proname="$studentDomain/$subdir/$studentName";
                   5966:     $proname .= '/'.$filename;
1.375     matthew  5967:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5968:                                               $studentName, $root);
1.275     stredwic 5969:     my @stats = split('&', $fileStat);
                   5970:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5971:         # @stats contains first the filename, then the stat output
                   5972:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5973:     } else {
                   5974:         return -1;
1.253     stredwic 5975:     }
1.26      www      5976: }
                   5977: 
1.712     albertel 5978: sub stat_file {
                   5979:     my ($uri) = @_;
1.787     albertel 5980:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5981: 
1.712     albertel 5982:     my ($udom,$uname,$file,$dir);
                   5983:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5984: 	($udom,$uname,$file) =
1.811     albertel 5985: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5986: 	$file = 'userfiles/'.$file;
1.740     www      5987: 	$dir = &propath($udom,$uname);
1.712     albertel 5988:     }
                   5989:     if ($uri =~ m-^/res/-) {
                   5990: 	($udom,$uname) = 
1.807     albertel 5991: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5992: 	$file = $uri;
                   5993:     }
                   5994: 
                   5995:     if (!$udom || !$uname || !$file) {
                   5996: 	# unable to handle the uri
                   5997: 	return ();
                   5998:     }
                   5999: 
                   6000:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6001:     my @stats = split('&', $result);
1.721     banghart 6002:     
1.712     albertel 6003:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6004: 	shift(@stats); #filename is first
                   6005: 	return @stats;
                   6006:     }
                   6007:     return ();
                   6008: }
                   6009: 
1.26      www      6010: # -------------------------------------------------------- Value of a Condition
                   6011: 
1.713     albertel 6012: # gets the value of a specific preevaluated condition
                   6013: #    stored in the string  $env{user.state.<cid>}
                   6014: # or looks up a condition reference in the bighash and if if hasn't
                   6015: # already been evaluated recurses into docondval to get the value of
                   6016: # the condition, then memoizing it to 
                   6017: #   $env{user.state.<cid>.<condition>}
1.40      www      6018: sub directcondval {
                   6019:     my $number=shift;
1.620     albertel 6020:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6021: 	&Apache::lonuserstate::evalstate();
                   6022:     }
1.713     albertel 6023:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6024: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6025:     } elsif ($number =~ /^_/) {
                   6026: 	my $sub_condition;
                   6027: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6028: 		&GDBM_READER(),0640)) {
                   6029: 	    $sub_condition=$bighash{'conditions'.$number};
                   6030: 	    untie(%bighash);
                   6031: 	}
                   6032: 	my $value = &docondval($sub_condition);
                   6033: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6034: 	return $value;
                   6035:     }
1.620     albertel 6036:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6037:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6038:     } else {
                   6039:        return 2;
                   6040:     }
                   6041: }
                   6042: 
1.713     albertel 6043: # get the collection of conditions for this resource
1.26      www      6044: sub condval {
                   6045:     my $condidx=shift;
1.54      www      6046:     my $allpathcond='';
1.713     albertel 6047:     foreach my $cond (split(/\|/,$condidx)) {
                   6048: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6049: 	    $allpathcond.=
                   6050: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6051: 	}
1.191     harris41 6052:     }
1.54      www      6053:     $allpathcond=~s/\|$//;
1.713     albertel 6054:     return &docondval($allpathcond);
                   6055: }
                   6056: 
                   6057: #evaluates an expression of conditions
                   6058: sub docondval {
                   6059:     my ($allpathcond) = @_;
                   6060:     my $result=0;
                   6061:     if ($env{'request.course.id'}
                   6062: 	&& defined($allpathcond)) {
                   6063: 	my $operand='|';
                   6064: 	my @stack;
                   6065: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6066: 	    if ($chunk eq '(') {
                   6067: 		push @stack,($operand,$result);
                   6068: 	    } elsif ($chunk eq ')') {
                   6069: 		my $before=pop @stack;
                   6070: 		if (pop @stack eq '&') {
                   6071: 		    $result=$result>$before?$before:$result;
                   6072: 		} else {
                   6073: 		    $result=$result>$before?$result:$before;
                   6074: 		}
                   6075: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6076: 		$operand=$chunk;
                   6077: 	    } else {
                   6078: 		my $new=directcondval($chunk);
                   6079: 		if ($operand eq '&') {
                   6080: 		    $result=$result>$new?$new:$result;
                   6081: 		} else {
                   6082: 		    $result=$result>$new?$result:$new;
                   6083: 		}
                   6084: 	    }
                   6085: 	}
1.26      www      6086:     }
                   6087:     return $result;
1.421     albertel 6088: }
                   6089: 
                   6090: # ---------------------------------------------------- Devalidate courseresdata
                   6091: 
                   6092: sub devalidatecourseresdata {
                   6093:     my ($coursenum,$coursedomain)=@_;
                   6094:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6095:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6096: }
                   6097: 
1.763     www      6098: 
1.200     www      6099: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6100: #
                   6101: #  Parameters:
                   6102: #      $coursenum    - Number of the course.
                   6103: #      $coursedomain - Domain at which the course was created.
                   6104: #  Returns:
                   6105: #     A hash of the course parameters along (I think) with timestamps
                   6106: #     and version info.
1.877     foxr     6107: 
1.624     albertel 6108: sub get_courseresdata {
                   6109:     my ($coursenum,$coursedomain)=@_;
1.200     www      6110:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6111:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6112:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6113:     my %dumpreply;
1.417     albertel 6114:     unless (defined($cached)) {
1.624     albertel 6115: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6116: 	$result=\%dumpreply;
1.251     albertel 6117: 	my ($tmp) = keys(%dumpreply);
                   6118: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6119: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6120: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6121: 	    return $tmp;
1.416     albertel 6122: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6123: 	    $result=undef;
1.599     albertel 6124: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6125: 	}
                   6126:     }
1.624     albertel 6127:     return $result;
                   6128: }
                   6129: 
1.633     albertel 6130: sub devalidateuserresdata {
                   6131:     my ($uname,$udom)=@_;
                   6132:     my $hashid="$udom:$uname";
                   6133:     &devalidate_cache_new('userres',$hashid);
                   6134: }
                   6135: 
1.624     albertel 6136: sub get_userresdata {
                   6137:     my ($uname,$udom)=@_;
                   6138:     #most student don\'t have any data set, check if there is some data
                   6139:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6140: 
                   6141:     my $hashid="$udom:$uname";
                   6142:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6143:     if (!defined($cached)) {
                   6144: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6145: 	$result=\%resourcedata;
                   6146: 	&do_cache_new('userres',$hashid,$result,600);
                   6147:     }
                   6148:     my ($tmp)=keys(%$result);
                   6149:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6150: 	return $result;
                   6151:     }
                   6152:     #error 2 occurs when the .db doesn't exist
                   6153:     if ($tmp!~/error: 2 /) {
1.672     albertel 6154: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6155: 		 " Trying to get resource data for ".
                   6156: 		 $uname." at ".$udom.": ".
                   6157: 		 $tmp."</font>");
                   6158:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6159: 	#&EXT_cache_set($udom,$uname);
                   6160: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6161: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6162:     }
                   6163:     return $tmp;
                   6164: }
1.879     foxr     6165: #----------------------------------------------- resdata - return resource data
                   6166: #  Purpose:
                   6167: #    Return resource data for either users or for a course.
                   6168: #  Parameters:
                   6169: #     $name      - Course/user name.
                   6170: #     $domain    - Name of the domain the user/course is registered on.
                   6171: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6172: #     @which     - Array of names of resources desired.
                   6173: #  Returns:
                   6174: #     The value of the first reasource in @which that is found in the
                   6175: #     resource hash.
                   6176: #  Exceptional Conditions:
                   6177: #     If the $type passed in is not valid (not the string 'course' or 
                   6178: #     'user', an undefined  reference is returned.
                   6179: #     If none of the resources are found, an undef is returned
1.624     albertel 6180: sub resdata {
                   6181:     my ($name,$domain,$type,@which)=@_;
                   6182:     my $result;
                   6183:     if ($type eq 'course') {
                   6184: 	$result=&get_courseresdata($name,$domain);
                   6185:     } elsif ($type eq 'user') {
                   6186: 	$result=&get_userresdata($name,$domain);
                   6187:     }
                   6188:     if (!ref($result)) { return $result; }    
1.251     albertel 6189:     foreach my $item (@which) {
1.417     albertel 6190: 	if (defined($result->{$item})) {
                   6191: 	    return $result->{$item};
1.251     albertel 6192: 	}
1.250     albertel 6193:     }
1.291     albertel 6194:     return undef;
1.200     www      6195: }
                   6196: 
1.379     matthew  6197: #
                   6198: # EXT resource caching routines
                   6199: #
                   6200: 
                   6201: sub clear_EXT_cache_status {
1.383     albertel 6202:     &delenv('cache.EXT.');
1.379     matthew  6203: }
                   6204: 
                   6205: sub EXT_cache_status {
                   6206:     my ($target_domain,$target_user) = @_;
1.383     albertel 6207:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6208:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6209:         # We know already the user has no data
                   6210:         return 1;
                   6211:     } else {
                   6212:         return 0;
                   6213:     }
                   6214: }
                   6215: 
                   6216: sub EXT_cache_set {
                   6217:     my ($target_domain,$target_user) = @_;
1.383     albertel 6218:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6219:     #&appenv($cachename => time);
1.379     matthew  6220: }
                   6221: 
1.28      www      6222: # --------------------------------------------------------- Value of a Variable
1.58      www      6223: sub EXT {
1.715     albertel 6224: 
1.395     albertel 6225:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6226:     unless ($varname) { return ''; }
1.218     albertel 6227:     #get real user name/domain, courseid and symb
                   6228:     my $courseid;
1.359     albertel 6229:     my $publicuser;
1.427     www      6230:     if ($symbparm) {
                   6231: 	$symbparm=&get_symb_from_alias($symbparm);
                   6232:     }
1.218     albertel 6233:     if (!($uname && $udom)) {
1.790     albertel 6234:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6235:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6236:     } else {
1.620     albertel 6237: 	$courseid=$env{'request.course.id'};
1.218     albertel 6238:     }
1.48      www      6239:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6240:     my $rest;
1.320     albertel 6241:     if (defined($therest[0])) {
1.48      www      6242:        $rest=join('.',@therest);
                   6243:     } else {
                   6244:        $rest='';
                   6245:     }
1.320     albertel 6246: 
1.57      www      6247:     my $qualifierrest=$qualifier;
                   6248:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6249:     my $spacequalifierrest=$space;
                   6250:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6251:     if ($realm eq 'user') {
1.48      www      6252: # --------------------------------------------------------------- user.resource
                   6253: 	if ($space eq 'resource') {
1.651     albertel 6254: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6255: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6256: 		 &&
1.744     albertel 6257: 		 ($symbparm eq &symbread()) ) {	
                   6258: 		# if we are in the middle of processing the resource the
                   6259: 		# get the value we are planning on committing
                   6260:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6261:                     return $Apache::lonhomework::results{$qualifierrest};
                   6262:                 } else {
                   6263:                     return $Apache::lonhomework::history{$qualifierrest};
                   6264:                 }
1.335     albertel 6265: 	    } else {
1.359     albertel 6266: 		my %restored;
1.620     albertel 6267: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6268: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6269: 		} else {
                   6270: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6271: 		}
1.335     albertel 6272: 		return $restored{$qualifierrest};
                   6273: 	    }
1.48      www      6274: # ----------------------------------------------------------------- user.access
                   6275:         } elsif ($space eq 'access') {
1.218     albertel 6276: 	    # FIXME - not supporting calls for a specific user
1.48      www      6277:             return &allowed($qualifier,$rest);
                   6278: # ------------------------------------------ user.preferences, user.environment
                   6279:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6280: 	    if (($uname eq $env{'user.name'}) &&
                   6281: 		($udom eq $env{'user.domain'})) {
                   6282: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6283: 	    } else {
1.359     albertel 6284: 		my %returnhash;
                   6285: 		if (!$publicuser) {
                   6286: 		    %returnhash=&userenvironment($udom,$uname,
                   6287: 						 $qualifierrest);
                   6288: 		}
1.218     albertel 6289: 		return $returnhash{$qualifierrest};
                   6290: 	    }
1.48      www      6291: # ----------------------------------------------------------------- user.course
                   6292:         } elsif ($space eq 'course') {
1.218     albertel 6293: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6294:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6295: # ------------------------------------------------------------------- user.role
                   6296:         } elsif ($space eq 'role') {
1.218     albertel 6297: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6298:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6299:             if ($qualifier eq 'value') {
                   6300: 		return $role;
                   6301:             } elsif ($qualifier eq 'extent') {
                   6302:                 return $where;
                   6303:             }
                   6304: # ----------------------------------------------------------------- user.domain
                   6305:         } elsif ($space eq 'domain') {
1.218     albertel 6306:             return $udom;
1.48      www      6307: # ------------------------------------------------------------------- user.name
                   6308:         } elsif ($space eq 'name') {
1.218     albertel 6309:             return $uname;
1.48      www      6310: # ---------------------------------------------------- Any other user namespace
1.29      www      6311:         } else {
1.359     albertel 6312: 	    my %reply;
                   6313: 	    if (!$publicuser) {
                   6314: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6315: 	    }
                   6316: 	    return $reply{$qualifierrest};
1.48      www      6317:         }
1.236     www      6318:     } elsif ($realm eq 'query') {
                   6319: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6320:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6321: 						[$spacequalifierrest]);
1.620     albertel 6322: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6323:    } elsif ($realm eq 'request') {
1.48      www      6324: # ------------------------------------------------------------- request.browser
                   6325:         if ($space eq 'browser') {
1.430     www      6326: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6327: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6328: 		    return 1;
                   6329: 		} else {
                   6330: 		    return 0;
                   6331: 		}
                   6332: 	    } else {
1.620     albertel 6333: 		return $env{'browser.'.$qualifier};
1.430     www      6334: 	    }
1.57      www      6335: # ------------------------------------------------------------ request.filename
                   6336:         } else {
1.620     albertel 6337:             return $env{'request.'.$spacequalifierrest};
1.29      www      6338:         }
1.28      www      6339:     } elsif ($realm eq 'course') {
1.48      www      6340: # ---------------------------------------------------------- course.description
1.620     albertel 6341:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6342:     } elsif ($realm eq 'resource') {
1.165     www      6343: 
1.620     albertel 6344: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6345: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6346: 	}
1.693     albertel 6347: 
                   6348: 	if ($space eq 'title') {
                   6349: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6350: 	    return &gettitle($symbparm);
                   6351: 	}
                   6352: 	
                   6353: 	if ($space eq 'map') {
                   6354: 	    my ($map) = &decode_symb($symbparm);
                   6355: 	    return &symbread($map);
                   6356: 	}
1.905     albertel 6357: 	if ($space eq 'filename') {
                   6358: 	    if ($symbparm) {
                   6359: 		return &clutter((&decode_symb($symbparm))[2]);
                   6360: 	    }
                   6361: 	    return &hreflocation('',$env{'request.filename'});
                   6362: 	}
1.693     albertel 6363: 
                   6364: 	my ($section, $group, @groups);
1.593     albertel 6365: 	my ($courselevelm,$courselevel);
1.539     albertel 6366: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6367: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6368: 
1.218     albertel 6369: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6370: 
1.60      www      6371: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6372: 	    my $symbp=$symbparm;
1.735     albertel 6373: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6374: 
                   6375: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6376: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6377: 
1.620     albertel 6378: 	    if (($env{'user.name'} eq $uname) &&
                   6379: 		($env{'user.domain'} eq $udom)) {
                   6380: 		$section=$env{'request.course.sec'};
1.733     raeburn  6381:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6382:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6383: 	    } else {
1.539     albertel 6384: 		if (! defined($usection)) {
1.551     albertel 6385: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6386: 		} else {
                   6387: 		    $section = $usection;
                   6388: 		}
1.733     raeburn  6389:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6390: 	    }
                   6391: 
                   6392: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6393: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6394: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6395: 
1.593     albertel 6396: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6397: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6398: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6399: 
1.60      www      6400: # ----------------------------------------------------------- first, check user
1.624     albertel 6401: 
                   6402: 	    my $userreply=&resdata($uname,$udom,'user',
                   6403: 				       ($courselevelr,$courselevelm,
                   6404: 					$courselevel));
                   6405: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6406: 
1.594     albertel 6407: # ------------------------------------------------ second, check some of course
1.684     raeburn  6408:             my $coursereply;
1.691     raeburn  6409:             if (@groups > 0) {
                   6410:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6411:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6412:                 if (defined($coursereply)) { return $coursereply; }
                   6413:             }
1.96      www      6414: 
1.684     raeburn  6415: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6416: 				     $env{'course.'.$courseid.'.domain'},
                   6417: 				     'course',
                   6418: 				     ($seclevelr,$seclevelm,$seclevel,
                   6419: 				      $courselevelr));
1.287     albertel 6420: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6421: 
1.60      www      6422: # ------------------------------------------------------ third, check map parms
1.218     albertel 6423: 	    my %parmhash=();
                   6424: 	    my $thisparm='';
                   6425: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6426: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6427: 		    &GDBM_READER(),0640)) {
1.218     albertel 6428: 		$thisparm=$parmhash{$symbparm};
                   6429: 		untie(%parmhash);
                   6430: 	    }
                   6431: 	    if ($thisparm) { return $thisparm; }
                   6432: 	}
1.594     albertel 6433: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6434: 
1.218     albertel 6435: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6436: 	my $filename;
                   6437: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6438: 	if ($symbparm) {
1.409     www      6439: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6440: 	} else {
1.620     albertel 6441: 	    $filename=$env{'request.filename'};
1.282     albertel 6442: 	}
                   6443: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6444: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6445: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6446: 	if (defined($metadata)) { return $metadata; }
1.142     www      6447: 
1.594     albertel 6448: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6449: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6450: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6451: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6452: 				     $env{'course.'.$courseid.'.domain'},
                   6453: 				     'course',
                   6454: 				     ($courselevelm,$courselevel));
1.593     albertel 6455: 	    if (defined($coursereply)) { return $coursereply; }
                   6456: 	}
1.145     www      6457: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6458: 	unless ($space eq '0') {
1.336     albertel 6459: 	    my @parts=split(/_/,$space);
                   6460: 	    my $id=pop(@parts);
                   6461: 	    my $part=join('_',@parts);
                   6462: 	    if ($part eq '') { $part='0'; }
                   6463: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6464: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6465: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6466: 	}
1.395     albertel 6467: 	if ($recurse) { return undef; }
                   6468: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6469: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6470: 
1.48      www      6471: # ---------------------------------------------------- Any other user namespace
                   6472:     } elsif ($realm eq 'environment') {
                   6473: # ----------------------------------------------------------------- environment
1.620     albertel 6474: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6475: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6476: 	} else {
1.770     albertel 6477: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6478: 		return '';
                   6479: 	    }
1.219     albertel 6480: 	    my %returnhash=&userenvironment($udom,$uname,
                   6481: 					    $spacequalifierrest);
                   6482: 	    return $returnhash{$spacequalifierrest};
                   6483: 	}
1.28      www      6484:     } elsif ($realm eq 'system') {
1.48      www      6485: # ----------------------------------------------------------------- system.time
                   6486: 	if ($space eq 'time') {
                   6487: 	    return time;
                   6488:         }
1.696     albertel 6489:     } elsif ($realm eq 'server') {
                   6490: # ----------------------------------------------------------------- system.time
                   6491: 	if ($space eq 'name') {
                   6492: 	    return $ENV{'SERVER_NAME'};
                   6493:         }
1.28      www      6494:     }
1.48      www      6495:     return '';
1.61      www      6496: }
                   6497: 
1.691     raeburn  6498: sub check_group_parms {
                   6499:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6500:     my @groupitems = ();
                   6501:     my $resultitem;
                   6502:     my @levels = ($symbparm,$mapparm,$what);
                   6503:     foreach my $group (@{$groups}) {
                   6504:         foreach my $level (@levels) {
                   6505:              my $item = $courseid.'.['.$group.'].'.$level;
                   6506:              push(@groupitems,$item);
                   6507:         }
                   6508:     }
                   6509:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6510:                             $env{'course.'.$courseid.'.domain'},
                   6511:                                      'course',@groupitems);
                   6512:     return $coursereply;
                   6513: }
                   6514: 
                   6515: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6516:     my ($courseid,@groups) = @_;
                   6517:     @groups = sort(@groups);
1.691     raeburn  6518:     return @groups;
                   6519: }
                   6520: 
1.395     albertel 6521: sub packages_tab_default {
                   6522:     my ($uri,$varname)=@_;
                   6523:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6524: 
                   6525:     my (@extension,@specifics,$do_default);
                   6526:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6527: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6528: 	if ($pack_type eq 'default') {
                   6529: 	    $do_default=1;
                   6530: 	} elsif ($pack_type eq 'extension') {
                   6531: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6532: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6533: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6534: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6535: 	}
                   6536:     }
                   6537:     # first look for a package that matches the requested part id
                   6538:     foreach my $package (@specifics) {
                   6539: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6540: 	next if ($pack_part ne $part);
                   6541: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6542: 	    return $packagetab{"$pack_type&$name&default"};
                   6543: 	}
                   6544:     }
                   6545:     # look for any possible matching non extension_ package
                   6546:     foreach my $package (@specifics) {
                   6547: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6548: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6549: 	    return $packagetab{"$pack_type&$name&default"};
                   6550: 	}
1.585     albertel 6551: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6552: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6553: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6554: 	}
                   6555:     }
1.738     albertel 6556:     # look for any posible extension_ match
                   6557:     foreach my $package (@extension) {
                   6558: 	my ($package,$pack_type)=@{$package};
                   6559: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6560: 	    return $packagetab{"$pack_type&$name&default"};
                   6561: 	}
                   6562: 	if (defined($packagetab{$package."&$name&default"})) {
                   6563: 	    return $packagetab{$package."&$name&default"};
                   6564: 	}
                   6565:     }
                   6566:     # look for a global default setting
                   6567:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6568: 	return $packagetab{"default&$name&default"};
                   6569:     }
1.395     albertel 6570:     return undef;
                   6571: }
                   6572: 
1.334     albertel 6573: sub add_prefix_and_part {
                   6574:     my ($prefix,$part)=@_;
                   6575:     my $keyroot;
                   6576:     if (defined($prefix) && $prefix !~ /^__/) {
                   6577: 	# prefix that has a part already
                   6578: 	$keyroot=$prefix;
                   6579:     } elsif (defined($prefix)) {
                   6580: 	# prefix that is missing a part
                   6581: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6582:     } else {
                   6583: 	# no prefix at all
                   6584: 	if (defined($part)) { $keyroot='_'.$part; }
                   6585:     }
                   6586:     return $keyroot;
                   6587: }
                   6588: 
1.71      www      6589: # ---------------------------------------------------------------- Get metadata
                   6590: 
1.599     albertel 6591: my %metaentry;
1.71      www      6592: sub metadata {
1.176     www      6593:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6594:     $uri=&declutter($uri);
1.288     albertel 6595:     # if it is a non metadata possible uri return quickly
1.529     albertel 6596:     if (($uri eq '') || 
                   6597: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6598: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6599:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6600: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6601: 	return undef;
1.288     albertel 6602:     }
1.73      www      6603:     my $filename=$uri;
                   6604:     $uri=~s/\.meta$//;
1.172     www      6605: #
                   6606: # Is the metadata already cached?
1.177     www      6607: # Look at timestamp of caching
1.172     www      6608: # Everything is cached by the main uri, libraries are never directly cached
                   6609: #
1.428     albertel 6610:     if (!defined($liburi)) {
1.599     albertel 6611: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6612: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6613:     }
                   6614:     {
1.172     www      6615: #
                   6616: # Is this a recursive call for a library?
                   6617: #
1.599     albertel 6618: #	if (! exists($metacache{$uri})) {
                   6619: #	    $metacache{$uri}={};
                   6620: #	}
1.171     www      6621:         if ($liburi) {
                   6622: 	    $liburi=&declutter($liburi);
                   6623:             $filename=$liburi;
1.401     bowersj2 6624:         } else {
1.599     albertel 6625: 	    &devalidate_cache_new('meta',$uri);
                   6626: 	    undef(%metaentry);
1.401     bowersj2 6627: 	}
1.140     www      6628:         my %metathesekeys=();
1.73      www      6629:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6630: 	my $metastring;
1.768     albertel 6631: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6632: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6633: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6634: 	    $metastring=&getfile($file);
1.489     albertel 6635: 	}
1.208     albertel 6636:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6637:         my $token;
1.140     www      6638:         undef %metathesekeys;
1.71      www      6639:         while ($token=$parser->get_token) {
1.339     albertel 6640: 	    if ($token->[0] eq 'S') {
                   6641: 		if (defined($token->[2]->{'package'})) {
1.172     www      6642: #
                   6643: # This is a package - get package info
                   6644: #
1.339     albertel 6645: 		    my $package=$token->[2]->{'package'};
                   6646: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6647: 		    if (defined($token->[2]->{'id'})) { 
                   6648: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6649: 		    }
1.599     albertel 6650: 		    if ($metaentry{':packages'}) {
                   6651: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6652: 		    } else {
1.599     albertel 6653: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6654: 		    }
1.736     albertel 6655: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6656: 			my $part=$keyroot;
                   6657: 			$part=~s/^\_//;
1.736     albertel 6658: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6659: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6660: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6661: 			    # ignore package.tab specified default values
                   6662:                             # here &package_tab_default() will fetch those
                   6663: 			    if ($subp eq 'default') { next; }
1.736     albertel 6664: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6665: 			    my $unikey;
                   6666: 			    if ($pack =~ /_0$/) {
                   6667: 				$unikey='parameter_0_'.$name;
                   6668: 				$part=0;
                   6669: 			    } else {
                   6670: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6671: 			    }
1.339     albertel 6672: 			    if ($subp eq 'display') {
                   6673: 				$value.=' [Part: '.$part.']';
                   6674: 			    }
1.599     albertel 6675: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6676: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6677: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6678: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6679: 			    }
1.599     albertel 6680: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6681: 				$metaentry{':'.$unikey}=
                   6682: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6683: 			    }
1.339     albertel 6684: 			}
                   6685: 		    }
                   6686: 		} else {
1.172     www      6687: #
                   6688: # This is not a package - some other kind of start tag
1.339     albertel 6689: #
                   6690: 		    my $entry=$token->[1];
                   6691: 		    my $unikey;
                   6692: 		    if ($entry eq 'import') {
                   6693: 			$unikey='';
                   6694: 		    } else {
                   6695: 			$unikey=$entry;
                   6696: 		    }
                   6697: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6698: 
                   6699: 		    if (defined($token->[2]->{'id'})) { 
                   6700: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6701: 		    }
1.175     www      6702: 
1.339     albertel 6703: 		    if ($entry eq 'import') {
1.175     www      6704: #
                   6705: # Importing a library here
1.339     albertel 6706: #
                   6707: 			if ($depthcount<20) {
                   6708: 			    my $location=$parser->get_text('/import');
                   6709: 			    my $dir=$filename;
                   6710: 			    $dir=~s|[^/]*$||;
                   6711: 			    $location=&filelocation($dir,$location);
1.736     albertel 6712: 			    my $metadata = 
                   6713: 				&metadata($uri,'keys', $location,$unikey,
                   6714: 					  $depthcount+1);
                   6715: 			    foreach my $meta (split(',',$metadata)) {
                   6716: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6717: 				$metathesekeys{$meta}=1;
1.339     albertel 6718: 			    }
                   6719: 			}
                   6720: 		    } else { 
                   6721: 			
                   6722: 			if (defined($token->[2]->{'name'})) { 
                   6723: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6724: 			}
                   6725: 			$metathesekeys{$unikey}=1;
1.736     albertel 6726: 			foreach my $param (@{$token->[3]}) {
                   6727: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6728: 				$token->[2]->{$param};
1.339     albertel 6729: 			}
                   6730: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6731: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6732: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6733: 		 # only ws inside the tag, and not in default, so use default
                   6734: 		 # as value
1.599     albertel 6735: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6736: 			} elsif ( $internaltext =~ /\S/ ) {
                   6737: 		  # something interesting inside the tag
                   6738: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6739: 			} else {
1.908     albertel 6740: 		  # no interesting values, don't set a default
1.339     albertel 6741: 			}
1.172     www      6742: # end of not-a-package not-a-library import
1.339     albertel 6743: 		    }
1.172     www      6744: # end of not-a-package start tag
1.339     albertel 6745: 		}
1.172     www      6746: # the next is the end of "start tag"
1.339     albertel 6747: 	    }
                   6748: 	}
1.483     albertel 6749: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6750: 	$extension = lc($extension);
                   6751: 	if ($extension eq 'htm') { $extension='html'; }
                   6752: 
1.737     albertel 6753: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6754: 	    #no specific packages #how's our extension
                   6755: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6756: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6757: 					 \%metathesekeys);
                   6758: 	}
1.883     albertel 6759: 
                   6760: 	if (!exists($metaentry{':packages'})
                   6761: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6762: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6763: 		#no specific packages well let's get default then
                   6764: 		if ($key!~/^default&/) { next; }
1.488     albertel 6765: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6766: 					     \%metathesekeys);
                   6767: 	    }
                   6768: 	}
1.338     www      6769: # are there custom rights to evaluate
1.599     albertel 6770: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6771: 
1.338     www      6772:     #
                   6773:     # Importing a rights file here
1.339     albertel 6774:     #
                   6775: 	    unless ($depthcount) {
1.599     albertel 6776: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6777: 		my $dir=$filename;
                   6778: 		$dir=~s|[^/]*$||;
                   6779: 		$location=&filelocation($dir,$location);
1.736     albertel 6780: 		my $rights_metadata =
                   6781: 		    &metadata($uri,'keys',$location,'_rights',
                   6782: 			      $depthcount+1);
                   6783: 		foreach my $rights (split(',',$rights_metadata)) {
                   6784: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6785: 		    $metathesekeys{$rights}=1;
1.339     albertel 6786: 		}
                   6787: 	    }
                   6788: 	}
1.737     albertel 6789: 	# uniqifiy package listing
                   6790: 	my %seen;
                   6791: 	my @uniq_packages =
                   6792: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6793: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6794: 
                   6795: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6796: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6797: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6798: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6799: # this is the end of "was not already recently cached
1.71      www      6800:     }
1.599     albertel 6801:     return $metaentry{':'.$what};
1.261     albertel 6802: }
                   6803: 
1.488     albertel 6804: sub metadata_create_package_def {
1.483     albertel 6805:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6806:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6807:     if ($subp eq 'default') { next; }
                   6808:     
1.599     albertel 6809:     if (defined($metaentry{':packages'})) {
                   6810: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6811:     } else {
1.599     albertel 6812: 	$metaentry{':packages'}=$package;
1.483     albertel 6813:     }
                   6814:     my $value=$packagetab{$key};
                   6815:     my $unikey;
                   6816:     $unikey='parameter_0_'.$name;
1.599     albertel 6817:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6818:     $$metathesekeys{$unikey}=1;
1.599     albertel 6819:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6820: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6821:     }
1.599     albertel 6822:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6823: 	$metaentry{':'.$unikey}=
                   6824: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6825:     }
                   6826: }
                   6827: 
1.261     albertel 6828: sub metadata_generate_part0 {
                   6829:     my ($metadata,$metacache,$uri) = @_;
                   6830:     my %allnames;
1.737     albertel 6831:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6832: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6833: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6834: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6835: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6836: 	    $allnames{$name}=$part;
                   6837: 	  }
                   6838: 	}
                   6839:     }
                   6840:     foreach my $name (keys(%allnames)) {
                   6841:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6842:       my $key=":parameter_0_$name";
1.261     albertel 6843:       $$metacache{"$key.part"}='0';
                   6844:       $$metacache{"$key.name"}=$name;
1.428     albertel 6845:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6846: 					   $allnames{$name}.'_'.$name.
                   6847: 					   '.type'};
1.428     albertel 6848:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6849: 			     '.display'};
1.644     www      6850:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6851:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6852:       $$metacache{"$key.display"}=$olddis;
                   6853:     }
1.71      www      6854: }
                   6855: 
1.764     albertel 6856: # ------------------------------------------------------ Devalidate title cache
                   6857: 
                   6858: sub devalidate_title_cache {
                   6859:     my ($url)=@_;
                   6860:     if (!$env{'request.course.id'}) { return; }
                   6861:     my $symb=&symbread($url);
                   6862:     if (!$symb) { return; }
                   6863:     my $key=$env{'request.course.id'}."\0".$symb;
                   6864:     &devalidate_cache_new('title',$key);
                   6865: }
                   6866: 
1.301     www      6867: # ------------------------------------------------- Get the title of a resource
                   6868: 
                   6869: sub gettitle {
                   6870:     my $urlsymb=shift;
                   6871:     my $symb=&symbread($urlsymb);
1.534     albertel 6872:     if ($symb) {
1.620     albertel 6873: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6874: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6875: 	if (defined($cached)) { 
                   6876: 	    return $result;
                   6877: 	}
1.534     albertel 6878: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6879: 	my $title='';
1.907     albertel 6880: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   6881: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   6882: 	} else {
                   6883: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6884: 		    &GDBM_READER(),0640)) {
                   6885: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6886: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   6887: 		untie(%bighash);
                   6888: 	    }
1.534     albertel 6889: 	}
                   6890: 	$title=~s/\&colon\;/\:/gs;
                   6891: 	if ($title) {
1.599     albertel 6892: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6893: 	}
                   6894: 	$urlsymb=$url;
                   6895:     }
                   6896:     my $title=&metadata($urlsymb,'title');
                   6897:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6898:     return $title;
1.301     www      6899: }
1.613     albertel 6900: 
1.614     albertel 6901: sub get_slot {
                   6902:     my ($which,$cnum,$cdom)=@_;
                   6903:     if (!$cnum || !$cdom) {
1.790     albertel 6904: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6905: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6906: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6907:     }
1.703     albertel 6908:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6909:     my %slotinfo;
                   6910:     if (exists($remembered{$key})) {
                   6911: 	$slotinfo{$which} = $remembered{$key};
                   6912:     } else {
                   6913: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6914: 	&Apache::lonhomework::showhash(%slotinfo);
                   6915: 	my ($tmp)=keys(%slotinfo);
                   6916: 	if ($tmp=~/^error:/) { return (); }
                   6917: 	$remembered{$key} = $slotinfo{$which};
                   6918:     }
1.616     albertel 6919:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6920: 	return %{$slotinfo{$which}};
                   6921:     }
                   6922:     return $slotinfo{$which};
1.614     albertel 6923: }
1.31      www      6924: # ------------------------------------------------- Update symbolic store links
                   6925: 
                   6926: sub symblist {
                   6927:     my ($mapname,%newhash)=@_;
1.438     www      6928:     $mapname=&deversion(&declutter($mapname));
1.31      www      6929:     my %hash;
1.620     albertel 6930:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6931:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6932:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6933: 	    foreach my $url (keys %newhash) {
                   6934: 		next if ($url eq 'last_known'
                   6935: 			 && $env{'form.no_update_last_known'});
                   6936: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6937: 						    $newhash{$url}->[1],
                   6938: 						    $newhash{$url}->[0]);
1.191     harris41 6939:             }
1.31      www      6940:             if (untie(%hash)) {
                   6941: 		return 'ok';
                   6942:             }
                   6943:         }
                   6944:     }
                   6945:     return 'error';
1.212     www      6946: }
                   6947: 
                   6948: # --------------------------------------------------------------- Verify a symb
                   6949: 
                   6950: sub symbverify {
1.510     www      6951:     my ($symb,$thisurl)=@_;
                   6952:     my $thisfn=$thisurl;
1.439     www      6953:     $thisfn=&declutter($thisfn);
1.215     www      6954: # direct jump to resource in page or to a sequence - will construct own symbs
                   6955:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6956: # check URL part
1.409     www      6957:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6958: 
1.431     www      6959:     unless ($url eq $thisfn) { return 0; }
1.213     www      6960: 
1.216     www      6961:     $symb=&symbclean($symb);
1.510     www      6962:     $thisurl=&deversion($thisurl);
1.439     www      6963:     $thisfn=&deversion($thisfn);
1.213     www      6964: 
                   6965:     my %bighash;
                   6966:     my $okay=0;
1.431     www      6967: 
1.620     albertel 6968:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6969:                             &GDBM_READER(),0640)) {
1.510     www      6970:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6971:         unless ($ids) { 
1.510     www      6972:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6973:         }
                   6974:         if ($ids) {
                   6975: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6976: 	    foreach my $id (split(/\,/,$ids)) {
                   6977: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6978:                if (
                   6979:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6980:    eq $symb) { 
1.620     albertel 6981: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6982: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6983: 		       $okay=1; 
                   6984: 		   }
                   6985: 	       }
1.216     www      6986: 	   }
                   6987:         }
1.213     www      6988: 	untie(%bighash);
                   6989:     }
                   6990:     return $okay;
1.31      www      6991: }
                   6992: 
1.210     www      6993: # --------------------------------------------------------------- Clean-up symb
                   6994: 
                   6995: sub symbclean {
                   6996:     my $symb=shift;
1.568     albertel 6997:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6998: # remove version from map
                   6999:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7000: 
1.210     www      7001: # remove version from URL
                   7002:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7003: 
1.507     www      7004: # remove wrapper
                   7005: 
1.510     www      7006:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7007:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7008:     return $symb;
1.409     www      7009: }
                   7010: 
                   7011: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7012: 
                   7013: sub encode_symb {
                   7014:     my ($map,$resid,$url)=@_;
                   7015:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7016: }
1.409     www      7017: 
                   7018: sub decode_symb {
1.568     albertel 7019:     my $symb=shift;
                   7020:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7021:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7022:     return (&fixversion($map),$resid,&fixversion($url));
                   7023: }
                   7024: 
                   7025: sub fixversion {
                   7026:     my $fn=shift;
1.609     banghart 7027:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7028:     my %bighash;
                   7029:     my $uri=&clutter($fn);
1.620     albertel 7030:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7031: # is this cached?
1.599     albertel 7032:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7033:     if (defined($cached)) { return $result; }
                   7034: # unfortunately not cached, or expired
1.620     albertel 7035:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7036: 	    &GDBM_READER(),0640)) {
                   7037:  	if ($bighash{'version_'.$uri}) {
                   7038:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7039:  	    unless (($version eq 'mostrecent') || 
                   7040: 		    ($version==&getversion($uri))) {
1.440     www      7041:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7042:  	    }
                   7043:  	}
                   7044:  	untie %bighash;
1.413     www      7045:     }
1.599     albertel 7046:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7047: }
                   7048: 
                   7049: sub deversion {
                   7050:     my $url=shift;
                   7051:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7052:     return $url;
1.210     www      7053: }
                   7054: 
1.31      www      7055: # ------------------------------------------------------ Return symb list entry
                   7056: 
                   7057: sub symbread {
1.249     www      7058:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7059:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7060:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7061: # no filename provided? try from environment
1.44      www      7062:     unless ($thisfn) {
1.620     albertel 7063:         if ($env{'request.symb'}) {
                   7064: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7065: 	}
1.620     albertel 7066: 	$thisfn=$env{'request.filename'};
1.44      www      7067:     }
1.569     albertel 7068:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7069: # is that filename actually a symb? Verify, clean, and return
                   7070:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7071: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7072: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7073: 	}
1.242     www      7074:     }
1.44      www      7075:     $thisfn=declutter($thisfn);
1.31      www      7076:     my %hash;
1.37      www      7077:     my %bighash;
                   7078:     my $syval='';
1.620     albertel 7079:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7080:         my $targetfn = $thisfn;
1.609     banghart 7081:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7082:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7083:         }
1.687     albertel 7084: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7085: 	    $targetfn=$1;
                   7086: 	}
1.620     albertel 7087:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7088:                       &GDBM_READER(),0640)) {
1.481     raeburn  7089: 	    $syval=$hash{$targetfn};
1.37      www      7090:             untie(%hash);
                   7091:         }
                   7092: # ---------------------------------------------------------- There was an entry
                   7093:         if ($syval) {
1.601     albertel 7094: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7095: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7096: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7097: 		    #return $env{$cache_str}='';
1.601     albertel 7098: 		#}    
                   7099: 		#$syval.=$1;
                   7100: 	    #}
1.37      www      7101:         } else {
                   7102: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7103:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7104:                             &GDBM_READER(),0640)) {
1.37      www      7105: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7106:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7107:               unless ($ids) { 
                   7108:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7109:               }
                   7110:               unless ($ids) {
                   7111: # alias?
                   7112: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7113:               }
1.37      www      7114:               if ($ids) {
                   7115: # ------------------------------------------------------------------- Has ID(s)
                   7116:                  my @possibilities=split(/\,/,$ids);
1.39      www      7117:                  if ($#possibilities==0) {
                   7118: # ----------------------------------------------- There is only one possibility
1.37      www      7119: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7120: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7121: 						    $resid,$thisfn);
1.249     www      7122:                  } elsif (!$donotrecurse) {
1.39      www      7123: # ------------------------------------------ There is more than one possibility
                   7124:                      my $realpossible=0;
1.800     albertel 7125:                      foreach my $id (@possibilities) {
                   7126: 			 my $file=$bighash{'src_'.$id};
1.39      www      7127:                          if (&allowed('bre',$file)) {
1.800     albertel 7128:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7129:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7130: 				$realpossible++;
1.626     albertel 7131:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7132: 						    $resid,$thisfn);
1.39      www      7133:                             }
                   7134: 			 }
1.191     harris41 7135:                      }
1.39      www      7136: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7137:                  } else {
                   7138:                      $syval='';
1.37      www      7139:                  }
                   7140: 	      }
                   7141:               untie(%bighash)
1.481     raeburn  7142:            }
1.31      www      7143:         }
1.62      www      7144:         if ($syval) {
1.620     albertel 7145: 	    return $env{$cache_str}=$syval;
1.62      www      7146:         }
1.31      www      7147:     }
1.44      www      7148:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7149:     return $env{$cache_str}='';
1.31      www      7150: }
                   7151: 
                   7152: # ---------------------------------------------------------- Return random seed
                   7153: 
1.32      www      7154: sub numval {
                   7155:     my $txt=shift;
                   7156:     $txt=~tr/A-J/0-9/;
                   7157:     $txt=~tr/a-j/0-9/;
                   7158:     $txt=~tr/K-T/0-9/;
                   7159:     $txt=~tr/k-t/0-9/;
                   7160:     $txt=~tr/U-Z/0-5/;
                   7161:     $txt=~tr/u-z/0-5/;
                   7162:     $txt=~s/\D//g;
1.564     albertel 7163:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7164:     return int($txt);
1.368     albertel 7165: }
                   7166: 
1.484     albertel 7167: sub numval2 {
                   7168:     my $txt=shift;
                   7169:     $txt=~tr/A-J/0-9/;
                   7170:     $txt=~tr/a-j/0-9/;
                   7171:     $txt=~tr/K-T/0-9/;
                   7172:     $txt=~tr/k-t/0-9/;
                   7173:     $txt=~tr/U-Z/0-5/;
                   7174:     $txt=~tr/u-z/0-5/;
                   7175:     $txt=~s/\D//g;
                   7176:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7177:     my $total;
                   7178:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7179:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7180:     return int($total);
                   7181: }
                   7182: 
1.575     albertel 7183: sub numval3 {
                   7184:     use integer;
                   7185:     my $txt=shift;
                   7186:     $txt=~tr/A-J/0-9/;
                   7187:     $txt=~tr/a-j/0-9/;
                   7188:     $txt=~tr/K-T/0-9/;
                   7189:     $txt=~tr/k-t/0-9/;
                   7190:     $txt=~tr/U-Z/0-5/;
                   7191:     $txt=~tr/u-z/0-5/;
                   7192:     $txt=~s/\D//g;
                   7193:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7194:     my $total;
                   7195:     foreach my $val (@txts) { $total+=$val; }
                   7196:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7197:     return $total;
                   7198: }
                   7199: 
1.675     albertel 7200: sub digest {
                   7201:     my ($data)=@_;
                   7202:     my $digest=&Digest::MD5::md5($data);
                   7203:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7204:     my ($e,$f);
                   7205:     {
                   7206:         use integer;
                   7207:         $e=($a+$b);
                   7208:         $f=($c+$d);
                   7209:         if ($_64bit) {
                   7210:             $e=(($e<<32)>>32);
                   7211:             $f=(($f<<32)>>32);
                   7212:         }
                   7213:     }
                   7214:     if (wantarray) {
                   7215: 	return ($e,$f);
                   7216:     } else {
                   7217: 	my $g;
                   7218: 	{
                   7219: 	    use integer;
                   7220: 	    $g=($e+$f);
                   7221: 	    if ($_64bit) {
                   7222: 		$g=(($g<<32)>>32);
                   7223: 	    }
                   7224: 	}
                   7225: 	return $g;
                   7226:     }
                   7227: }
                   7228: 
1.368     albertel 7229: sub latest_rnd_algorithm_id {
1.675     albertel 7230:     return '64bit5';
1.366     albertel 7231: }
1.32      www      7232: 
1.503     albertel 7233: sub get_rand_alg {
                   7234:     my ($courseid)=@_;
1.790     albertel 7235:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7236:     if ($courseid) {
1.620     albertel 7237: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7238:     }
                   7239:     return &latest_rnd_algorithm_id();
                   7240: }
                   7241: 
1.562     albertel 7242: sub validCODE {
                   7243:     my ($CODE)=@_;
                   7244:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7245:     return 0;
                   7246: }
                   7247: 
1.491     albertel 7248: sub getCODE {
1.620     albertel 7249:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7250:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7251: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7252: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7253: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7254:     }
                   7255:     return undef;
                   7256: }
                   7257: 
1.31      www      7258: sub rndseed {
1.155     albertel 7259:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7260:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7261:     if (!defined($symb)) {
1.366     albertel 7262: 	unless ($symb=$wsymb) { return time; }
                   7263:     }
                   7264:     if (!$courseid) { $courseid=$wcourseid; }
                   7265:     if (!$domain) { $domain=$wdomain; }
                   7266:     if (!$username) { $username=$wusername }
1.503     albertel 7267:     my $which=&get_rand_alg();
1.803     albertel 7268: 
1.491     albertel 7269:     if (defined(&getCODE())) {
1.675     albertel 7270: 	if ($which eq '64bit5') {
                   7271: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7272: 	} elsif ($which eq '64bit4') {
1.575     albertel 7273: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7274: 	} else {
                   7275: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7276: 	}
1.675     albertel 7277:     } elsif ($which eq '64bit5') {
                   7278: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7279:     } elsif ($which eq '64bit4') {
                   7280: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7281:     } elsif ($which eq '64bit3') {
                   7282: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7283:     } elsif ($which eq '64bit2') {
                   7284: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7285:     } elsif ($which eq '64bit') {
                   7286: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7287:     }
                   7288:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7289: }
                   7290: 
                   7291: sub rndseed_32bit {
                   7292:     my ($symb,$courseid,$domain,$username)=@_;
                   7293:     {
                   7294: 	use integer;
                   7295: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7296: 	my $symbseed=numval($symb) << 22;
                   7297: 	my $namechck=unpack("%32C*",$username) << 17;
                   7298: 	my $nameseed=numval($username) << 12;
                   7299: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7300: 	my $courseseed=unpack("%32C*",$courseid);
                   7301: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7302: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7303: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7304: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7305: 	return $num;
                   7306:     }
                   7307: }
                   7308: 
                   7309: sub rndseed_64bit {
                   7310:     my ($symb,$courseid,$domain,$username)=@_;
                   7311:     {
                   7312: 	use integer;
                   7313: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7314: 	my $symbseed=numval($symb) << 10;
                   7315: 	my $namechck=unpack("%32S*",$username);
                   7316: 	
                   7317: 	my $nameseed=numval($username) << 21;
                   7318: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7319: 	my $courseseed=unpack("%32S*",$courseid);
                   7320: 	
                   7321: 	my $num1=$symbchck+$symbseed+$namechck;
                   7322: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7323: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7324: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7325: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7326: 	return "$num1,$num2";
1.155     albertel 7327:     }
1.366     albertel 7328: }
                   7329: 
1.443     albertel 7330: sub rndseed_64bit2 {
                   7331:     my ($symb,$courseid,$domain,$username)=@_;
                   7332:     {
                   7333: 	use integer;
                   7334: 	# strings need to be an even # of cahracters long, it it is odd the
                   7335:         # last characters gets thrown away
                   7336: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7337: 	my $symbseed=numval($symb) << 10;
                   7338: 	my $namechck=unpack("%32S*",$username.' ');
                   7339: 	
                   7340: 	my $nameseed=numval($username) << 21;
1.501     albertel 7341: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7342: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7343: 	
                   7344: 	my $num1=$symbchck+$symbseed+$namechck;
                   7345: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7346: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7347: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7348: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7349: 	return "$num1,$num2";
                   7350:     }
                   7351: }
                   7352: 
                   7353: sub rndseed_64bit3 {
                   7354:     my ($symb,$courseid,$domain,$username)=@_;
                   7355:     {
                   7356: 	use integer;
                   7357: 	# strings need to be an even # of cahracters long, it it is odd the
                   7358:         # last characters gets thrown away
                   7359: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7360: 	my $symbseed=numval2($symb) << 10;
                   7361: 	my $namechck=unpack("%32S*",$username.' ');
                   7362: 	
                   7363: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7364: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7365: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7366: 	
                   7367: 	my $num1=$symbchck+$symbseed+$namechck;
                   7368: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7369: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7370: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7371: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7372: 	
1.503     albertel 7373: 	return "$num1:$num2";
1.443     albertel 7374:     }
                   7375: }
                   7376: 
1.575     albertel 7377: sub rndseed_64bit4 {
                   7378:     my ($symb,$courseid,$domain,$username)=@_;
                   7379:     {
                   7380: 	use integer;
                   7381: 	# strings need to be an even # of cahracters long, it it is odd the
                   7382:         # last characters gets thrown away
                   7383: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7384: 	my $symbseed=numval3($symb) << 10;
                   7385: 	my $namechck=unpack("%32S*",$username.' ');
                   7386: 	
                   7387: 	my $nameseed=numval3($username) << 21;
                   7388: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7389: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7390: 	
                   7391: 	my $num1=$symbchck+$symbseed+$namechck;
                   7392: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7393: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7394: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7395: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7396: 	
                   7397: 	return "$num1:$num2";
                   7398:     }
                   7399: }
                   7400: 
1.675     albertel 7401: sub rndseed_64bit5 {
                   7402:     my ($symb,$courseid,$domain,$username)=@_;
                   7403:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7404:     return "$num1:$num2";
                   7405: }
                   7406: 
1.366     albertel 7407: sub rndseed_CODE_64bit {
                   7408:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7409:     {
1.366     albertel 7410: 	use integer;
1.443     albertel 7411: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7412: 	my $symbseed=numval2($symb);
1.491     albertel 7413: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7414: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7415: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7416: 	my $num1=$symbseed+$CODEchck;
                   7417: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7418: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7419: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7420: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7421: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7422: 	return "$num1:$num2";
1.366     albertel 7423:     }
                   7424: }
                   7425: 
1.575     albertel 7426: sub rndseed_CODE_64bit4 {
                   7427:     my ($symb,$courseid,$domain,$username)=@_;
                   7428:     {
                   7429: 	use integer;
                   7430: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7431: 	my $symbseed=numval3($symb);
                   7432: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7433: 	my $CODEseed=numval3(&getCODE());
                   7434: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7435: 	my $num1=$symbseed+$CODEchck;
                   7436: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7437: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7438: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7439: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7440: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7441: 	return "$num1:$num2";
                   7442:     }
                   7443: }
                   7444: 
1.675     albertel 7445: sub rndseed_CODE_64bit5 {
                   7446:     my ($symb,$courseid,$domain,$username)=@_;
                   7447:     my $code = &getCODE();
                   7448:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7449:     return "$num1:$num2";
                   7450: }
                   7451: 
1.366     albertel 7452: sub setup_random_from_rndseed {
                   7453:     my ($rndseed)=@_;
1.503     albertel 7454:     if ($rndseed =~/([,:])/) {
                   7455: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7456: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7457:     } else {
                   7458: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7459:     }
1.36      albertel 7460: }
                   7461: 
1.474     albertel 7462: sub latest_receipt_algorithm_id {
1.835     albertel 7463:     return 'receipt3';
1.474     albertel 7464: }
                   7465: 
1.480     www      7466: sub recunique {
                   7467:     my $fucourseid=shift;
                   7468:     my $unique;
1.835     albertel 7469:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7470: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7471: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7472:     } else {
                   7473: 	$unique=$perlvar{'lonReceipt'};
                   7474:     }
                   7475:     return unpack("%32C*",$unique);
                   7476: }
                   7477: 
                   7478: sub recprefix {
                   7479:     my $fucourseid=shift;
                   7480:     my $prefix;
1.835     albertel 7481:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7482: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7483: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7484:     } else {
                   7485: 	$prefix=$perlvar{'lonHostID'};
                   7486:     }
                   7487:     return unpack("%32C*",$prefix);
                   7488: }
                   7489: 
1.76      www      7490: sub ireceipt {
1.474     albertel 7491:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7492: 
                   7493:     my $return =&recprefix($fucourseid).'-';
                   7494: 
                   7495:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7496: 	$env{'request.state'} eq 'construct') {
                   7497: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7498: 	return $return;
                   7499:     }
                   7500: 
1.76      www      7501:     my $cuname=unpack("%32C*",$funame);
                   7502:     my $cudom=unpack("%32C*",$fudom);
                   7503:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7504:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7505:     my $cunique=&recunique($fucourseid);
1.474     albertel 7506:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7507:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7508: 
1.790     albertel 7509: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7510: 			       
                   7511: 	$return.= ($cunique%$cuname+
                   7512: 		   $cunique%$cudom+
                   7513: 		   $cusymb%$cuname+
                   7514: 		   $cusymb%$cudom+
                   7515: 		   $cucourseid%$cuname+
                   7516: 		   $cucourseid%$cudom+
                   7517: 		   $cpart%$cuname+
                   7518: 		   $cpart%$cudom);
                   7519:     } else {
                   7520: 	$return.= ($cunique%$cuname+
                   7521: 		   $cunique%$cudom+
                   7522: 		   $cusymb%$cuname+
                   7523: 		   $cusymb%$cudom+
                   7524: 		   $cucourseid%$cuname+
                   7525: 		   $cucourseid%$cudom);
                   7526:     }
                   7527:     return $return;
1.76      www      7528: }
                   7529: 
                   7530: sub receipt {
1.474     albertel 7531:     my ($part)=@_;
1.790     albertel 7532:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7533:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7534: }
1.260     ng       7535: 
1.790     albertel 7536: sub whichuser {
                   7537:     my ($passedsymb)=@_;
                   7538:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7539:     if (defined($env{'form.grade_symb'})) {
                   7540: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7541: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7542: 	if (!$allowed &&
                   7543: 	    exists($env{'request.course.sec'}) &&
                   7544: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7545: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7546: 			      '/'.$env{'request.course.sec'});
                   7547: 	}
                   7548: 	if ($allowed) {
                   7549: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7550: 	    $courseid=$tmp_courseid;
                   7551: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7552: 	    ($name)=&get_env_multiple('form.grade_username');
                   7553: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7554: 	}
                   7555:     }
                   7556:     if (!$passedsymb) {
                   7557: 	$symb=&symbread();
                   7558:     } else {
                   7559: 	$symb=$passedsymb;
                   7560:     }
                   7561:     $courseid=$env{'request.course.id'};
                   7562:     $domain=$env{'user.domain'};
                   7563:     $name=$env{'user.name'};
                   7564:     if ($name eq 'public' && $domain eq 'public') {
                   7565: 	if (!defined($env{'form.username'})) {
                   7566: 	    $env{'form.username'}.=time.rand(10000000);
                   7567: 	}
                   7568: 	$name.=$env{'form.username'};
                   7569:     }
                   7570:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7571: 
                   7572: }
                   7573: 
1.36      albertel 7574: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7575: # returns either the contents of the file or 
                   7576: # -1 if the file doesn't exist
1.481     raeburn  7577: #
                   7578: # if the target is a file that was uploaded via DOCS, 
                   7579: # a check will be made to see if a current copy exists on the local server,
                   7580: # if it does this will be served, otherwise a copy will be retrieved from
                   7581: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7582: # the local server.   
1.472     albertel 7583: 
1.36      albertel 7584: sub getfile {
1.538     albertel 7585:     my ($file) = @_;
1.609     banghart 7586:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7587:     &repcopy($file);
                   7588:     return &readfile($file);
                   7589: }
                   7590: 
                   7591: sub repcopy_userfile {
                   7592:     my ($file)=@_;
1.609     banghart 7593:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7594:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7595:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7596: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7597:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7598:     if (-e "$file") {
1.828     www      7599: # we already have a local copy, check it out
1.538     albertel 7600: 	my @fileinfo = stat($file);
1.828     www      7601: 	my $rtncode;
                   7602: 	my $info;
1.538     albertel 7603: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7604: 	if ($lwpresp ne 'ok') {
1.828     www      7605: # there is no such file anymore, even though we had a local copy
1.482     albertel 7606: 	    if ($rtncode eq '404') {
1.538     albertel 7607: 		unlink($file);
1.482     albertel 7608: 	    }
                   7609: 	    return -1;
                   7610: 	}
                   7611: 	if ($info < $fileinfo[9]) {
1.828     www      7612: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7613: 	    return 'ok';
1.828     www      7614: 	} else {
                   7615: # the file is outdated, get rid of it
                   7616: 	    unlink($file);
1.482     albertel 7617: 	}
1.828     www      7618:     }
                   7619: # one way or the other, at this point, we don't have the file
                   7620: # construct the correct path for the file
                   7621:     my @parts = ($cdom,$cnum); 
                   7622:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7623: 	push @parts, split(/\//,$1);
                   7624:     }
                   7625:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7626:     foreach my $part (@parts) {
                   7627: 	$path .= '/'.$part;
                   7628: 	if (!-e $path) {
                   7629: 	    mkdir($path,0770);
1.482     albertel 7630: 	}
                   7631:     }
1.828     www      7632: # now the path exists for sure
                   7633: # get a user agent
                   7634:     my $ua=new LWP::UserAgent;
                   7635:     my $transferfile=$file.'.in.transfer';
                   7636: # FIXME: this should flock
                   7637:     if (-e $transferfile) { return 'ok'; }
                   7638:     my $request;
                   7639:     $uri=~s/^\///;
1.838     albertel 7640:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7641:     my $response=$ua->request($request,$transferfile);
                   7642: # did it work?
                   7643:     if ($response->is_error()) {
                   7644: 	unlink($transferfile);
                   7645: 	&logthis("Userfile repcopy failed for $uri");
                   7646: 	return -1;
                   7647:     }
                   7648: # worked, rename the transfer file
                   7649:     rename($transferfile,$file);
1.607     raeburn  7650:     return 'ok';
1.481     raeburn  7651: }
                   7652: 
1.517     albertel 7653: sub tokenwrapper {
                   7654:     my $uri=shift;
1.552     albertel 7655:     $uri=~s|^http\://([^/]+)||;
                   7656:     $uri=~s|^/||;
1.620     albertel 7657:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7658:     my $token=$1;
1.552     albertel 7659:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7660:     if ($udom && $uname && $file) {
                   7661: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7662:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7663:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7664:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7665:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7666:     } else {
                   7667:         return '/adm/notfound.html';
                   7668:     }
                   7669: }
                   7670: 
1.828     www      7671: # call with reqtype HEAD: get last modification time
                   7672: # call with reqtype GET: get the file contents
                   7673: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7674: #
1.481     raeburn  7675: sub getuploaded {
                   7676:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7677:     $uri=~s/^\///;
1.838     albertel 7678:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7679:     my $ua=new LWP::UserAgent;
                   7680:     my $request=new HTTP::Request($reqtype,$uri);
                   7681:     my $response=$ua->request($request);
                   7682:     $$rtncode = $response->code;
1.482     albertel 7683:     if (! $response->is_success()) {
                   7684: 	return 'failed';
                   7685:     }      
                   7686:     if ($reqtype eq 'HEAD') {
1.486     www      7687: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7688:     } elsif ($reqtype eq 'GET') {
                   7689: 	$$info = $response->content;
1.472     albertel 7690:     }
1.482     albertel 7691:     return 'ok';
1.36      albertel 7692: }
                   7693: 
1.481     raeburn  7694: sub readfile {
                   7695:     my $file = shift;
                   7696:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7697:     my $fh;
                   7698:     open($fh,"<$file");
                   7699:     my $a='';
1.800     albertel 7700:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7701:     return $a;
                   7702: }
                   7703: 
1.36      albertel 7704: sub filelocation {
1.590     banghart 7705:     my ($dir,$file) = @_;
                   7706:     my $location;
                   7707:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7708: 
                   7709:     if ($file =~ m-^/adm/-) {
                   7710: 	$file=~s-^/adm/wrapper/-/-;
                   7711: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7712:     }
1.882     albertel 7713: 
1.590     banghart 7714:     if ($file=~m:^/~:) { # is a contruction space reference
                   7715:         $location = $file;
                   7716:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7717:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7718: 	# is a correct contruction space reference
                   7719:         $location = $file;
1.609     banghart 7720:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7721:         my ($udom,$uname,$filename)=
1.811     albertel 7722:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7723:         my $home=&homeserver($uname,$udom);
                   7724:         my $is_me=0;
                   7725:         my @ids=&current_machine_ids();
                   7726:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7727:         if ($is_me) {
1.740     www      7728:   	    $location=&propath($udom,$uname).
1.590     banghart 7729:   	      '/userfiles/'.$filename;
                   7730:         } else {
                   7731:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7732:   	      $udom.'/'.$uname.'/'.$filename;
                   7733:         }
1.882     albertel 7734:     } elsif ($file =~ m-^/adm/-) {
                   7735: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7736:     } else {
                   7737:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7738:         $file=~s:^/res/:/:;
                   7739:         if ( !( $file =~ m:^/:) ) {
                   7740:             $location = $dir. '/'.$file;
                   7741:         } else {
                   7742:             $location = '/home/httpd/html/res'.$file;
                   7743:         }
1.59      albertel 7744:     }
1.590     banghart 7745:     $location=~s://+:/:g; # remove duplicate /
                   7746:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7747:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7748:     return $location;
1.46      www      7749: }
1.36      albertel 7750: 
1.46      www      7751: sub hreflocation {
                   7752:     my ($dir,$file)=@_;
1.460     albertel 7753:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7754: 	$file=filelocation($dir,$file);
1.700     albertel 7755:     } elsif ($file=~m-^/adm/-) {
                   7756: 	$file=~s-^/adm/wrapper/-/-;
                   7757: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7758:     }
                   7759:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7760: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7761:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7762: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7763:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7764: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7765: 	    -/uploaded/$1/$2/-x;
1.46      www      7766:     }
1.910.2.1  albertel 7767:     if ($file=~ m{^/userfiles/}) {
                   7768: 	$file =~ s{^/userfiles/}{/uploaded/};
                   7769:     }
1.462     albertel 7770:     return $file;
1.465     albertel 7771: }
                   7772: 
                   7773: sub current_machine_domains {
1.853     albertel 7774:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7775: }
                   7776: 
                   7777: sub machine_domains {
                   7778:     my ($hostname) = @_;
1.465     albertel 7779:     my @domains;
1.838     albertel 7780:     my %hostname = &all_hostnames();
1.465     albertel 7781:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7782: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7783: 	if ($hostname eq $name) {
1.844     albertel 7784: 	    push(@domains,&host_domain($id));
1.465     albertel 7785: 	}
                   7786:     }
                   7787:     return @domains;
                   7788: }
                   7789: 
                   7790: sub current_machine_ids {
1.853     albertel 7791:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7792: }
                   7793: 
                   7794: sub machine_ids {
                   7795:     my ($hostname) = @_;
                   7796:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7797:     my @ids;
1.888     albertel 7798:     my %name_to_host = &all_names();
1.889     albertel 7799:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7800: 	return @{ $name_to_host{$hostname} };
                   7801:     }
                   7802:     return;
1.31      www      7803: }
                   7804: 
1.824     raeburn  7805: sub additional_machine_domains {
                   7806:     my @domains;
                   7807:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7808:     while( my $line = <$fh>) {
                   7809:         $line =~ s/\s//g;
                   7810:         push(@domains,$line);
                   7811:     }
                   7812:     return @domains;
                   7813: }
                   7814: 
                   7815: sub default_login_domain {
                   7816:     my $domain = $perlvar{'lonDefDomain'};
                   7817:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7818:     foreach my $posdom (&current_machine_domains(),
                   7819:                         &additional_machine_domains()) {
                   7820:         if (lc($posdom) eq lc($testdomain)) {
                   7821:             $domain=$posdom;
                   7822:             last;
                   7823:         }
                   7824:     }
                   7825:     return $domain;
                   7826: }
                   7827: 
1.31      www      7828: # ------------------------------------------------------------- Declutters URLs
                   7829: 
                   7830: sub declutter {
                   7831:     my $thisfn=shift;
1.569     albertel 7832:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7833:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7834:     $thisfn=~s/^\///;
1.697     albertel 7835:     $thisfn=~s|^adm/wrapper/||;
                   7836:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7837:     $thisfn=~s/^res\///;
1.235     www      7838:     $thisfn=~s/\?.+$//;
1.268     www      7839:     return $thisfn;
                   7840: }
                   7841: 
                   7842: # ------------------------------------------------------------- Clutter up URLs
                   7843: 
                   7844: sub clutter {
                   7845:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7846:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7847: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7848:        $thisfn='/res'.$thisfn; 
                   7849:     }
1.694     albertel 7850:     if ($thisfn !~m|/adm|) {
1.695     albertel 7851: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7852: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7853: 	} else {
                   7854: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7855: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7856: 	    if ($embstyle eq 'ssi'
                   7857: 		|| ($embstyle eq 'hdn')
                   7858: 		|| ($embstyle eq 'rat')
                   7859: 		|| ($embstyle eq 'prv')
                   7860: 		|| ($embstyle eq 'ign')) {
                   7861: 		#do nothing with these
                   7862: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7863: 		|| ($embstyle eq 'emb')
                   7864: 		|| ($embstyle eq 'wrp')) {
                   7865: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7866: 	    } elsif ($embstyle eq 'unk'
                   7867: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7868: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7869: 	    } else {
1.718     www      7870: #		&logthis("Got a blank emb style");
1.695     albertel 7871: 	    }
1.694     albertel 7872: 	}
                   7873:     }
1.31      www      7874:     return $thisfn;
1.12      www      7875: }
                   7876: 
1.787     albertel 7877: sub clutter_with_no_wrapper {
                   7878:     my $uri = &clutter(shift);
                   7879:     if ($uri =~ m-^/adm/-) {
                   7880: 	$uri =~ s-^/adm/wrapper/-/-;
                   7881: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7882:     }
                   7883:     return $uri;
                   7884: }
                   7885: 
1.557     albertel 7886: sub freeze_escape {
                   7887:     my ($value)=@_;
                   7888:     if (ref($value)) {
                   7889: 	$value=&nfreeze($value);
                   7890: 	return '__FROZEN__'.&escape($value);
                   7891:     }
                   7892:     return &escape($value);
                   7893: }
                   7894: 
1.11      www      7895: 
1.557     albertel 7896: sub thaw_unescape {
                   7897:     my ($value)=@_;
                   7898:     if ($value =~ /^__FROZEN__/) {
                   7899: 	substr($value,0,10,undef);
                   7900: 	$value=&unescape($value);
                   7901: 	return &thaw($value);
                   7902:     }
                   7903:     return &unescape($value);
                   7904: }
                   7905: 
1.436     albertel 7906: sub correct_line_ends {
                   7907:     my ($result)=@_;
                   7908:     $$result =~s/\r\n/\n/mg;
                   7909:     $$result =~s/\r/\n/mg;
1.415     albertel 7910: }
1.1       albertel 7911: # ================================================================ Main Program
                   7912: 
1.184     www      7913: sub goodbye {
1.204     albertel 7914:    &logthis("Starting Shut down");
1.443     albertel 7915: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7916:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7917: #converted
1.599     albertel 7918: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7919:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7920: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7921: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7922: #1.1 only
1.870     albertel 7923: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7924: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7925: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7926: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7927:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7928:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7929:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7930:    &flushcourselogs();
                   7931:    &logthis("Shutting down");
                   7932: }
                   7933: 
1.852     albertel 7934: sub get_dns {
1.869     albertel 7935:     my ($url,$func,$ignore_cache) = @_;
                   7936:     if (!$ignore_cache) {
                   7937: 	my ($content,$cached)=
                   7938: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7939: 	if ($cached) {
                   7940: 	    &$func($content);
                   7941: 	    return;
                   7942: 	}
                   7943:     }
                   7944: 
                   7945:     my %alldns;
1.852     albertel 7946:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7947:     foreach my $dns (<$config>) {
                   7948: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7949: 	$alldns{$1} = 1;
                   7950:     }
                   7951:     while (%alldns) {
                   7952: 	my ($dns) = keys(%alldns);
                   7953: 	delete($alldns{$dns});
1.852     albertel 7954: 	my $ua=new LWP::UserAgent;
                   7955: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7956: 	my $response=$ua->request($request);
                   7957: 	next if ($response->is_error());
                   7958: 	my @content = split("\n",$response->content);
1.869     albertel 7959: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7960: 	&$func(\@content);
1.869     albertel 7961: 	return;
1.852     albertel 7962:     }
                   7963:     close($config);
1.871     albertel 7964:     my $which = (split('/',$url))[3];
                   7965:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7966:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7967:     my @content = <$config>;
                   7968:     &$func(\@content);
                   7969:     return;
1.852     albertel 7970: }
1.327     albertel 7971: # ------------------------------------------------------------ Read domain file
                   7972: {
1.852     albertel 7973:     my $loaded;
1.846     albertel 7974:     my %domain;
                   7975: 
1.852     albertel 7976:     sub parse_domain_tab {
                   7977: 	my ($lines) = @_;
                   7978: 	foreach my $line (@$lines) {
                   7979: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7980: 
1.846     albertel 7981: 	    chomp($line);
1.852     albertel 7982: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7983: 	    my %this_domain;
                   7984: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7985: 			       'lang_def', 'city', 'longi', 'lati',
                   7986: 			       'primary') {
                   7987: 		$this_domain{$field} = shift(@elements);
                   7988: 	    }
                   7989: 	    $domain{$name} = \%this_domain;
1.852     albertel 7990: 	}
                   7991:     }
1.864     albertel 7992: 
                   7993:     sub reset_domain_info {
                   7994: 	undef($loaded);
                   7995: 	undef(%domain);
                   7996:     }
                   7997: 
1.852     albertel 7998:     sub load_domain_tab {
1.869     albertel 7999: 	my ($ignore_cache) = @_;
                   8000: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8001: 	my $fh;
                   8002: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8003: 	    my @lines = <$fh>;
                   8004: 	    &parse_domain_tab(\@lines);
1.448     albertel 8005: 	}
1.852     albertel 8006: 	close($fh);
                   8007: 	$loaded = 1;
1.327     albertel 8008:     }
1.846     albertel 8009: 
                   8010:     sub domain {
1.852     albertel 8011: 	&load_domain_tab() if (!$loaded);
                   8012: 
1.846     albertel 8013: 	my ($name,$what) = @_;
                   8014: 	return if ( !exists($domain{$name}) );
                   8015: 
                   8016: 	if (!$what) {
                   8017: 	    return $domain{$name}{'description'};
                   8018: 	}
                   8019: 	return $domain{$name}{$what};
                   8020:     }
1.327     albertel 8021: }
                   8022: 
                   8023: 
1.1       albertel 8024: # ------------------------------------------------------------- Read hosts file
                   8025: {
1.838     albertel 8026:     my %hostname;
1.844     albertel 8027:     my %hostdom;
1.845     albertel 8028:     my %libserv;
1.852     albertel 8029:     my $loaded;
1.888     albertel 8030:     my %name_to_host;
1.852     albertel 8031: 
                   8032:     sub parse_hosts_tab {
                   8033: 	my ($file) = @_;
                   8034: 	foreach my $configline (@$file) {
                   8035: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8036: 	    next if ($configline =~ /^\^/);
                   8037: 	    chomp($configline);
                   8038: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8039: 	    $name=~s/\s//g;
                   8040: 	    if ($id && $domain && $role && $name) {
                   8041: 		$hostname{$id}=$name;
1.888     albertel 8042: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8043: 		$hostdom{$id}=$domain;
                   8044: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8045: 	    }
                   8046: 	}
                   8047:     }
1.864     albertel 8048:     
                   8049:     sub reset_hosts_info {
1.897     albertel 8050: 	&purge_remembered();
1.864     albertel 8051: 	&reset_domain_info();
                   8052: 	&reset_hosts_ip_info();
1.892     albertel 8053: 	undef(%name_to_host);
1.864     albertel 8054: 	undef(%hostname);
                   8055: 	undef(%hostdom);
                   8056: 	undef(%libserv);
                   8057: 	undef($loaded);
                   8058:     }
1.1       albertel 8059: 
1.852     albertel 8060:     sub load_hosts_tab {
1.869     albertel 8061: 	my ($ignore_cache) = @_;
                   8062: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8063: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8064: 	my @config = <$config>;
                   8065: 	&parse_hosts_tab(\@config);
                   8066: 	close($config);
                   8067: 	$loaded=1;
1.1       albertel 8068:     }
1.852     albertel 8069: 
1.838     albertel 8070:     sub hostname {
1.852     albertel 8071: 	&load_hosts_tab() if (!$loaded);
                   8072: 
1.838     albertel 8073: 	my ($lonid) = @_;
                   8074: 	return $hostname{$lonid};
                   8075:     }
1.845     albertel 8076: 
1.838     albertel 8077:     sub all_hostnames {
1.852     albertel 8078: 	&load_hosts_tab() if (!$loaded);
                   8079: 
1.838     albertel 8080: 	return %hostname;
                   8081:     }
1.845     albertel 8082: 
1.888     albertel 8083:     sub all_names {
                   8084: 	&load_hosts_tab() if (!$loaded);
                   8085: 
                   8086: 	return %name_to_host;
                   8087:     }
                   8088: 
1.845     albertel 8089:     sub is_library {
1.852     albertel 8090: 	&load_hosts_tab() if (!$loaded);
                   8091: 
1.845     albertel 8092: 	return exists($libserv{$_[0]});
                   8093:     }
                   8094: 
                   8095:     sub all_library {
1.852     albertel 8096: 	&load_hosts_tab() if (!$loaded);
                   8097: 
1.845     albertel 8098: 	return %libserv;
                   8099:     }
                   8100: 
1.841     albertel 8101:     sub get_servers {
1.852     albertel 8102: 	&load_hosts_tab() if (!$loaded);
                   8103: 
1.841     albertel 8104: 	my ($domain,$type) = @_;
                   8105: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8106: 	                                          : %hostname;
                   8107: 	my %result;
1.842     albertel 8108: 	if (ref($domain) eq 'ARRAY') {
                   8109: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8110: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8111: 		    $result{$host} = $hostname;
                   8112: 		}
                   8113: 	    }
                   8114: 	} else {
                   8115: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8116: 		if ($hostdom{$host} eq $domain) {
                   8117: 		    $result{$host} = $hostname;
                   8118: 		}
1.841     albertel 8119: 	    }
                   8120: 	}
                   8121: 	return %result;
                   8122:     }
1.845     albertel 8123: 
1.844     albertel 8124:     sub host_domain {
1.852     albertel 8125: 	&load_hosts_tab() if (!$loaded);
                   8126: 
1.844     albertel 8127: 	my ($lonid) = @_;
                   8128: 	return $hostdom{$lonid};
                   8129:     }
                   8130: 
1.841     albertel 8131:     sub all_domains {
1.852     albertel 8132: 	&load_hosts_tab() if (!$loaded);
                   8133: 
1.841     albertel 8134: 	my %seen;
                   8135: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8136: 	return @uniq;
                   8137:     }
1.1       albertel 8138: }
                   8139: 
1.847     albertel 8140: { 
                   8141:     my %iphost;
1.856     albertel 8142:     my %name_to_ip;
                   8143:     my %lonid_to_ip;
1.869     albertel 8144: 
1.847     albertel 8145:     sub get_hosts_from_ip {
                   8146: 	my ($ip) = @_;
                   8147: 	my %iphosts = &get_iphost();
                   8148: 	if (ref($iphosts{$ip})) {
                   8149: 	    return @{$iphosts{$ip}};
                   8150: 	}
                   8151: 	return;
1.839     albertel 8152:     }
1.864     albertel 8153:     
                   8154:     sub reset_hosts_ip_info {
                   8155: 	undef(%iphost);
                   8156: 	undef(%name_to_ip);
                   8157: 	undef(%lonid_to_ip);
                   8158:     }
1.856     albertel 8159: 
                   8160:     sub get_host_ip {
                   8161: 	my ($lonid) = @_;
                   8162: 	if (exists($lonid_to_ip{$lonid})) {
                   8163: 	    return $lonid_to_ip{$lonid};
                   8164: 	}
                   8165: 	my $name=&hostname($lonid);
                   8166:    	my $ip = gethostbyname($name);
                   8167: 	return if (!$ip || length($ip) ne 4);
                   8168: 	$ip=inet_ntoa($ip);
                   8169: 	$name_to_ip{$name}   = $ip;
                   8170: 	$lonid_to_ip{$lonid} = $ip;
                   8171: 	return $ip;
                   8172:     }
1.847     albertel 8173:     
                   8174:     sub get_iphost {
1.869     albertel 8175: 	my ($ignore_cache) = @_;
1.894     albertel 8176: 
1.869     albertel 8177: 	if (!$ignore_cache) {
                   8178: 	    if (%iphost) {
                   8179: 		return %iphost;
                   8180: 	    }
                   8181: 	    my ($ip_info,$cached)=
                   8182: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8183: 	    if ($cached) {
                   8184: 		%iphost      = %{$ip_info->[0]};
                   8185: 		%name_to_ip  = %{$ip_info->[1]};
                   8186: 		%lonid_to_ip = %{$ip_info->[2]};
                   8187: 		return %iphost;
                   8188: 	    }
                   8189: 	}
1.894     albertel 8190: 
                   8191: 	# get yesterday's info for fallback
                   8192: 	my %old_name_to_ip;
                   8193: 	my ($ip_info,$cached)=
                   8194: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8195: 	if ($cached) {
                   8196: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8197: 	}
                   8198: 
1.888     albertel 8199: 	my %name_to_host = &all_names();
                   8200: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8201: 	    my $ip;
                   8202: 	    if (!exists($name_to_ip{$name})) {
                   8203: 		$ip = gethostbyname($name);
                   8204: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8205: 		    if (defined($old_name_to_ip{$name})) {
                   8206: 			$ip = $old_name_to_ip{$name};
                   8207: 			&logthis("Can't find $name defaulting to old $ip");
                   8208: 		    } else {
                   8209: 			&logthis("Name $name no IP found");
                   8210: 			next;
                   8211: 		    }
                   8212: 		} else {
                   8213: 		    $ip=inet_ntoa($ip);
1.847     albertel 8214: 		}
                   8215: 		$name_to_ip{$name} = $ip;
                   8216: 	    } else {
                   8217: 		$ip = $name_to_ip{$name};
1.653     albertel 8218: 	    }
1.888     albertel 8219: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8220: 		$lonid_to_ip{$id} = $ip;
                   8221: 	    }
                   8222: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8223: 	}
1.869     albertel 8224: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8225: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8226: 				      48*60*60);
1.869     albertel 8227: 
1.847     albertel 8228: 	return %iphost;
1.598     albertel 8229:     }
                   8230: }
                   8231: 
1.862     albertel 8232: BEGIN {
                   8233: 
                   8234: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8235:     unless ($readit) {
                   8236: {
                   8237:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8238:     %perlvar = (%perlvar,%{$configvars});
                   8239: }
                   8240: 
                   8241: 
1.1       albertel 8242: # ------------------------------------------------------ Read spare server file
                   8243: {
1.448     albertel 8244:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8245: 
                   8246:     while (my $configline=<$config>) {
                   8247:        chomp($configline);
1.284     matthew  8248:        if ($configline) {
1.784     albertel 8249: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8250: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8251: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8252:        }
                   8253:     }
1.448     albertel 8254:     close($config);
1.1       albertel 8255: }
1.11      www      8256: # ------------------------------------------------------------ Read permissions
                   8257: {
1.448     albertel 8258:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8259: 
                   8260:     while (my $configline=<$config>) {
1.448     albertel 8261: 	chomp($configline);
                   8262: 	if ($configline) {
                   8263: 	    my ($role,$perm)=split(/ /,$configline);
                   8264: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8265: 	}
1.11      www      8266:     }
1.448     albertel 8267:     close($config);
1.11      www      8268: }
                   8269: 
                   8270: # -------------------------------------------- Read plain texts for permissions
                   8271: {
1.448     albertel 8272:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8273: 
                   8274:     while (my $configline=<$config>) {
1.448     albertel 8275: 	chomp($configline);
                   8276: 	if ($configline) {
1.742     raeburn  8277: 	    my ($short,@plain)=split(/:/,$configline);
                   8278:             %{$prp{$short}} = ();
                   8279: 	    if (@plain > 0) {
                   8280:                 $prp{$short}{'std'} = $plain[0];
                   8281:                 for (my $i=1; $i<@plain; $i++) {
                   8282:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8283:                 }
                   8284:             }
1.448     albertel 8285: 	}
1.135     www      8286:     }
1.448     albertel 8287:     close($config);
1.135     www      8288: }
                   8289: 
                   8290: # ---------------------------------------------------------- Read package table
                   8291: {
1.448     albertel 8292:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8293: 
                   8294:     while (my $configline=<$config>) {
1.483     albertel 8295: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8296: 	chomp($configline);
                   8297: 	my ($short,$plain)=split(/:/,$configline);
                   8298: 	my ($pack,$name)=split(/\&/,$short);
                   8299: 	if ($plain ne '') {
                   8300: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8301: 	    $packagetab{$short}=$plain; 
                   8302: 	}
1.11      www      8303:     }
1.448     albertel 8304:     close($config);
1.329     matthew  8305: }
                   8306: 
                   8307: # ------------- set up temporary directory
                   8308: {
                   8309:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8310: 
1.11      www      8311: }
                   8312: 
1.794     albertel 8313: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8314: 				'compress_threshold'=> 20_000,
                   8315:  			        });
1.185     www      8316: 
1.281     www      8317: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8318: $dumpcount=0;
1.22      www      8319: 
1.163     harris41 8320: &logtouch();
1.672     albertel 8321: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8322: $readit=1;
1.564     albertel 8323:     {
                   8324: 	use integer;
                   8325: 	my $test=(2**32)+1;
1.568     albertel 8326: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8327: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8328:     }
1.195     www      8329: }
1.1       albertel 8330: }
1.179     www      8331: 
1.1       albertel 8332: 1;
1.191     harris41 8333: __END__
                   8334: 
1.243     albertel 8335: =pod
                   8336: 
1.191     harris41 8337: =head1 NAME
                   8338: 
1.243     albertel 8339: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8340: 
                   8341: =head1 SYNOPSIS
                   8342: 
1.243     albertel 8343: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8344: 
                   8345:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8346: 
1.243     albertel 8347: Common parameters:
                   8348: 
                   8349: =over 4
                   8350: 
                   8351: =item *
                   8352: 
                   8353: $uname : an internal username (if $cname expecting a course Id specifically)
                   8354: 
                   8355: =item *
                   8356: 
                   8357: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8358: 
                   8359: =item *
                   8360: 
                   8361: $symb : a resource instance identifier
                   8362: 
                   8363: =item *
                   8364: 
                   8365: $namespace : the name of a .db file that contains the data needed or
                   8366: being set.
                   8367: 
                   8368: =back
                   8369: 
1.394     bowersj2 8370: =head1 OVERVIEW
1.191     harris41 8371: 
1.394     bowersj2 8372: lonnet provides subroutines which interact with the
                   8373: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8374: about classes, users, and resources.
1.243     albertel 8375: 
                   8376: For many of these objects you can also use this to store data about
                   8377: them or modify them in various ways.
1.191     harris41 8378: 
1.394     bowersj2 8379: =head2 Symbs
1.191     harris41 8380: 
1.394     bowersj2 8381: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8382: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8383: map, the resource number of the resource in the map, and the URL of
                   8384: the resource itself. The latter is somewhat redundant, but might help
                   8385: if maps change.
                   8386: 
                   8387: An example is
                   8388: 
                   8389:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8390: 
                   8391: The respective map entry is
                   8392: 
                   8393:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8394:   title="Problem 2">
                   8395:  </resource>
                   8396: 
                   8397: Symbs are used by the random number generator, as well as to store and
                   8398: restore data specific to a certain instance of for example a problem.
                   8399: 
                   8400: =head2 Storing And Retrieving Data
                   8401: 
                   8402: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8403: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8404: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8405: is is the non-critical message twin of cstore. These functions are for
                   8406: handlers to store a perl hash to a user's permanent data space in an
                   8407: easy manner, and to retrieve it again on another call. It is expected
                   8408: that a handler would use this once at the beginning to retrieve data,
                   8409: and then again once at the end to send only the new data back.
                   8410: 
                   8411: The data is stored in the user's data directory on the user's
                   8412: homeserver under the ID of the course.
                   8413: 
                   8414: The hash that is returned by restore will have all of the previous
                   8415: value for all of the elements of the hash.
                   8416: 
                   8417: Example:
                   8418: 
                   8419:  #creating a hash
                   8420:  my %hash;
                   8421:  $hash{'foo'}='bar';
                   8422: 
                   8423:  #storing it
                   8424:  &Apache::lonnet::cstore(\%hash);
                   8425: 
                   8426:  #changing a value
                   8427:  $hash{'foo'}='notbar';
                   8428: 
                   8429:  #adding a new value
                   8430:  $hash{'bar'}='foo';
                   8431:  &Apache::lonnet::cstore(\%hash);
                   8432: 
                   8433:  #retrieving the hash
                   8434:  my %history=&Apache::lonnet::restore();
                   8435: 
                   8436:  #print the hash
                   8437:  foreach my $key (sort(keys(%history))) {
                   8438:    print("\%history{$key} = $history{$key}");
                   8439:  }
                   8440: 
                   8441: Will print out:
1.191     harris41 8442: 
1.394     bowersj2 8443:  %history{1:foo} = bar
                   8444:  %history{1:keys} = foo:timestamp
                   8445:  %history{1:timestamp} = 990455579
                   8446:  %history{2:bar} = foo
                   8447:  %history{2:foo} = notbar
                   8448:  %history{2:keys} = foo:bar:timestamp
                   8449:  %history{2:timestamp} = 990455580
                   8450:  %history{bar} = foo
                   8451:  %history{foo} = notbar
                   8452:  %history{timestamp} = 990455580
                   8453:  %history{version} = 2
                   8454: 
                   8455: Note that the special hash entries C<keys>, C<version> and
                   8456: C<timestamp> were added to the hash. C<version> will be equal to the
                   8457: total number of versions of the data that have been stored. The
                   8458: C<timestamp> attribute will be the UNIX time the hash was
                   8459: stored. C<keys> is available in every historical section to list which
                   8460: keys were added or changed at a specific historical revision of a
                   8461: hash.
                   8462: 
                   8463: B<Warning>: do not store the hash that restore returns directly. This
                   8464: will cause a mess since it will restore the historical keys as if the
                   8465: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8466: 
1.394     bowersj2 8467: Calling convention:
1.191     harris41 8468: 
1.394     bowersj2 8469:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8470:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8471: 
1.394     bowersj2 8472: For more detailed information, see lonnet specific documentation.
1.191     harris41 8473: 
1.394     bowersj2 8474: =head1 RETURN MESSAGES
1.191     harris41 8475: 
1.394     bowersj2 8476: =over 4
1.191     harris41 8477: 
1.394     bowersj2 8478: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8479: 
1.394     bowersj2 8480: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8481: when the connection is brought back up
1.191     harris41 8482: 
1.394     bowersj2 8483: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8484: for later delivery
1.191     harris41 8485: 
1.394     bowersj2 8486: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8487: 
1.394     bowersj2 8488: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8489: that was requested
1.191     harris41 8490: 
1.243     albertel 8491: =back
1.191     harris41 8492: 
1.243     albertel 8493: =head1 PUBLIC SUBROUTINES
1.191     harris41 8494: 
1.243     albertel 8495: =head2 Session Environment Functions
1.191     harris41 8496: 
1.243     albertel 8497: =over 4
1.191     harris41 8498: 
1.394     bowersj2 8499: =item * 
                   8500: X<appenv()>
                   8501: B<appenv(%hash)>: the value of %hash is written to
                   8502: the user envirnoment file, and will be restored for each access this
1.620     albertel 8503: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8504: process
1.191     harris41 8505: 
                   8506: =item *
1.394     bowersj2 8507: X<delenv()>
                   8508: B<delenv($regexp)>: removes all items from the session
                   8509: environment file that matches the regular expression in $regexp. The
1.620     albertel 8510: values are also delted from the current processes %env.
1.191     harris41 8511: 
1.795     albertel 8512: =item * get_env_multiple($name) 
                   8513: 
                   8514: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8515: values may be defined and end up as an array ref.
                   8516: 
                   8517: returns an array of values
                   8518: 
1.243     albertel 8519: =back
                   8520: 
                   8521: =head2 User Information
1.191     harris41 8522: 
1.243     albertel 8523: =over 4
1.191     harris41 8524: 
                   8525: =item *
1.394     bowersj2 8526: X<queryauthenticate()>
                   8527: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8528: authentication scheme
                   8529: 
                   8530: =item *
1.394     bowersj2 8531: X<authenticate()>
                   8532: B<authenticate($uname,$upass,$udom)>: try to
                   8533: authenticate user from domain's lib servers (first use the current
                   8534: one). C<$upass> should be the users password.
1.191     harris41 8535: 
                   8536: =item *
1.394     bowersj2 8537: X<homeserver()>
                   8538: B<homeserver($uname,$udom)>: find the server which has
                   8539: the user's directory and files (there must be only one), this caches
                   8540: the answer, and also caches if there is a borken connection.
1.191     harris41 8541: 
                   8542: =item *
1.394     bowersj2 8543: X<idget()>
                   8544: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8545: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8546: username, and only 1 username per ID in a specific domain) (returns
                   8547: hash: id=>name,id=>name)
1.191     harris41 8548: 
                   8549: =item *
1.394     bowersj2 8550: X<idrget()>
                   8551: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8552: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8553: 
                   8554: =item *
1.394     bowersj2 8555: X<idput()>
                   8556: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8557: 
                   8558: =item *
1.394     bowersj2 8559: X<rolesinit()>
                   8560: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8561: 
                   8562: =item *
1.551     albertel 8563: X<getsection()>
                   8564: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8565: course $cname, return section name/number or '' for "not in course"
                   8566: and '-1' for "no section"
                   8567: 
                   8568: =item *
1.394     bowersj2 8569: X<userenvironment()>
                   8570: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8571: passed in @what from the requested user's environment, returns a hash
                   8572: 
1.858     raeburn  8573: =item * 
                   8574: X<userlog_query()>
1.859     albertel 8575: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8576: activity.log file. %filters defines filters applied when parsing the
                   8577: log file. These can be start or end timestamps, or the type of action
                   8578: - log to look for Login or Logout events, check for Checkin or
                   8579: Checkout, role for role selection. The response is in the form
                   8580: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8581: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8582: 
1.243     albertel 8583: =back
                   8584: 
                   8585: =head2 User Roles
                   8586: 
                   8587: =over 4
                   8588: 
                   8589: =item *
                   8590: 
1.810     raeburn  8591: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8592:  F: full access
                   8593:  U,I,K: authentication modes (cxx only)
                   8594:  '': forbidden
                   8595:  1: user needs to choose course
                   8596:  2: browse allowed
1.766     albertel 8597:  A: passphrase authentication needed
1.243     albertel 8598: 
                   8599: =item *
                   8600: 
                   8601: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8602: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8603: and course level
                   8604: 
                   8605: =item *
                   8606: 
                   8607: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8608: explanation of a user role term
                   8609: 
1.832     raeburn  8610: =item *
                   8611: 
1.858     raeburn  8612: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8613: All arguments are optional. Returns a hash of a roles, either for
                   8614: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8615: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8616: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8617: and value is set to colon-separated start and end times for the role.
                   8618: If no username and domain are specified, will default to current
                   8619: user/domain. Types, roles, and roledoms are references to arrays,
                   8620: of role statuses (active, future or previous), roles 
                   8621: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8622: to restrict the list of roles reported. If no array ref is 
                   8623: provided for types, will default to return only active roles.
1.834     albertel 8624: 
1.243     albertel 8625: =back
                   8626: 
                   8627: =head2 User Modification
                   8628: 
                   8629: =over 4
                   8630: 
                   8631: =item *
                   8632: 
                   8633: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8634: user for the level given by URL.  Optional start and end dates (leave empty
                   8635: string or zero for "no date")
1.191     harris41 8636: 
                   8637: =item *
                   8638: 
1.243     albertel 8639: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8640: change a users, password, possible return values are: ok,
                   8641: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8642: refused
1.191     harris41 8643: 
                   8644: =item *
                   8645: 
1.243     albertel 8646: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8647: 
                   8648: =item *
                   8649: 
1.243     albertel 8650: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8651: modify user
1.191     harris41 8652: 
                   8653: =item *
                   8654: 
1.286     matthew  8655: modifystudent
                   8656: 
                   8657: modify a students enrollment and identification information.
                   8658: The course id is resolved based on the current users environment.  
                   8659: This means the envoking user must be a course coordinator or otherwise
                   8660: associated with a course.
                   8661: 
1.297     matthew  8662: This call is essentially a wrapper for lonnet::modifyuser and
                   8663: lonnet::modify_student_enrollment
1.286     matthew  8664: 
                   8665: Inputs: 
                   8666: 
                   8667: =over 4
                   8668: 
                   8669: =item B<$udom> Students loncapa domain
                   8670: 
                   8671: =item B<$uname> Students loncapa login name
                   8672: 
                   8673: =item B<$uid> Students id/student number
                   8674: 
                   8675: =item B<$umode> Students authentication mode
                   8676: 
                   8677: =item B<$upass> Students password
                   8678: 
                   8679: =item B<$first> Students first name
                   8680: 
                   8681: =item B<$middle> Students middle name
                   8682: 
                   8683: =item B<$last> Students last name
                   8684: 
                   8685: =item B<$gene> Students generation
                   8686: 
                   8687: =item B<$usec> Students section in course
                   8688: 
                   8689: =item B<$end> Unix time of the roles expiration
                   8690: 
                   8691: =item B<$start> Unix time of the roles start date
                   8692: 
                   8693: =item B<$forceid> If defined, allow $uid to be changed
                   8694: 
                   8695: =item B<$desiredhome> server to use as home server for student
                   8696: 
                   8697: =back
1.297     matthew  8698: 
                   8699: =item *
                   8700: 
                   8701: modify_student_enrollment
                   8702: 
                   8703: Change a students enrollment status in a class.  The environment variable
                   8704: 'role.request.course' must be defined for this function to proceed.
                   8705: 
                   8706: Inputs:
                   8707: 
                   8708: =over 4
                   8709: 
                   8710: =item $udom, students domain
                   8711: 
                   8712: =item $uname, students name
                   8713: 
                   8714: =item $uid, students user id
                   8715: 
                   8716: =item $first, students first name
                   8717: 
                   8718: =item $middle
                   8719: 
                   8720: =item $last
                   8721: 
                   8722: =item $gene
                   8723: 
                   8724: =item $usec
                   8725: 
                   8726: =item $end
                   8727: 
                   8728: =item $start
                   8729: 
                   8730: =back
                   8731: 
1.191     harris41 8732: 
                   8733: =item *
                   8734: 
1.243     albertel 8735: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8736: custom role; give a custom role to a user for the level given by URL.  Specify
                   8737: name and domain of role author, and role name
1.191     harris41 8738: 
                   8739: =item *
                   8740: 
1.243     albertel 8741: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8742: 
                   8743: =item *
                   8744: 
1.243     albertel 8745: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8746: 
                   8747: =back
                   8748: 
                   8749: =head2 Course Infomation
                   8750: 
                   8751: =over 4
1.191     harris41 8752: 
                   8753: =item *
                   8754: 
1.631     albertel 8755: coursedescription($courseid) : returns a hash of information about the
                   8756: specified course id, including all environment settings for the
                   8757: course, the description of the course will be in the hash under the
                   8758: key 'description'
1.191     harris41 8759: 
                   8760: =item *
                   8761: 
1.624     albertel 8762: resdata($name,$domain,$type,@which) : request for current parameter
                   8763: setting for a specific $type, where $type is either 'course' or 'user',
                   8764: @what should be a list of parameters to ask about. This routine caches
                   8765: answers for 5 minutes.
1.243     albertel 8766: 
1.877     foxr     8767: =item *
                   8768: 
                   8769: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8770: data base, returning a hash that is keyed by the resource name and has
                   8771: values that are the resource value.  I believe that the timestamps and
                   8772: versions are also returned.
                   8773: 
                   8774: 
1.243     albertel 8775: =back
                   8776: 
                   8777: =head2 Course Modification
                   8778: 
                   8779: =over 4
1.191     harris41 8780: 
                   8781: =item *
                   8782: 
1.243     albertel 8783: writecoursepref($courseid,%prefs) : write preferences (environment
                   8784: database) for a course
1.191     harris41 8785: 
                   8786: =item *
                   8787: 
1.243     albertel 8788: createcourse($udom,$description,$url) : make/modify course
                   8789: 
                   8790: =back
                   8791: 
                   8792: =head2 Resource Subroutines
                   8793: 
                   8794: =over 4
1.191     harris41 8795: 
                   8796: =item *
                   8797: 
1.243     albertel 8798: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8799: 
                   8800: =item *
                   8801: 
1.243     albertel 8802: repcopy($filename) : subscribes to the requested file, and attempts to
                   8803: replicate from the owning library server, Might return
1.607     raeburn  8804: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8805: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8806: resource. Expects the local filesystem pathname
                   8807: (/home/httpd/html/res/....)
                   8808: 
                   8809: =back
                   8810: 
                   8811: =head2 Resource Information
                   8812: 
                   8813: =over 4
1.191     harris41 8814: 
                   8815: =item *
                   8816: 
1.243     albertel 8817: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8818: a vairety of different possible values, $varname should be a request
                   8819: string, and the other parameters can be used to specify who and what
                   8820: one is asking about.
                   8821: 
                   8822: Possible values for $varname are environment.lastname (or other item
                   8823: from the envirnment hash), user.name (or someother aspect about the
                   8824: user), resource.0.maxtries (or some other part and parameter of a
                   8825: resource)
1.204     albertel 8826: 
                   8827: =item *
                   8828: 
1.243     albertel 8829: directcondval($number) : get current value of a condition; reads from a state
                   8830: string
1.204     albertel 8831: 
                   8832: =item *
                   8833: 
1.243     albertel 8834: condval($condidx) : value of condition index based on state
1.204     albertel 8835: 
                   8836: =item *
                   8837: 
1.243     albertel 8838: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8839: resource's metadata, $what should be either a specific key, or either
                   8840: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8841: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8842: 
                   8843: this function automatically caches all requests
1.191     harris41 8844: 
                   8845: =item *
                   8846: 
1.243     albertel 8847: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8848: network of library servers; returns file handle of where SQL and regex results
                   8849: will be stored for query
1.191     harris41 8850: 
                   8851: =item *
                   8852: 
1.243     albertel 8853: symbread($filename) : return symbolic list entry (filename argument optional);
                   8854: returns the data handle
1.191     harris41 8855: 
                   8856: =item *
                   8857: 
1.243     albertel 8858: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8859: a possible symb for the URL in $thisfn, and if is an encryypted
                   8860: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8861: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8862: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8863: 
1.191     harris41 8864: 
                   8865: =item *
                   8866: 
1.243     albertel 8867: symbclean($symb) : removes versions numbers from a symb, returns the
                   8868: cleaned symb
1.191     harris41 8869: 
                   8870: =item *
                   8871: 
1.243     albertel 8872: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8873: course map, user must be in a course for it to work.
1.191     harris41 8874: 
                   8875: =item *
                   8876: 
1.243     albertel 8877: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8878: 
                   8879: =item *
                   8880: 
1.243     albertel 8881: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8882: a random seed, all arguments are optional, if they aren't sent it uses the
                   8883: environment to derive them. Note: if symb isn't sent and it can't get one
                   8884: from &symbread it will use the current time as its return value
1.191     harris41 8885: 
                   8886: =item *
                   8887: 
1.243     albertel 8888: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8889: unfakeable, receipt
1.191     harris41 8890: 
                   8891: =item *
                   8892: 
1.620     albertel 8893: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8894: 
                   8895: =item *
                   8896: 
1.243     albertel 8897: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8898: 
                   8899: =item *
                   8900: 
1.243     albertel 8901: 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 8902: 
                   8903: =item *
                   8904: 
1.243     albertel 8905: 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 8906: 
                   8907: =item *
                   8908: 
1.243     albertel 8909: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8910: 
                   8911: =item *
                   8912: 
1.243     albertel 8913: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8914: forcing spreadsheet to reevaluate the resource scores next time.
                   8915: 
                   8916: =back
                   8917: 
                   8918: =head2 Storing/Retreiving Data
                   8919: 
                   8920: =over 4
1.191     harris41 8921: 
                   8922: =item *
                   8923: 
1.243     albertel 8924: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8925: for this url; hashref needs to be given and should be a \%hashname; the
                   8926: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8927: be derived from the env
1.191     harris41 8928: 
                   8929: =item *
                   8930: 
1.243     albertel 8931: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8932: uses critical subroutine
1.191     harris41 8933: 
                   8934: =item *
                   8935: 
1.243     albertel 8936: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8937: all args are optional
1.191     harris41 8938: 
                   8939: =item *
                   8940: 
1.717     albertel 8941: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8942: dumps the complete (or key matching regexp) namespace into a hash
                   8943: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8944: normally &store()ed into
                   8945: 
                   8946: $range should be either an integer '100' (give me the first 100
                   8947:                                            matching records)
                   8948:               or be  two integers sperated by a - with no spaces
                   8949:                  '30-50' (give me the 30th through the 50th matching
                   8950:                           records)
                   8951: 
                   8952: 
                   8953: =item *
                   8954: 
                   8955: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8956: replaces a &store() version of data with a replacement set of data
                   8957: for a particular resource in a namespace passed in the $storehash hash 
                   8958: reference
                   8959: 
                   8960: =item *
                   8961: 
1.243     albertel 8962: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8963: works very similar to store/cstore, but all data is stored in a
                   8964: temporary location and can be reset using tmpreset, $storehash should
                   8965: be a hash reference, returns nothing on success
1.191     harris41 8966: 
                   8967: =item *
                   8968: 
1.243     albertel 8969: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8970: similar to restore, but all data is stored in a temporary location and
                   8971: can be reset using tmpreset. Returns a hash of values on success,
                   8972: error string otherwise.
1.191     harris41 8973: 
                   8974: =item *
                   8975: 
1.243     albertel 8976: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8977: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8978: 
                   8979: =item *
                   8980: 
1.243     albertel 8981: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8982: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8983: 
                   8984: =item *
                   8985: 
1.243     albertel 8986: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8987: namesp ($udom and $uname are optional)
1.191     harris41 8988: 
                   8989: =item *
                   8990: 
1.702     albertel 8991: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8992: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8993: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8994: 
1.702     albertel 8995: $range should be either an integer '100' (give me the first 100
                   8996:                                            matching records)
                   8997:               or be  two integers sperated by a - with no spaces
                   8998:                  '30-50' (give me the 30th through the 50th matching
                   8999:                           records)
1.449     matthew  9000: =item *
                   9001: 
                   9002: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9003: $store can be a scalar, an array reference, or if the amount to be 
                   9004: incremented is > 1, a hash reference.
                   9005: 
                   9006: ($udom and $uname are optional)
1.191     harris41 9007: 
                   9008: =item *
                   9009: 
1.243     albertel 9010: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9011: ($udom and $uname are optional)
1.191     harris41 9012: 
                   9013: =item *
                   9014: 
1.243     albertel 9015: cput($namespace,$storehash,$udom,$uname) : critical put
                   9016: ($udom and $uname are optional)
1.191     harris41 9017: 
                   9018: =item *
                   9019: 
1.748     albertel 9020: newput($namespace,$storehash,$udom,$uname) :
                   9021: 
                   9022: Attempts to store the items in the $storehash, but only if they don't
                   9023: currently exist, if this succeeds you can be certain that you have 
                   9024: successfully created a new key value pair in the $namespace db.
                   9025: 
                   9026: 
                   9027: Args:
                   9028:  $namespace: name of database to store values to
                   9029:  $storehash: hashref to store to the db
                   9030:  $udom: (optional) domain of user containing the db
                   9031:  $uname: (optional) name of user caontaining the db
                   9032: 
                   9033: Returns:
                   9034:  'ok' -> succeeded in storing all keys of $storehash
                   9035:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9036:                         least <key> already existed in the db (other
                   9037:                         requested keys may also already exist)
                   9038:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9039:  'con_lost' -> unable to contact request server
                   9040:  'refused' -> action was not allowed by remote machine
                   9041: 
                   9042: 
                   9043: =item *
                   9044: 
1.243     albertel 9045: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9046: reference filled in from namesp (encrypts the return communication)
                   9047: ($udom and $uname are optional)
1.191     harris41 9048: 
                   9049: =item *
                   9050: 
1.243     albertel 9051: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9052: critical subroutine
                   9053: 
1.806     raeburn  9054: =item *
                   9055: 
1.860     raeburn  9056: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9057: array reference filled in from namespace found in domain level on either
                   9058: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9059: 
                   9060: =item *
                   9061: 
1.860     raeburn  9062: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9063: domain level either on specified domain server ($uhome) or primary domain 
                   9064: server ($udom and $uhome are optional)
1.806     raeburn  9065: 
1.243     albertel 9066: =back
                   9067: 
                   9068: =head2 Network Status Functions
                   9069: 
                   9070: =over 4
1.191     harris41 9071: 
                   9072: =item *
                   9073: 
                   9074: dirlist($uri) : return directory list based on URI
                   9075: 
                   9076: =item *
                   9077: 
1.243     albertel 9078: spareserver() : find server with least workload from spare.tab
                   9079: 
                   9080: =back
                   9081: 
                   9082: =head2 Apache Request
                   9083: 
                   9084: =over 4
1.191     harris41 9085: 
                   9086: =item *
                   9087: 
1.243     albertel 9088: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9089: localhost, posts hash
                   9090: 
                   9091: =back
                   9092: 
                   9093: =head2 Data to String to Data
                   9094: 
                   9095: =over 4
1.191     harris41 9096: 
                   9097: =item *
                   9098: 
1.243     albertel 9099: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9100: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9101: 
                   9102: =item *
                   9103: 
1.243     albertel 9104: hashref2str($hashref) : convert a hashref into a string complete with
                   9105: escaping and '=' and '&' separators, supports elements that are
                   9106: arrayrefs and hashrefs
1.191     harris41 9107: 
                   9108: =item *
                   9109: 
1.243     albertel 9110: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9111: with escaping and '&' separators, supports elements that are arrayrefs
                   9112: and hashrefs
1.191     harris41 9113: 
                   9114: =item *
                   9115: 
1.243     albertel 9116: str2hash($string) : convert string to hash using unescaping and
                   9117: splitting on '=' and '&', supports elements that are arrayrefs and
                   9118: hashrefs
1.191     harris41 9119: 
                   9120: =item *
                   9121: 
1.243     albertel 9122: str2array($string) : convert string to hash using unescaping and
                   9123: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9124: 
                   9125: =back
                   9126: 
                   9127: =head2 Logging Routines
                   9128: 
                   9129: =over 4
                   9130: 
                   9131: These routines allow one to make log messages in the lonnet.log and
                   9132: lonnet.perm logfiles.
1.191     harris41 9133: 
                   9134: =item *
                   9135: 
1.243     albertel 9136: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9137: 
                   9138: =item *
                   9139: 
1.243     albertel 9140: logthis() : append message to the normal lonnet.log file, it gets
                   9141: preiodically rolled over and deleted.
1.191     harris41 9142: 
                   9143: =item *
                   9144: 
1.243     albertel 9145: logperm() : append a permanent message to lonnet.perm.log, this log
                   9146: file never gets deleted by any automated portion of the system, only
                   9147: messages of critical importance should go in here.
                   9148: 
                   9149: =back
                   9150: 
                   9151: =head2 General File Helper Routines
                   9152: 
                   9153: =over 4
1.191     harris41 9154: 
                   9155: =item *
                   9156: 
1.481     raeburn  9157: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9158: (a) files in /uploaded
                   9159:   (i) If a local copy of the file exists - 
                   9160:       compares modification date of local copy with last-modified date for 
                   9161:       definitive version stored on home server for course. If local copy is 
                   9162:       stale, requests a new version from the home server and stores it. 
                   9163:       If the original has been removed from the home server, then local copy 
                   9164:       is unlinked.
                   9165:   (ii) If local copy does not exist -
                   9166:       requests the file from the home server and stores it. 
                   9167:   
                   9168:   If $caller is 'uploadrep':  
                   9169:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9170:     for request for files originally uploaded via DOCS. 
                   9171:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9172:   
                   9173:   Otherwise:
                   9174:      This indicates a call from the content generation phase of the request.
                   9175:      -  returns the entire contents of the file or -1.
                   9176:      
                   9177: (b) files in /res
                   9178:    - returns the entire contents of a file or -1; 
                   9179:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9180: 
1.712     albertel 9181: 
                   9182: =item *
                   9183: 
                   9184: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9185:                   reference
                   9186: 
                   9187: returns either a stat() list of data about the file or an empty list
                   9188: if the file doesn't exist or couldn't find out about it (connection
                   9189: problems or user unknown)
                   9190: 
1.191     harris41 9191: =item *
                   9192: 
1.243     albertel 9193: filelocation($dir,$file) : returns file system location of a file
                   9194: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9195: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9196: and a file of ../bob will become /a/bob)
1.191     harris41 9197: 
                   9198: =item *
                   9199: 
                   9200: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9201: filelocation except for hrefs
                   9202: 
                   9203: =item *
                   9204: 
                   9205: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9206: 
1.243     albertel 9207: =back
                   9208: 
1.608     albertel 9209: =head2 Usererfile file routines (/uploaded*)
                   9210: 
                   9211: =over 4
                   9212: 
                   9213: =item *
                   9214: 
                   9215: userfileupload(): main rotine for putting a file in a user or course's
                   9216:                   filespace, arguments are,
                   9217: 
1.620     albertel 9218:  formname - required - this is the name of the element in $env where the
1.608     albertel 9219:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9220:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9221:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9222:  coursedoc - if true, store the file in the course of the active role
                   9223:              of the current user
                   9224:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9225:          if undefined, it will be placed in "unknown"
                   9226: 
                   9227:  (This routine calls clean_filename() to remove any dangerous
                   9228:  characters from the filename, and then calls finuserfileupload() to
                   9229:  complete the transaction)
                   9230: 
                   9231:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9232:  and /adm/notfound.html if unsuccessful
                   9233: 
                   9234: =item *
                   9235: 
                   9236: clean_filename(): routine for cleaing a filename up for storage in
                   9237:                  userfile space, argument is:
                   9238: 
                   9239:  filename - proposed filename
                   9240: 
                   9241: returns: the new clean filename
                   9242: 
                   9243: =item *
                   9244: 
                   9245: finishuserfileupload(): routine that creaes and sends the file to
                   9246: userspace, probably shouldn't be called directly
                   9247: 
                   9248:   docuname: username or courseid of destination for the file
                   9249:   docudom: domain of user/course of destination for the file
                   9250:   formname: same as for userfileupload()
                   9251:   fname: filename (inculding subdirectories) for the file
                   9252: 
                   9253:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9254:  and /adm/notfound.html if unsuccessful
                   9255: 
                   9256: =item *
                   9257: 
                   9258: renameuserfile(): renames an existing userfile to a new name
                   9259: 
                   9260:   Args:
                   9261:    docuname: username or courseid of destination for the file
                   9262:    docudom: domain of user/course of destination for the file
                   9263:    old: current file name (including any subdirs under userfiles)
                   9264:    new: desired file name (including any subdirs under userfiles)
                   9265: 
                   9266: =item *
                   9267: 
                   9268: mkdiruserfile(): creates a directory is a userfiles dir
                   9269: 
                   9270:   Args:
                   9271:    docuname: username or courseid of destination for the file
                   9272:    docudom: domain of user/course of destination for the file
                   9273:    dir: dir to create (including any subdirs under userfiles)
                   9274: 
                   9275: =item *
                   9276: 
                   9277: removeuserfile(): removes a file that exists in userfiles
                   9278: 
                   9279:   Args:
                   9280:    docuname: username or courseid of destination for the file
                   9281:    docudom: domain of user/course of destination for the file
                   9282:    fname: filname to delete (including any subdirs under userfiles)
                   9283: 
                   9284: =item *
                   9285: 
                   9286: removeuploadedurl(): convience function for removeuserfile()
                   9287: 
                   9288:   Args:
                   9289:    url:  a full /uploaded/... url to delete
                   9290: 
1.747     albertel 9291: =item * 
                   9292: 
                   9293: get_portfile_permissions():
                   9294:   Args:
                   9295:     domain: domain of user or course contain the portfolio files
                   9296:     user: name of user or num of course contain the portfolio files
                   9297:   Returns:
                   9298:     hashref of a dump of the proper file_permissions.db
                   9299:    
                   9300: 
                   9301: =item * 
                   9302: 
                   9303: get_access_controls():
                   9304: 
                   9305: Args:
                   9306:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9307:   group: (optional) the group you want the files associated with
                   9308:   file: (optional) the file you want access info on
                   9309: 
                   9310: Returns:
1.749     raeburn  9311:     a hash (keys are file names) of hashes containing
                   9312:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9313:         values are XML containing access control settings (see below) 
1.747     albertel 9314: 
                   9315: Internal notes:
                   9316: 
1.749     raeburn  9317:  access controls are stored in file_permissions.db as key=value pairs.
                   9318:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9319:         where scope -> public,guest,course,group,domains or users.
                   9320:               end -> UNIX time for end of access (0 -> no end date)
                   9321:               start -> UNIX time for start of access
                   9322: 
                   9323:     value -> XML description of access control
                   9324:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9325:             <start></start>
                   9326:             <end></end>
                   9327: 
                   9328:             <password></password>  for scope type = guest
                   9329: 
                   9330:             <domain></domain>     for scope type = course or group
                   9331:             <number></number>
                   9332:             <roles id="">
                   9333:              <role></role>
                   9334:              <access></access>
                   9335:              <section></section>
                   9336:              <group></group>
                   9337:             </roles>
                   9338: 
                   9339:             <dom></dom>         for scope type = domains
                   9340: 
                   9341:             <users>             for scope type = users
                   9342:              <user>
                   9343:               <uname></uname>
                   9344:               <udom></udom>
                   9345:              </user>
                   9346:             </users>
                   9347:            </scope> 
                   9348:               
                   9349:  Access data is also aggregated for each file in an additional key=value pair:
                   9350:  key -> path to file/file_name\0accesscontrol 
                   9351:  value -> reference to hash
                   9352:           hash contains key = value pairs
                   9353:           where key = uniqueID:scope_end_start
                   9354:                 value = UNIX time record was last updated
                   9355: 
                   9356:           Used to improve speed of look-ups of access controls for each file.  
                   9357:  
                   9358:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9359: 
                   9360: modify_access_controls():
                   9361: 
                   9362: Modifies access controls for a portfolio file
                   9363: Args
                   9364: 1. file name
                   9365: 2. reference to hash of required changes,
                   9366: 3. domain
                   9367: 4. username
                   9368:   where domain,username are the domain of the portfolio owner 
                   9369:   (either a user or a course) 
                   9370: 
                   9371: Returns:
                   9372: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9373: 2. result of deletions ('ok' or 'error', with error message).
                   9374: 3. reference to hash of any new or updated access controls.
                   9375: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9376:    key = integer (inbound ID)
                   9377:    value = uniqueID  
1.747     albertel 9378: 
1.608     albertel 9379: =back
                   9380: 
1.243     albertel 9381: =head2 HTTP Helper Routines
                   9382: 
                   9383: =over 4
                   9384: 
1.191     harris41 9385: =item *
                   9386: 
                   9387: escape() : unpack non-word characters into CGI-compatible hex codes
                   9388: 
                   9389: =item *
                   9390: 
                   9391: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9392: 
1.243     albertel 9393: =back
                   9394: 
                   9395: =head1 PRIVATE SUBROUTINES
                   9396: 
                   9397: =head2 Underlying communication routines (Shouldn't call)
                   9398: 
                   9399: =over 4
                   9400: 
                   9401: =item *
                   9402: 
                   9403: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9404: 
                   9405: =item *
                   9406: 
                   9407: reply() : uses subreply to send a message to remote machine, logs all failures
                   9408: 
                   9409: =item *
                   9410: 
                   9411: critical() : passes a critical message to another server; if cannot
                   9412: get through then place message in connection buffer directory and
                   9413: returns con_delayed, if incapable of saving message, returns
                   9414: con_failed
                   9415: 
                   9416: =item *
                   9417: 
                   9418: reconlonc() : tries to reconnect lonc client processes.
                   9419: 
                   9420: =back
                   9421: 
                   9422: =head2 Resource Access Logging
                   9423: 
                   9424: =over 4
                   9425: 
                   9426: =item *
                   9427: 
                   9428: flushcourselogs() : flush (save) buffer logs and access logs
                   9429: 
                   9430: =item *
                   9431: 
                   9432: courselog($what) : save message for course in hash
                   9433: 
                   9434: =item *
                   9435: 
                   9436: courseacclog($what) : save message for course using &courselog().  Perform
                   9437: special processing for specific resource types (problems, exams, quizzes, etc).
                   9438: 
1.191     harris41 9439: =item *
                   9440: 
                   9441: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9442: as a PerlChildExitHandler
1.243     albertel 9443: 
                   9444: =back
                   9445: 
                   9446: =head2 Other
                   9447: 
                   9448: =over 4
                   9449: 
                   9450: =item *
                   9451: 
                   9452: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9453: 
                   9454: =back
                   9455: 
                   9456: =cut
1.877     foxr     9457: 

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