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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.746   ! raeburn     4: # $Id: lonnet.pm,v 1.745 2006/06/07 18:41:57 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.740     www        55: use lib '/home/httpd/lib/perl';
                     56: use LONCAPA;
                     57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.374     www       284: # ------------------------------------------- Transfer profile into environment
                    285: 
                    286: sub transfer_profile_to_env {
                    287:     my ($lonidsdir,$handle)=@_;
1.720     albertel  288:     if (!defined($lonidsdir)) {
                    289: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    290:     }
                    291:     if (!defined($handle)) {
                    292:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    293:     }
                    294: 
1.374     www       295:     my @profile;
                    296:     {
1.448     albertel  297: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       298: 	flock($idf,LOCK_SH);
                    299: 	@profile=<$idf>;
1.448     albertel  300: 	close($idf);
1.374     www       301:     }
                    302:     my $envi;
1.433     matthew   303:     my %Remove;
1.374     www       304:     for ($envi=0;$envi<=$#profile;$envi++) {
                    305: 	chomp($profile[$envi]);
1.690     albertel  306: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  307: 	$envname=&unescape($envname);
                    308: 	$envvalue=&unescape($envvalue);
1.619     albertel  309: 	$env{$envname} = $envvalue;
1.433     matthew   310:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    311:             if ($time < time-300) {
                    312:                 $Remove{$key}++;
                    313:             }
                    314:         }
                    315:     }
1.619     albertel  316:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   317:     foreach my $expired_key (keys(%Remove)) {
                    318:         &delenv($expired_key);
1.374     www       319:     }
1.1       albertel  320: }
                    321: 
1.5       www       322: # ---------------------------------------------------------- Append Environment
                    323: 
                    324: sub appenv {
1.6       www       325:     my %newenv=@_;
1.692     albertel  326:     foreach my $key (keys(%newenv)) {
                    327: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  328:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  329:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       330:                 .'</font>');
1.692     albertel  331: 	    delete($newenv{$key});
1.35      www       332:         } else {
1.692     albertel  333:             $env{$key}=$newenv{$key};
1.35      www       334:         }
1.191     harris41  335:     }
1.95      www       336: 
                    337:     my $lockfh;
1.620     albertel  338:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  339: 	return 'error: '.$!;
1.95      www       340:     }
                    341:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  342:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       343:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  344:          close($lockfh);
1.95      www       345:          return 'error: '.$!;
                    346:     }
                    347: 
1.6       www       348:     my @oldenv;
                    349:     {
1.448     albertel  350: 	my $fh;
1.620     albertel  351: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  352: 	    return 'error: '.$!;
                    353: 	}
                    354: 	@oldenv=<$fh>;
                    355: 	close($fh);
1.6       www       356:     }
                    357:     for (my $i=0; $i<=$#oldenv; $i++) {
                    358:         chomp($oldenv[$i]);
1.9       www       359:         if ($oldenv[$i] ne '') {
1.690     albertel  360: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.726     albertel  361: 	    $name=&unescape($name);
                    362: 	    $value=&unescape($value);
1.448     albertel  363: 	    unless (defined($newenv{$name})) {
                    364: 		$newenv{$name}=$value;
                    365: 	    }
1.9       www       366:         }
1.6       www       367:     }
                    368:     {
1.448     albertel  369: 	my $fh;
1.620     albertel  370: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  371: 	    return 'error';
                    372: 	}
                    373: 	my $newname;
                    374: 	foreach $newname (keys %newenv) {
1.726     albertel  375: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
1.448     albertel  376: 	}
                    377: 	close($fh);
1.56      www       378:     }
1.448     albertel  379: 	
                    380:     close($lockfh);
1.56      www       381:     return 'ok';
                    382: }
                    383: # ----------------------------------------------------- Delete from Environment
                    384: 
                    385: sub delenv {
                    386:     my $delthis=shift;
                    387:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  388:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       389:                 "Attempt to delete from environment ".$delthis);
                    390:         return 'error';
                    391:     }
                    392:     my @oldenv;
                    393:     {
1.448     albertel  394: 	my $fh;
1.620     albertel  395: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  396: 	    return 'error';
                    397: 	}
                    398: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  399: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  400: 		     'Could not obtain shared lock in delenv: '.$!);
                    401: 	    close($fh);
                    402: 	    return 'error: '.$!;
                    403: 	}
                    404: 	@oldenv=<$fh>;
                    405: 	close($fh);
1.56      www       406:     }
                    407:     {
1.448     albertel  408: 	my $fh;
1.620     albertel  409: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  410: 	    return 'error';
                    411: 	}
                    412: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  413: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  414: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    415: 	    close($fh);
                    416: 	    return 'error: '.$!;
                    417: 	}
1.692     albertel  418: 	foreach my $cur_key (@oldenv) {
1.726     albertel  419: 	    my $unescaped_cur_key = &unescape($cur_key);
                    420: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    421:                 my ($key) = split('=',$cur_key,2);
                    422: 		$key = &unescape($key);
1.619     albertel  423:                 delete($env{$key});
1.473     matthew   424:             } else {
1.692     albertel  425:                 print $fh $cur_key; 
1.473     matthew   426:             }
1.448     albertel  427: 	}
                    428: 	close($fh);
1.5       www       429:     }
                    430:     return 'ok';
1.369     albertel  431: }
                    432: 
                    433: # ------------------------------------------ Find out current server userload
                    434: # there is a copy in lond
                    435: sub userload {
                    436:     my $numusers=0;
                    437:     {
                    438: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    439: 	my $filename;
                    440: 	my $curtime=time;
                    441: 	while ($filename=readdir(LONIDS)) {
                    442: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  443: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  444: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  445: 	}
                    446: 	closedir(LONIDS);
                    447:     }
                    448:     my $userloadpercent=0;
                    449:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    450:     if ($maxuserload) {
1.371     albertel  451: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  452:     }
1.372     albertel  453:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  454:     return $userloadpercent;
1.283     www       455: }
                    456: 
                    457: # ------------------------------------------ Fight off request when overloaded
                    458: 
                    459: sub overloaderror {
                    460:     my ($r,$checkserver)=@_;
                    461:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    462:     my $loadavg;
                    463:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  464:        open(my $loadfile,'/proc/loadavg');
1.283     www       465:        $loadavg=<$loadfile>;
                    466:        $loadavg =~ s/\s.*//g;
1.285     matthew   467:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  468:        close($loadfile);
1.283     www       469:     } else {
                    470:        $loadavg=&reply('load',$checkserver);
                    471:     }
1.285     matthew   472:     my $overload=$loadavg-100;
1.283     www       473:     if ($overload>0) {
1.285     matthew   474: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       475:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       476:         return 413;
1.283     www       477:     }    
                    478:     return '';
1.5       www       479: }
1.1       albertel  480: 
                    481: # ------------------------------ Find server with least workload from spare.tab
1.11      www       482: 
1.1       albertel  483: sub spareserver {
1.670     albertel  484:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  485:     my $tryserver;
                    486:     my $spareserver='';
1.370     albertel  487:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    488:     my $lowestserver=$loadpercent > $userloadpercent?
                    489: 	             $loadpercent :  $userloadpercent;
1.670     albertel  490:     foreach $tryserver (keys(%spareid)) {
                    491: 	my $loadans=&reply('load',$tryserver);
                    492: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  493: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    494: 	    next; #didn't get a number from the server
                    495: 	}
                    496: 	my $answer;
                    497: 	if ($loadans =~ /\d/) {
                    498: 	    if ($userloadans =~ /\d/) {
                    499: 		#both are numbers, pick the bigger one
                    500: 		$answer=$loadans > $userloadans?
                    501: 		    $loadans :  $userloadans;
                    502: 	    } else {
                    503: 		$answer = $loadans;
                    504: 	    }
                    505: 	} else {
                    506: 	    $answer = $userloadans;
                    507: 	}
                    508: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  509: 	    if ($want_server_name) {
                    510: 		$spareserver=$tryserver;
                    511: 	    } else {
                    512: 		$spareserver="http://$hostname{$tryserver}";
                    513: 	    }
1.411     albertel  514: 	    $lowestserver=$answer;
                    515: 	}
1.370     albertel  516:     }
1.1       albertel  517:     return $spareserver;
1.202     matthew   518: }
                    519: 
                    520: # --------------------------------------------- Try to change a user's password
                    521: 
                    522: sub changepass {
                    523:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    524:     $currentpass = &escape($currentpass);
                    525:     $newpass     = &escape($newpass);
                    526:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    527: 		       $server);
                    528:     if (! $answer) {
                    529: 	&logthis("No reply on password change request to $server ".
                    530: 		 "by $uname in domain $udom.");
                    531:     } elsif ($answer =~ "^ok") {
                    532:         &logthis("$uname in $udom successfully changed their password ".
                    533: 		 "on $server.");
                    534:     } elsif ($answer =~ "^pwchange_failure") {
                    535: 	&logthis("$uname in $udom was unable to change their password ".
                    536: 		 "on $server.  The action was blocked by either lcpasswd ".
                    537: 		 "or pwchange");
                    538:     } elsif ($answer =~ "^non_authorized") {
                    539:         &logthis("$uname in $udom did not get their password correct when ".
                    540: 		 "attempting to change it on $server.");
                    541:     } elsif ($answer =~ "^auth_mode_error") {
                    542:         &logthis("$uname in $udom attempted to change their password despite ".
                    543: 		 "not being locally or internally authenticated on $server.");
                    544:     } elsif ($answer =~ "^unknown_user") {
                    545:         &logthis("$uname in $udom attempted to change their password ".
                    546: 		 "on $server but were unable to because $server is not ".
                    547: 		 "their home server.");
                    548:     } elsif ($answer =~ "^refused") {
                    549: 	&logthis("$server refused to change $uname in $udom password because ".
                    550: 		 "it was sent an unencrypted request to change the password.");
                    551:     }
                    552:     return $answer;
1.1       albertel  553: }
                    554: 
1.169     harris41  555: # ----------------------- Try to determine user's current authentication scheme
                    556: 
                    557: sub queryauthenticate {
                    558:     my ($uname,$udom)=@_;
1.456     albertel  559:     my $uhome=&homeserver($uname,$udom);
                    560:     if (!$uhome) {
                    561: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    562: 	return 'no_host';
                    563:     }
                    564:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    565:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    566: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  567:     }
1.456     albertel  568:     return $answer;
1.169     harris41  569: }
                    570: 
1.1       albertel  571: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       572: 
1.1       albertel  573: sub authenticate {
                    574:     my ($uname,$upass,$udom)=@_;
1.12      www       575:     $upass=escape($upass);
1.199     www       576:     $uname=~s/\W//g;
1.471     albertel  577:     my $uhome=&homeserver($uname,$udom);
                    578:     if (!$uhome) {
                    579: 	&logthis("User $uname at $udom is unknown in authenticate");
                    580: 	return 'no_host';
1.1       albertel  581:     }
1.471     albertel  582:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    583:     if ($answer eq 'authorized') {
                    584: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    585: 	return $uhome; 
                    586:     }
                    587:     if ($answer eq 'non_authorized') {
                    588: 	&logthis("User $uname at $udom rejected by $uhome");
                    589: 	return 'no_host'; 
1.9       www       590:     }
1.471     albertel  591:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  592:     return 'no_host';
                    593: }
                    594: 
                    595: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       596: 
1.599     albertel  597: my %homecache;
1.1       albertel  598: sub homeserver {
1.230     stredwic  599:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  600:     my $index="$uname:$udom";
1.426     albertel  601: 
1.599     albertel  602:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  603:     my $tryserver;
                    604:     foreach $tryserver (keys %libserv) {
1.230     stredwic  605:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  606: 		 exists($badServerCache{$tryserver}));
1.1       albertel  607: 	if ($hostdom{$tryserver} eq $udom) {
                    608:            my $answer=reply("home:$udom:$uname",$tryserver);
                    609:            if ($answer eq 'found') { 
1.599     albertel  610: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  611:            } elsif ($answer eq 'no_host') {
                    612: 	       $badServerCache{$tryserver}=1;
1.221     matthew   613:            }
1.1       albertel  614:        }
                    615:     }    
                    616:     return 'no_host';
1.70      www       617: }
                    618: 
                    619: # ------------------------------------- Find the usernames behind a list of IDs
                    620: 
                    621: sub idget {
                    622:     my ($udom,@ids)=@_;
                    623:     my %returnhash=();
                    624:     
                    625:     my $tryserver;
                    626:     foreach $tryserver (keys %libserv) {
                    627:        if ($hostdom{$tryserver} eq $udom) {
                    628: 	  my $idlist=join('&',@ids);
                    629:           $idlist=~tr/A-Z/a-z/; 
                    630: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    631:           my @answer=();
1.76      www       632:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       633: 	      @answer=split(/\&/,$reply);
                    634:           }                    ;
                    635:           my $i;
                    636:           for ($i=0;$i<=$#ids;$i++) {
                    637:               if ($answer[$i]) {
                    638: 		  $returnhash{$ids[$i]}=$answer[$i];
                    639:               } 
                    640:           }
                    641:        }
                    642:     }    
                    643:     return %returnhash;
                    644: }
                    645: 
                    646: # ------------------------------------- Find the IDs behind a list of usernames
                    647: 
                    648: sub idrget {
                    649:     my ($udom,@unames)=@_;
                    650:     my %returnhash=();
1.191     harris41  651:     foreach (@unames) {
1.70      www       652:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  653:     }
1.70      www       654:     return %returnhash;
                    655: }
                    656: 
                    657: # ------------------------------- Store away a list of names and associated IDs
                    658: 
                    659: sub idput {
                    660:     my ($udom,%ids)=@_;
                    661:     my %servers=();
1.191     harris41  662:     foreach (keys %ids) {
1.487     albertel  663: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       664:         my $uhom=&homeserver($_,$udom);
                    665:         if ($uhom ne 'no_host') {
                    666:             my $id=&escape($ids{$_});
                    667:             $id=~tr/A-Z/a-z/;
                    668:             my $unam=&escape($_);
                    669: 	    if ($servers{$uhom}) {
                    670: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    671:             } else {
                    672:                 $servers{$uhom}=$id.'='.$unam;
                    673:             }
                    674:         }
1.191     harris41  675:     }
                    676:     foreach (keys %servers) {
1.70      www       677:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  678:     }
1.344     www       679: }
                    680: 
                    681: # --------------------------------------------------- Assign a key to a student
                    682: 
                    683: sub assign_access_key {
1.364     www       684: #
                    685: # a valid key looks like uname:udom#comments
                    686: # comments are being appended
                    687: #
1.498     www       688:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    689:     $kdom=
1.620     albertel  690:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       691:     $knum=
1.620     albertel  692:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       693:     $cdom=
1.620     albertel  694:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       695:     $cnum=
1.620     albertel  696:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    697:     $udom=$env{'user.name'} unless (defined($udom));
                    698:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       699:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       700:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  701:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       702:                                                   # assigned to this person
                    703:                                                   # - this should not happen,
1.345     www       704:                                                   # unless something went wrong
                    705:                                                   # the first time around
                    706: # ready to assign
1.364     www       707:         $logentry=$1.'; '.$logentry;
1.496     www       708:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       709:                                                  $kdom,$knum) eq 'ok') {
1.345     www       710: # key now belongs to user
1.346     www       711: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       712:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    713:                 &appenv('environment.'.$envkey => $ckey);
                    714:                 return 'ok';
                    715:             } else {
                    716:                 return 
                    717:   'error: Count not permanently assign key, will need to be re-entered later.';
                    718: 	    }
                    719:         } else {
                    720:             return 'error: Could not assign key, try again later.';
                    721:         }
1.364     www       722:     } elsif (!$existing{$ckey}) {
1.345     www       723: # the key does not exist
                    724: 	return 'error: The key does not exist';
                    725:     } else {
                    726: # the key is somebody else's
                    727: 	return 'error: The key is already in use';
                    728:     }
1.344     www       729: }
                    730: 
1.364     www       731: # ------------------------------------------ put an additional comment on a key
                    732: 
                    733: sub comment_access_key {
                    734: #
                    735: # a valid key looks like uname:udom#comments
                    736: # comments are being appended
                    737: #
                    738:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    739:     $cdom=
1.620     albertel  740:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       741:     $cnum=
1.620     albertel  742:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       743:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    744:     if ($existing{$ckey}) {
                    745:         $existing{$ckey}.='; '.$logentry;
                    746: # ready to assign
1.367     www       747:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       748:                                                  $cdom,$cnum) eq 'ok') {
                    749: 	    return 'ok';
                    750:         } else {
                    751: 	    return 'error: Count not store comment.';
                    752:         }
                    753:     } else {
                    754: # the key does not exist
                    755: 	return 'error: The key does not exist';
                    756:     }
                    757: }
                    758: 
1.344     www       759: # ------------------------------------------------------ Generate a set of keys
                    760: 
                    761: sub generate_access_keys {
1.364     www       762:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       763:     $cdom=
1.620     albertel  764:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       765:     $cnum=
1.620     albertel  766:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       767:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       768:     unless (($cdom) && ($cnum)) { return 0; }
                    769:     if ($number>10000) { return 0; }
                    770:     sleep(2); # make sure don't get same seed twice
                    771:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    772:     my $total=0;
                    773:     for (my $i=1;$i<=$number;$i++) {
                    774:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    775:                   sprintf("%lx",int(100000*rand)).'-'.
                    776:                   sprintf("%lx",int(100000*rand));
                    777:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    778:        $newkey=~s/0/h/g; # and also 0 and O
                    779:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    780:        if ($existing{$newkey}) {
                    781:            $i--;
                    782:        } else {
1.364     www       783: 	  if (&put('accesskeys',
                    784:               { $newkey => '# generated '.localtime().
1.620     albertel  785:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       786:                            '; '.$logentry },
                    787: 		   $cdom,$cnum) eq 'ok') {
1.344     www       788:               $total++;
                    789: 	  }
                    790:        }
                    791:     }
1.620     albertel  792:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       793:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    794:     return $total;
                    795: }
                    796: 
                    797: # ------------------------------------------------------- Validate an accesskey
                    798: 
                    799: sub validate_access_key {
                    800:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    801:     $cdom=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       803:     $cnum=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    805:     $udom=$env{'user.domain'} unless (defined($udom));
                    806:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       807:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  808:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       809: }
                    810: 
                    811: # ------------------------------------- Find the section of student in a course
1.652     albertel  812: sub devalidate_getsection_cache {
                    813:     my ($udom,$unam,$courseid)=@_;
                    814:     $courseid=~s/\_/\//g;
                    815:     $courseid=~s/^(\w)/\/$1/;
                    816:     my $hashid="$udom:$unam:$courseid";
                    817:     &devalidate_cache_new('getsection',$hashid);
                    818: }
1.298     matthew   819: 
                    820: sub getsection {
                    821:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  822:     my $cachetime=1800;
1.298     matthew   823:     $courseid=~s/\_/\//g;
                    824:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  825: 
                    826:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  827:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  828:     if (defined($cached)) { return $result; }
                    829: 
1.298     matthew   830:     my %Pending; 
                    831:     my %Expired;
                    832:     #
                    833:     # Each role can either have not started yet (pending), be active, 
                    834:     #    or have expired.
                    835:     #
                    836:     # If there is an active role, we are done.
                    837:     #
                    838:     # If there is more than one role which has not started yet, 
                    839:     #     choose the one which will start sooner
                    840:     # If there is one role which has not started yet, return it.
                    841:     #
                    842:     # If there is more than one expired role, choose the one which ended last.
                    843:     # If there is a role which has expired, return it.
                    844:     #
                    845:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    846:                         &homeserver($unam,$udom)))) {
                    847:         my ($key,$value)=split(/\=/,$_);
                    848:         $key=&unescape($key);
1.479     albertel  849:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   850:         my $section=$1;
                    851:         if ($key eq $courseid.'_st') { $section=''; }
                    852:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    853:         my $now=time;
1.548     albertel  854:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   855:             $Expired{$end}=$section;
                    856:             next;
                    857:         }
1.548     albertel  858:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   859:             $Pending{$start}=$section;
                    860:             next;
                    861:         }
1.599     albertel  862:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   863:     }
                    864:     #
                    865:     # Presumedly there will be few matching roles from the above
                    866:     # loop and the sorting time will be negligible.
                    867:     if (scalar(keys(%Pending))) {
                    868:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  869:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   870:     } 
                    871:     if (scalar(keys(%Expired))) {
                    872:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    873:         my $time = pop(@sorted);
1.599     albertel  874:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   875:     }
1.599     albertel  876:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   877: }
1.70      www       878: 
1.599     albertel  879: sub save_cache {
                    880:     &purge_remembered();
1.722     albertel  881:     #&Apache::loncommon::validate_page();
1.620     albertel  882:     undef(%env);
1.599     albertel  883: }
1.452     albertel  884: 
1.599     albertel  885: my $to_remember=-1;
                    886: my %remembered;
                    887: my %accessed;
                    888: my $kicks=0;
                    889: my $hits=0;
                    890: sub devalidate_cache_new {
                    891:     my ($name,$id,$debug) = @_;
                    892:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    893:     $id=&escape($name.':'.$id);
                    894:     $memcache->delete($id);
                    895:     delete($remembered{$id});
                    896:     delete($accessed{$id});
                    897: }
                    898: 
                    899: sub is_cached_new {
                    900:     my ($name,$id,$debug) = @_;
                    901:     $id=&escape($name.':'.$id);
                    902:     if (exists($remembered{$id})) {
                    903: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    904: 	$accessed{$id}=[&gettimeofday()];
                    905: 	$hits++;
                    906: 	return ($remembered{$id},1);
                    907:     }
                    908:     my $value = $memcache->get($id);
                    909:     if (!(defined($value))) {
                    910: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  911: 	return (undef,undef);
1.416     albertel  912:     }
1.599     albertel  913:     if ($value eq '__undef__') {
                    914: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    915: 	$value=undef;
                    916:     }
                    917:     &make_room($id,$value,$debug);
                    918:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    919:     return ($value,1);
                    920: }
                    921: 
                    922: sub do_cache_new {
                    923:     my ($name,$id,$value,$time,$debug) = @_;
                    924:     $id=&escape($name.':'.$id);
                    925:     my $setvalue=$value;
                    926:     if (!defined($setvalue)) {
                    927: 	$setvalue='__undef__';
                    928:     }
1.623     albertel  929:     if (!defined($time) ) {
                    930: 	$time=600;
                    931:     }
1.599     albertel  932:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  933:     $memcache->set($id,$setvalue,$time);
                    934:     # need to make a copy of $value
                    935:     #&make_room($id,$value,$debug);
1.599     albertel  936:     return $value;
                    937: }
                    938: 
                    939: sub make_room {
                    940:     my ($id,$value,$debug)=@_;
                    941:     $remembered{$id}=$value;
                    942:     if ($to_remember<0) { return; }
                    943:     $accessed{$id}=[&gettimeofday()];
                    944:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    945:     my $to_kick;
                    946:     my $max_time=0;
                    947:     foreach my $other (keys(%accessed)) {
                    948: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    949: 	    $to_kick=$other;
                    950: 	    $max_time=&tv_interval($accessed{$other});
                    951: 	}
                    952:     }
                    953:     delete($remembered{$to_kick});
                    954:     delete($accessed{$to_kick});
                    955:     $kicks++;
                    956:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  957:     return;
                    958: }
                    959: 
1.599     albertel  960: sub purge_remembered {
1.604     albertel  961:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    962:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  963:     undef(%remembered);
                    964:     undef(%accessed);
1.428     albertel  965: }
1.70      www       966: # ------------------------------------- Read an entry from a user's environment
                    967: 
                    968: sub userenvironment {
                    969:     my ($udom,$unam,@what)=@_;
                    970:     my %returnhash=();
                    971:     my @answer=split(/\&/,
                    972:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    973:                       &homeserver($unam,$udom)));
                    974:     my $i;
                    975:     for ($i=0;$i<=$#what;$i++) {
                    976: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    977:     }
                    978:     return %returnhash;
1.1       albertel  979: }
                    980: 
1.617     albertel  981: # ---------------------------------------------------------- Get a studentphoto
                    982: sub studentphoto {
                    983:     my ($udom,$unam,$ext) = @_;
                    984:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   985:     if (defined($env{'request.course.id'})) {
1.708     raeburn   986:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   987:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    988:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    989:             } else {
                    990:                 my ($result,$perm_reqd)=
1.707     albertel  991: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   992:                 if ($result eq 'ok') {
                    993:                     if (!($perm_reqd eq 'yes')) {
                    994:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    995:                     }
                    996:                 }
                    997:             }
                    998:         }
                    999:     } else {
                   1000:         my ($result,$perm_reqd) = 
1.707     albertel 1001: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1002:         if ($result eq 'ok') {
                   1003:             if (!($perm_reqd eq 'yes')) {
                   1004:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1005:             }
                   1006:         }
                   1007:     }
                   1008:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1009: }
                   1010: 
                   1011: sub retrievestudentphoto {
                   1012:     my ($udom,$unam,$ext,$type) = @_;
                   1013:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1014:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1015:     if ($ret eq 'ok') {
                   1016:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1017:         if ($type eq 'thumbnail') {
                   1018:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1019:         }
                   1020:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1021:         return $tokenurl;
                   1022:     } else {
                   1023:         if ($type eq 'thumbnail') {
                   1024:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1025:         } else { 
                   1026:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1027:         }
1.617     albertel 1028:     }
                   1029: }
                   1030: 
1.263     www      1031: # -------------------------------------------------------------------- New chat
                   1032: 
                   1033: sub chatsend {
1.724     raeburn  1034:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1035:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1036:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1037:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1038:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1039: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1040: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1041: }
                   1042: 
                   1043: # ------------------------------------------ Find current version of a resource
                   1044: 
                   1045: sub getversion {
                   1046:     my $fname=&clutter(shift);
                   1047:     unless ($fname=~/^\/res\//) { return -1; }
                   1048:     return &currentversion(&filelocation('',$fname));
                   1049: }
                   1050: 
                   1051: sub currentversion {
                   1052:     my $fname=shift;
1.599     albertel 1053:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1054:     if (defined($cached)) { return $result; }
1.292     www      1055:     my $author=$fname;
                   1056:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1057:     my ($udom,$uname)=split(/\//,$author);
                   1058:     my $home=homeserver($uname,$udom);
                   1059:     if ($home eq 'no_host') { 
                   1060:         return -1; 
                   1061:     }
                   1062:     my $answer=reply("currentversion:$fname",$home);
                   1063:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1064: 	return -1;
                   1065:     }
1.599     albertel 1066:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1067: }
                   1068: 
1.1       albertel 1069: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1070: 
1.1       albertel 1071: sub subscribe {
                   1072:     my $fname=shift;
1.312     www      1073:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1074:     $fname=~s/[\n\r]//g;
1.1       albertel 1075:     my $author=$fname;
                   1076:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1077:     my ($udom,$uname)=split(/\//,$author);
                   1078:     my $home=homeserver($uname,$udom);
1.335     albertel 1079:     if ($home eq 'no_host') {
                   1080:         return 'not_found';
1.1       albertel 1081:     }
                   1082:     my $answer=reply("sub:$fname",$home);
1.64      www      1083:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1084: 	$answer.=' by '.$home;
                   1085:     }
1.1       albertel 1086:     return $answer;
                   1087: }
                   1088:     
1.8       www      1089: # -------------------------------------------------------------- Replicate file
                   1090: 
                   1091: sub repcopy {
                   1092:     my $filename=shift;
1.23      www      1093:     $filename=~s/\/+/\//g;
1.607     raeburn  1094:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1095:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1096:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1097: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1098: 	return &repcopy_userfile($filename);
                   1099:     }
1.532     albertel 1100:     $filename=~s/[\n\r]//g;
1.8       www      1101:     my $transname="$filename.in.transfer";
1.607     raeburn  1102:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1103:     my $remoteurl=subscribe($filename);
1.64      www      1104:     if ($remoteurl =~ /^con_lost by/) {
                   1105: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1106:            return 'unavailable';
1.8       www      1107:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1108: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1109: 	   return 'not_found';
1.64      www      1110:     } elsif ($remoteurl =~ /^rejected by/) {
                   1111: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1112:            return 'forbidden';
1.20      www      1113:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1114:            return 'ok';
1.8       www      1115:     } else {
1.290     www      1116:         my $author=$filename;
                   1117:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1118:         my ($udom,$uname)=split(/\//,$author);
                   1119:         my $home=homeserver($uname,$udom);
                   1120:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1121:            my @parts=split(/\//,$filename);
                   1122:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1123:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1124:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1125: 	       return 'bad_request';
1.8       www      1126:            }
                   1127:            my $count;
                   1128:            for ($count=5;$count<$#parts;$count++) {
                   1129:                $path.="/$parts[$count]";
                   1130:                if ((-e $path)!=1) {
                   1131: 		   mkdir($path,0777);
                   1132:                }
                   1133:            }
                   1134:            my $ua=new LWP::UserAgent;
                   1135:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1136:            my $response=$ua->request($request,$transname);
                   1137:            if ($response->is_error()) {
                   1138: 	       unlink($transname);
                   1139:                my $message=$response->status_line;
1.672     albertel 1140:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1141:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1142:                return 'unavailable';
1.8       www      1143:            } else {
1.16      www      1144: 	       if ($remoteurl!~/\.meta$/) {
                   1145:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1146:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1147:                   if ($mresponse->is_error()) {
                   1148: 		      unlink($filename.'.meta');
                   1149:                       &logthis(
1.672     albertel 1150:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1151:                   }
                   1152: 	       }
1.8       www      1153:                rename($transname,$filename);
1.607     raeburn  1154:                return 'ok';
1.8       www      1155:            }
1.290     www      1156:        }
1.8       www      1157:     }
1.330     www      1158: }
                   1159: 
                   1160: # ------------------------------------------------ Get server side include body
                   1161: sub ssi_body {
1.381     albertel 1162:     my ($filelink,%form)=@_;
1.606     matthew  1163:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1164:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1165:     }
1.330     www      1166:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1167:                                      &ssi($filelink,%form));
1.565     albertel 1168:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1169:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1170:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1171:     return $output;
1.8       www      1172: }
                   1173: 
1.15      www      1174: # --------------------------------------------------------- Server Side Include
                   1175: 
                   1176: sub ssi {
                   1177: 
1.23      www      1178:     my ($fn,%form)=@_;
1.15      www      1179: 
                   1180:     my $ua=new LWP::UserAgent;
1.23      www      1181:     
                   1182:     my $request;
1.711     albertel 1183: 
                   1184:     $form{'no_update_last_known'}=1;
                   1185: 
1.23      www      1186:     if (%form) {
                   1187:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1188:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1189:     } else {
                   1190:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1191:     }
                   1192: 
1.15      www      1193:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1194:     my $response=$ua->request($request);
                   1195: 
1.324     www      1196:     return $response->content;
                   1197: }
                   1198: 
                   1199: sub externalssi {
                   1200:     my ($url)=@_;
                   1201:     my $ua=new LWP::UserAgent;
                   1202:     my $request=new HTTP::Request('GET',$url);
                   1203:     my $response=$ua->request($request);
1.15      www      1204:     return $response->content;
                   1205: }
1.254     www      1206: 
1.492     albertel 1207: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1208: 
                   1209: sub allowuploaded {
                   1210:     my ($srcurl,$url)=@_;
                   1211:     $url=&clutter(&declutter($url));
                   1212:     my $dir=$url;
                   1213:     $dir=~s/\/[^\/]+$//;
                   1214:     my %httpref=();
                   1215:     my $httpurl=&hreflocation('',$url);
                   1216:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1217:     &Apache::lonnet::appenv(%httpref);
1.254     www      1218: }
1.477     raeburn  1219: 
1.478     albertel 1220: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1221: # input: action, courseID, current domain, intended
1.637     raeburn  1222: #        path to file, source of file, instruction to parse file for objects,
                   1223: #        ref to hash for embedded objects,
                   1224: #        ref to hash for codebase of java objects.
                   1225: #
1.485     raeburn  1226: # output: url to file (if action was uploaddoc), 
                   1227: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1228: #
1.478     albertel 1229: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1230: # course.
1.477     raeburn  1231: #
1.478     albertel 1232: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1233: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1234: #          course's home server.
1.477     raeburn  1235: #
1.478     albertel 1236: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1237: #          be copied from $source (current location) to 
                   1238: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1239: #         and will then be copied to
                   1240: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1241: #         course's home server.
1.485     raeburn  1242: #
1.481     raeburn  1243: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1244: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1245: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1246: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1247: #         in course's home server.
1.637     raeburn  1248: #
1.477     raeburn  1249: 
                   1250: sub process_coursefile {
1.638     albertel 1251:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1252:     my $fetchresult;
1.638     albertel 1253:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1254:     if ($action eq 'propagate') {
1.638     albertel 1255:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1256: 			     $home);
1.481     raeburn  1257:     } else {
1.477     raeburn  1258:         my $fpath = '';
                   1259:         my $fname = $file;
1.478     albertel 1260:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1261:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1262:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1263:         if ($action eq 'copy') {
                   1264:             if ($source eq '') {
                   1265:                 $fetchresult = 'no source file';
                   1266:                 return $fetchresult;
                   1267:             } else {
                   1268:                 my $destination = $filepath.'/'.$fname;
                   1269:                 rename($source,$destination);
                   1270:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1271:                                  $home);
1.481     raeburn  1272:             }
                   1273:         } elsif ($action eq 'uploaddoc') {
                   1274:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1275:             print $fh $env{'form.'.$source};
1.481     raeburn  1276:             close($fh);
1.637     raeburn  1277:             if ($parser eq 'parse') {
                   1278:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1279:                 unless ($parse_result eq 'ok') {
                   1280:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1281:                 }
                   1282:             }
1.477     raeburn  1283:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1284:                                  $home);
1.481     raeburn  1285:             if ($fetchresult eq 'ok') {
                   1286:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1287:             } else {
                   1288:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1289:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1290:                 return '/adm/notfound.html';
                   1291:             }
1.477     raeburn  1292:         }
                   1293:     }
1.485     raeburn  1294:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1295:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1296:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1297:     }
                   1298:     return $fetchresult;
                   1299: }
                   1300: 
1.637     raeburn  1301: sub build_filepath {
                   1302:     my ($fpath) = @_;
                   1303:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1304:     unless ($fpath eq '') {
                   1305:         my @parts=split('/',$fpath);
                   1306:         foreach my $part (@parts) {
                   1307:             $filepath.= '/'.$part;
                   1308:             if ((-e $filepath)!=1) {
                   1309:                 mkdir($filepath,0777);
                   1310:             }
                   1311:         }
                   1312:     }
                   1313:     return $filepath;
                   1314: }
                   1315: 
                   1316: sub store_edited_file {
1.638     albertel 1317:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1318:     my $file = $primary_url;
                   1319:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1320:     my $fpath = '';
                   1321:     my $fname = $file;
                   1322:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1323:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1324:     my $filepath = &build_filepath($fpath);
                   1325:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1326:     print $fh $content;
                   1327:     close($fh);
1.638     albertel 1328:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1329:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1330: 			  $home);
1.637     raeburn  1331:     if ($$fetchresult eq 'ok') {
                   1332:         return '/uploaded/'.$fpath.'/'.$fname;
                   1333:     } else {
1.638     albertel 1334:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1335: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1336:         return '/adm/notfound.html';
                   1337:     }
                   1338: }
                   1339: 
1.531     albertel 1340: sub clean_filename {
                   1341:     my ($fname)=@_;
1.315     www      1342: # Replace Windows backslashes by forward slashes
1.257     www      1343:     $fname=~s/\\/\//g;
1.315     www      1344: # Get rid of everything but the actual filename
1.257     www      1345:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1346: # Replace spaces by underscores
                   1347:     $fname=~s/\s+/\_/g;
                   1348: # Replace all other weird characters by nothing
1.317     www      1349:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1350: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1351: # numbers
                   1352:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1353:     return $fname;
                   1354: }
                   1355: 
1.608     albertel 1356: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1357: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1358: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1359: #        $coursedoc - if true up to the current course
                   1360: #                     if false
                   1361: #        $subdir - directory in userfile to store the file into
                   1362: #        $parser, $allfiles, $codebase - unknown
                   1363: #
                   1364: # output: url of file in userspace, or error: <message> 
                   1365: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1366: 
                   1367: 
1.531     albertel 1368: sub userfileupload {
1.719     banghart 1369:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1370:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1371:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1372:     $fname=&clean_filename($fname);
1.315     www      1373: # See if there is anything left
1.257     www      1374:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1375:     chop($env{'form.'.$formname});
1.523     raeburn  1376:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1377:         my $now = time;
                   1378:         my $filepath = 'tmp/helprequests/'.$now;
                   1379:         my @parts=split(/\//,$filepath);
                   1380:         my $fullpath = $perlvar{'lonDaemons'};
                   1381:         for (my $i=0;$i<@parts;$i++) {
                   1382:             $fullpath .= '/'.$parts[$i];
                   1383:             if ((-e $fullpath)!=1) {
                   1384:                 mkdir($fullpath,0777);
                   1385:             }
                   1386:         }
                   1387:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1388:         print $fh $env{'form.'.$formname};
1.523     raeburn  1389:         close($fh);
1.741     raeburn  1390:         return $fullpath.'/'.$fname;
                   1391:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1392:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1393:                        '_'.$env{'user.domain'}.'/pending';
                   1394:         my @parts=split(/\//,$filepath);
                   1395:         my $fullpath = $perlvar{'lonDaemons'};
                   1396:         for (my $i=0;$i<@parts;$i++) {
                   1397:             $fullpath .= '/'.$parts[$i];
                   1398:             if ((-e $fullpath)!=1) {
                   1399:                 mkdir($fullpath,0777);
                   1400:             }
                   1401:         }
                   1402:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1403:         print $fh $env{'form.'.$formname};
                   1404:         close($fh);
                   1405:         return $fullpath.'/'.$fname;
1.523     raeburn  1406:     }
1.719     banghart 1407:     
1.258     www      1408: # Create the directory if not present
1.493     albertel 1409:     $fname="$subdir/$fname";
1.259     www      1410:     if ($coursedoc) {
1.638     albertel 1411: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1412: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1413:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1414:             return &finishuserfileupload($docuname,$docudom,
                   1415: 					 $formname,$fname,$parser,$allfiles,
                   1416: 					 $codebase);
1.481     raeburn  1417:         } else {
1.620     albertel 1418:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1419:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1420: 				       $fname,$formname,$parser,
                   1421: 				       $allfiles,$codebase);
1.481     raeburn  1422:         }
1.719     banghart 1423:     } elsif (defined($destuname)) {
                   1424:         my $docuname=$destuname;
                   1425:         my $docudom=$destudom;
                   1426: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1427: 				     $fname,$parser,$allfiles,$codebase);
                   1428:         
1.259     www      1429:     } else {
1.638     albertel 1430:         my $docuname=$env{'user.name'};
                   1431:         my $docudom=$env{'user.domain'};
1.714     raeburn  1432:         if (exists($env{'form.group'})) {
                   1433:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1434:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1435:         }
1.638     albertel 1436: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1437: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1438:     }
1.271     www      1439: }
                   1440: 
                   1441: sub finishuserfileupload {
1.638     albertel 1442:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1443:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1444:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1445:     my ($fnamepath,$file);
                   1446:     $file=$fname;
                   1447:     if ($fname=~m|/|) {
                   1448:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1449: 	$path.=$fnamepath.'/';
                   1450:     }
1.259     www      1451:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1452:     my $count;
                   1453:     for ($count=4;$count<=$#parts;$count++) {
                   1454:         $filepath.="/$parts[$count]";
                   1455:         if ((-e $filepath)!=1) {
                   1456: 	    mkdir($filepath,0777);
                   1457:         }
                   1458:     }
                   1459: # Save the file
                   1460:     {
1.701     albertel 1461: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1462: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1463: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1464: 	    return '/adm/notfound.html';
                   1465: 	}
                   1466: 	if (!print FH ($env{'form.'.$formname})) {
                   1467: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1468: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1469: 	    return '/adm/notfound.html';
                   1470: 	}
1.570     albertel 1471: 	close(FH);
1.258     www      1472:     }
1.637     raeburn  1473:     if ($parser eq 'parse') {
1.638     albertel 1474:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1475: 						   $codebase);
1.637     raeburn  1476:         unless ($parse_result eq 'ok') {
1.638     albertel 1477:             &logthis('Failed to parse '.$filepath.$file.
                   1478: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1479:         }
                   1480:     }
1.259     www      1481: # Notify homeserver to grep it
                   1482: #
1.638     albertel 1483:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1484:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1485:     if ($fetchresult eq 'ok') {
1.259     www      1486: #
1.258     www      1487: # Return the URL to it
1.494     albertel 1488:         return '/uploaded/'.$path.$file;
1.263     www      1489:     } else {
1.494     albertel 1490:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1491: 		 ': '.$fetchresult);
1.263     www      1492:         return '/adm/notfound.html';
                   1493:     }    
1.493     albertel 1494: }
                   1495: 
1.637     raeburn  1496: sub extract_embedded_items {
1.648     raeburn  1497:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1498:     my @state = ();
                   1499:     my %javafiles = (
                   1500:                       codebase => '',
                   1501:                       code => '',
                   1502:                       archive => ''
                   1503:                     );
                   1504:     my %mediafiles = (
                   1505:                       src => '',
                   1506:                       movie => '',
                   1507:                      );
1.648     raeburn  1508:     my $p;
                   1509:     if ($content) {
                   1510:         $p = HTML::LCParser->new($content);
                   1511:     } else {
                   1512:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1513:     }
1.641     albertel 1514:     while (my $t=$p->get_token()) {
1.640     albertel 1515: 	if ($t->[0] eq 'S') {
                   1516: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1517: 	    push (@state, $tagname);
1.648     raeburn  1518:             if (lc($tagname) eq 'allow') {
                   1519:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1520:             }
1.640     albertel 1521: 	    if (lc($tagname) eq 'img') {
                   1522: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1523: 	    }
1.645     raeburn  1524:             if (lc($tagname) eq 'script') {
                   1525:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1526:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1527:                 } else {
                   1528:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1529:                 }
                   1530:             }
                   1531:             if (lc($tagname) eq 'link') {
                   1532:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1533:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1534:                 }
                   1535:             }
1.640     albertel 1536: 	    if (lc($tagname) eq 'object' ||
                   1537: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1538: 		foreach my $item (keys(%javafiles)) {
                   1539: 		    $javafiles{$item} = '';
                   1540: 		}
                   1541: 	    }
                   1542: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1543: 		my $name = lc($attr->{'name'});
                   1544: 		foreach my $item (keys(%javafiles)) {
                   1545: 		    if ($name eq $item) {
                   1546: 			$javafiles{$item} = $attr->{'value'};
                   1547: 			last;
                   1548: 		    }
                   1549: 		}
                   1550: 		foreach my $item (keys(%mediafiles)) {
                   1551: 		    if ($name eq $item) {
                   1552: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1553: 			last;
                   1554: 		    }
                   1555: 		}
                   1556: 	    }
                   1557: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1558: 		foreach my $item (keys(%javafiles)) {
                   1559: 		    if ($attr->{$item}) {
                   1560: 			$javafiles{$item} = $attr->{$item};
                   1561: 			last;
                   1562: 		    }
                   1563: 		}
                   1564: 		foreach my $item (keys(%mediafiles)) {
                   1565: 		    if ($attr->{$item}) {
                   1566: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1567: 			last;
                   1568: 		    }
                   1569: 		}
                   1570: 	    }
                   1571: 	} elsif ($t->[0] eq 'E') {
                   1572: 	    my ($tagname) = ($t->[1]);
                   1573: 	    if ($javafiles{'codebase'} ne '') {
                   1574: 		$javafiles{'codebase'} .= '/';
                   1575: 	    }  
                   1576: 	    if (lc($tagname) eq 'applet' ||
                   1577: 		lc($tagname) eq 'object' ||
                   1578: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1579: 		) {
                   1580: 		foreach my $item (keys(%javafiles)) {
                   1581: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1582: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1583: 			&add_filetype($allfiles,$file,$item);
                   1584: 		    }
                   1585: 		}
                   1586: 	    } 
                   1587: 	    pop @state;
                   1588: 	}
                   1589:     }
1.637     raeburn  1590:     return 'ok';
                   1591: }
                   1592: 
1.639     albertel 1593: sub add_filetype {
                   1594:     my ($allfiles,$file,$type)=@_;
                   1595:     if (exists($allfiles->{$file})) {
                   1596: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1597: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1598: 	}
                   1599:     } else {
                   1600: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1601:     }
                   1602: }
                   1603: 
1.493     albertel 1604: sub removeuploadedurl {
                   1605:     my ($url)=@_;
                   1606:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1607:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1608: }
                   1609: 
                   1610: sub removeuserfile {
                   1611:     my ($docuname,$docudom,$fname)=@_;
                   1612:     my $home=&homeserver($docuname,$docudom);
                   1613:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1614: }
1.15      www      1615: 
1.530     albertel 1616: sub mkdiruserfile {
                   1617:     my ($docuname,$docudom,$dir)=@_;
                   1618:     my $home=&homeserver($docuname,$docudom);
                   1619:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1620: }
                   1621: 
1.531     albertel 1622: sub renameuserfile {
                   1623:     my ($docuname,$docudom,$old,$new)=@_;
                   1624:     my $home=&homeserver($docuname,$docudom);
                   1625:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1626: 		  &escape("$new"),$home);
                   1627: }
                   1628: 
1.14      www      1629: # ------------------------------------------------------------------------- Log
                   1630: 
                   1631: sub log {
                   1632:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1633:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1634: }
                   1635: 
                   1636: # ------------------------------------------------------------------ Course Log
1.352     www      1637: #
                   1638: # This routine flushes several buffers of non-mission-critical nature
                   1639: #
1.157     www      1640: 
                   1641: sub flushcourselogs {
1.352     www      1642:     &logthis('Flushing log buffers');
                   1643: #
                   1644: # course logs
                   1645: # This is a log of all transactions in a course, which can be used
                   1646: # for data mining purposes
                   1647: #
                   1648: # It also collects the courseid database, which lists last transaction
                   1649: # times and course titles for all courseids
                   1650: #
                   1651:     my %courseidbuffer=();
1.191     harris41 1652:     foreach (keys %courselogs) {
1.157     www      1653:         my $crsid=$_;
1.352     www      1654:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1655: 		          &escape($courselogs{$crsid}),
                   1656: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1657: 	    delete $courselogs{$crsid};
                   1658:         } else {
                   1659:             &logthis('Failed to flush log buffer for '.$crsid);
                   1660:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1661:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1662:                         " exceeded maximum size, deleting.</font>");
                   1663:                delete $courselogs{$crsid};
                   1664:             }
1.352     www      1665:         }
                   1666:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1667:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1668: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1669:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1670:         } else {
                   1671:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1672: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1673:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1674:         }
1.191     harris41 1675:     }
1.352     www      1676: #
                   1677: # Write course id database (reverse lookup) to homeserver of courses 
                   1678: # Is used in pickcourse
                   1679: #
                   1680:     foreach (keys %courseidbuffer) {
1.353     www      1681:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1682:     }
                   1683: #
                   1684: # File accesses
                   1685: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1686: #
1.449     matthew  1687:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1688:         if ($entry =~ /___count$/) {
                   1689:             my ($dom,$name);
                   1690:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1691:             if (! defined($dom) || $dom eq '' || 
                   1692:                 ! defined($name) || $name eq '') {
1.620     albertel 1693:                 my $cid = $env{'request.course.id'};
                   1694:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1695:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1696:             }
1.450     matthew  1697:             my $value = $accesshash{$entry};
                   1698:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1699:             my %temphash=($url => $value);
1.449     matthew  1700:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1701:             if ($result eq 'ok') {
                   1702:                 delete $accesshash{$entry};
                   1703:             } elsif ($result eq 'unknown_cmd') {
                   1704:                 # Target server has old code running on it.
1.450     matthew  1705:                 my %temphash=($entry => $value);
1.449     matthew  1706:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1707:                     delete $accesshash{$entry};
                   1708:                 }
                   1709:             }
                   1710:         } else {
1.458     matthew  1711:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1712:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1713:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1714:                 delete $accesshash{$entry};
                   1715:             }
1.185     www      1716:         }
1.191     harris41 1717:     }
1.352     www      1718: #
                   1719: # Roles
                   1720: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1721: #
1.349     www      1722:     foreach (keys %userrolehash) {
                   1723:         my $entry=$_;
1.351     www      1724:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1725: 	    split(/\:/,$entry);
                   1726:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1727:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1728:                 $rudom,$runame) eq 'ok') {
                   1729: 	    delete $userrolehash{$entry};
                   1730:         }
                   1731:     }
1.662     raeburn  1732: #
                   1733: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1734: #
                   1735:     my %domrolebuffer = ();
                   1736:     foreach my $entry (keys %domainrolehash) {
                   1737:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1738:         if ($domrolebuffer{$rudom}) {
                   1739:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1740:                       '='.&escape($domainrolehash{$entry});
                   1741:         } else {
                   1742:             $domrolebuffer{$rudom}.=&escape($entry).
                   1743:                       '='.&escape($domainrolehash{$entry});
                   1744:         }
                   1745:         delete $domainrolehash{$entry};
                   1746:     }
                   1747:     foreach my $dom (keys(%domrolebuffer)) {
                   1748:         foreach my $tryserver (keys %libserv) {
                   1749:             if ($hostdom{$tryserver} eq $dom) {
                   1750:                 unless (&reply('domroleput:'.$dom.':'.
                   1751:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1752:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1753:                 }
                   1754:             }
                   1755:         }
                   1756:     }
1.186     www      1757:     $dumpcount++;
1.157     www      1758: }
                   1759: 
                   1760: sub courselog {
                   1761:     my $what=shift;
1.158     www      1762:     $what=time.':'.$what;
1.620     albertel 1763:     unless ($env{'request.course.id'}) { return ''; }
                   1764:     $coursedombuf{$env{'request.course.id'}}=
                   1765:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1766:     $coursenumbuf{$env{'request.course.id'}}=
                   1767:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1768:     $coursehombuf{$env{'request.course.id'}}=
                   1769:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1770:     $coursedescrbuf{$env{'request.course.id'}}=
                   1771:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1772:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1773:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1774:     $courseownerbuf{$env{'request.course.id'}}=
                   1775:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1776:     $coursetypebuf{$env{'request.course.id'}}=
                   1777:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1778:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1779: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1780:     } else {
1.620     albertel 1781: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1782:     }
1.620     albertel 1783:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1784: 	&flushcourselogs();
                   1785:     }
1.158     www      1786: }
                   1787: 
                   1788: sub courseacclog {
                   1789:     my $fnsymb=shift;
1.620     albertel 1790:     unless ($env{'request.course.id'}) { return ''; }
                   1791:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1792:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1793:         $what.=':POST';
1.583     matthew  1794:         # FIXME: Probably ought to escape things....
1.620     albertel 1795: 	foreach (keys %env) {
1.158     www      1796:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1797: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1798:             }
1.191     harris41 1799:         }
1.583     matthew  1800:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1801:         # FIXME: We should not be depending on a form parameter that someone
                   1802:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1803:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1804:             $what.= ':POST';
                   1805:             # FIXME: Probably ought to escape things....
                   1806:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1807:                                  'crsdiscuss') {
1.620     albertel 1808:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1809:             }
                   1810:         }
1.158     www      1811:     }
                   1812:     &courselog($what);
1.149     www      1813: }
                   1814: 
1.185     www      1815: sub countacc {
                   1816:     my $url=&declutter(shift);
1.458     matthew  1817:     return if (! defined($url) || $url eq '');
1.620     albertel 1818:     unless ($env{'request.course.id'}) { return ''; }
                   1819:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1820:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1821:     $accesshash{$key}++;
1.185     www      1822: }
1.349     www      1823: 
1.361     www      1824: sub linklog {
                   1825:     my ($from,$to)=@_;
                   1826:     $from=&declutter($from);
                   1827:     $to=&declutter($to);
                   1828:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1829:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1830: }
                   1831:   
1.349     www      1832: sub userrolelog {
                   1833:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1834:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1835:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1836:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1837:         ($trole=~/^ta/)) {
1.350     www      1838:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1839:        $userrolehash
                   1840:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1841:                     =$tend.':'.$tstart;
1.662     raeburn  1842:     }
                   1843:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1844:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1845:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1846:         ($trole=~/^sc/)) {
                   1847:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1848:        $domainrolehash
                   1849:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1850:                     = $tend.':'.$tstart;
                   1851:     }
1.351     www      1852: }
                   1853: 
                   1854: sub get_course_adv_roles {
                   1855:     my $cid=shift;
1.620     albertel 1856:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1857:     my %coursehash=&coursedescription($cid);
1.470     www      1858:     my %nothide=();
                   1859:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1860: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1861:     }
1.351     www      1862:     my %returnhash=();
                   1863:     my %dumphash=
                   1864:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1865:     my $now=time;
                   1866:     foreach (keys %dumphash) {
                   1867: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1868:         if (($tstart) && ($tstart<0)) { next; }
                   1869:         if (($tend) && ($tend<$now)) { next; }
                   1870:         if (($tstart) && ($now<$tstart)) { next; }
                   1871:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1872: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1873: 	if ((&privileged($username,$domain)) && 
                   1874: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1875: 	if ($role eq 'cr') { next; }
1.351     www      1876:         my $key=&plaintext($role);
1.656     albertel 1877: 	if ($role =~ /^cr/) {
                   1878: 	    $key=(split('/',$role))[3];
                   1879: 	}
1.351     www      1880:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1881:         if ($returnhash{$key}) {
                   1882: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1883:         } else {
                   1884:             $returnhash{$key}=$username.':'.$domain;
                   1885:         }
1.400     www      1886:      }
                   1887:     return %returnhash;
                   1888: }
                   1889: 
                   1890: sub get_my_roles {
                   1891:     my ($uname,$udom)=@_;
1.620     albertel 1892:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1893:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1894:     my %dumphash=
                   1895:             &dump('nohist_userroles',$udom,$uname);
                   1896:     my %returnhash=();
                   1897:     my $now=time;
                   1898:     foreach (keys %dumphash) {
                   1899: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1900:         if (($tstart) && ($tstart<0)) { next; }
                   1901:         if (($tend) && ($tend<$now)) { next; }
                   1902:         if (($tstart) && ($now<$tstart)) { next; }
                   1903:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1904: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1905:      }
                   1906:     return %returnhash;
1.399     www      1907: }
                   1908: 
                   1909: # ----------------------------------------------------- Frontpage Announcements
                   1910: #
                   1911: #
                   1912: 
                   1913: sub postannounce {
                   1914:     my ($server,$text)=@_;
                   1915:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1916:     unless ($text=~/\w/) { $text=''; }
                   1917:     return &reply('setannounce:'.&escape($text),$server);
                   1918: }
                   1919: 
                   1920: sub getannounce {
1.448     albertel 1921: 
                   1922:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1923: 	my $announcement='';
                   1924: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1925: 	close($fh);
1.399     www      1926: 	if ($announcement=~/\w/) { 
                   1927: 	    return 
                   1928:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1929:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1930: 	} else {
                   1931: 	    return '';
                   1932: 	}
                   1933:     } else {
                   1934: 	return '';
                   1935:     }
1.351     www      1936: }
1.353     www      1937: 
                   1938: # ---------------------------------------------------------- Course ID routines
                   1939: # Deal with domain's nohist_courseid.db files
                   1940: #
                   1941: 
                   1942: sub courseidput {
                   1943:     my ($domain,$what,$coursehome)=@_;
                   1944:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1945: }
                   1946: 
                   1947: sub courseiddump {
1.741     raeburn  1948:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1949:     my %returnhash=();
1.355     www      1950:     unless ($domfilter) { $domfilter=''; }
1.353     www      1951:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1952:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1953: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1954: 	        foreach (
                   1955:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1956: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1957:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1958:                                $tryserver))) {
1.506     raeburn  1959: 		    my ($key,$value)=split(/\=/,$_);
                   1960:                     if (($key) && ($value)) {
1.516     raeburn  1961: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1962:                     }
1.353     www      1963:                 }
                   1964:             }
                   1965:         }
                   1966:     }
                   1967:     return %returnhash;
                   1968: }
                   1969: 
1.658     raeburn  1970: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1971: 
                   1972: sub dcmailput {
1.685     raeburn  1973:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1974:     my $status = &Apache::lonnet::critical(
1.740     www      1975:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1976:        &escape($message),$server);
1.662     raeburn  1977:     return $status;
                   1978: }
                   1979: 
1.658     raeburn  1980: sub dcmaildump {
                   1981:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1982:     my %returnhash=();
                   1983:     if (exists($domain_primary{$dom})) {
                   1984:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1985:                                                          &escape($enddate).':';
                   1986: 	my @esc_senders=map { &escape($_)} @$senders;
                   1987: 	$cmd.=&escape(join('&',@esc_senders));
                   1988: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1989:             my ($key,$value) = split(/\=/,$_);
                   1990:             if (($key) && ($value)) {
                   1991:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  1992:             }
                   1993:         }
                   1994:     }
                   1995:     return %returnhash;
                   1996: }
1.662     raeburn  1997: # ---------------------------------------------------------- Domain roles
                   1998: 
                   1999: sub get_domain_roles {
                   2000:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2001:     if (undef($startdate) || $startdate eq '') {
                   2002:         $startdate = '.';
                   2003:     }
                   2004:     if (undef($enddate) || $enddate eq '') {
                   2005:         $enddate = '.';
                   2006:     }
                   2007:     my $rolelist = join(':',@{$roles});
                   2008:     my %personnel = ();
                   2009:     foreach my $tryserver (keys(%libserv)) {
                   2010:         if ($hostdom{$tryserver} eq $dom) {
                   2011:             %{$personnel{$tryserver}}=();
                   2012:             foreach (
                   2013:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2014:                    &escape($startdate).':'.&escape($enddate).':'.
                   2015:                    &escape($rolelist), $tryserver))) {
                   2016:                 my($key,$value) = split(/\=/,$_);
                   2017:                 if (($key) && ($value)) {
                   2018:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2019:                 }
                   2020:             }
                   2021:         }
                   2022:     }
                   2023:     return %personnel;
                   2024: }
1.658     raeburn  2025: 
1.149     www      2026: # ----------------------------------------------------------- Check out an item
                   2027: 
1.504     albertel 2028: sub get_first_access {
                   2029:     my ($type,$argsymb)=@_;
                   2030:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2031:     if ($argsymb) { $symb=$argsymb; }
                   2032:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2033:     if ($type eq 'map') {
                   2034: 	$res=&symbread($map);
                   2035:     } else {
                   2036: 	$res=$symb;
                   2037:     }
                   2038:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2039:     return $times{"$courseid\0$res"};
1.504     albertel 2040: }
                   2041: 
                   2042: sub set_first_access {
                   2043:     my ($type)=@_;
                   2044:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2045:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2046:     if ($type eq 'map') {
                   2047: 	$res=&symbread($map);
                   2048:     } else {
                   2049: 	$res=$symb;
                   2050:     }
                   2051:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2052:     if (!$firstaccess) {
1.588     albertel 2053: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2054:     }
                   2055:     return 'already_set';
1.504     albertel 2056: }
                   2057: 
1.149     www      2058: sub checkout {
                   2059:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2060:     my $now=time;
                   2061:     my $lonhost=$perlvar{'lonHostID'};
                   2062:     my $infostr=&escape(
1.234     www      2063:                  'CHECKOUTTOKEN&'.
1.149     www      2064:                  $tuname.'&'.
                   2065:                  $tudom.'&'.
                   2066:                  $tcrsid.'&'.
                   2067:                  $symb.'&'.
                   2068: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2069:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2070:     if ($token=~/^error\:/) { 
1.672     albertel 2071:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2072:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2073:                  "</font>");
                   2074:         return ''; 
                   2075:     }
                   2076: 
1.149     www      2077:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2078:     $token=~tr/a-z/A-Z/;
                   2079: 
1.153     www      2080:     my %infohash=('resource.0.outtoken' => $token,
                   2081:                   'resource.0.checkouttime' => $now,
                   2082:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2083: 
                   2084:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2085:        return '';
1.151     www      2086:     } else {
1.672     albertel 2087:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2088:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2089:                  "</font>");
1.149     www      2090:     }    
                   2091: 
                   2092:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2093:                          &escape('Checkout '.$infostr.' - '.
                   2094:                                                  $token)) ne 'ok') {
                   2095: 	return '';
1.151     www      2096:     } else {
1.672     albertel 2097:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2098:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2099:                  "</font>");
1.149     www      2100:     }
1.151     www      2101:     return $token;
1.149     www      2102: }
                   2103: 
                   2104: # ------------------------------------------------------------ Check in an item
                   2105: 
                   2106: sub checkin {
                   2107:     my $token=shift;
1.150     www      2108:     my $now=time;
                   2109:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2110:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2111:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2112:     $dtoken=~s/\W/\_/g;
1.234     www      2113:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2114:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2115: 
1.154     www      2116:     unless (($tuname) && ($tudom)) {
                   2117:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2118:         return '';
                   2119:     }
                   2120:     
                   2121:     unless (&allowed('mgr',$tcrsid)) {
                   2122:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2123:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2124:         return '';
                   2125:     }
                   2126: 
1.153     www      2127:     my %infohash=('resource.0.intoken' => $token,
                   2128:                   'resource.0.checkintime' => $now,
                   2129:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2130: 
                   2131:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2132:        return '';
                   2133:     }    
                   2134: 
                   2135:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2136:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2137: 	return '';
                   2138:     }
                   2139: 
                   2140:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2141: }
                   2142: 
                   2143: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2144: 
                   2145: sub expirespread {
                   2146:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2147:     my $cid=$env{'request.course.id'}; 
1.110     www      2148:     if ($cid) {
                   2149:        my $now=time;
                   2150:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2151:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2152:                             $env{'course.'.$cid.'.num'}.
1.110     www      2153: 	        	    ':nohist_expirationdates:'.
                   2154:                             &escape($key).'='.$now,
1.620     albertel 2155:                             $env{'course.'.$cid.'.home'})
1.110     www      2156:     }
                   2157:     return 'ok';
1.14      www      2158: }
                   2159: 
1.109     www      2160: # ----------------------------------------------------- Devalidate Spreadsheets
                   2161: 
                   2162: sub devalidate {
1.325     www      2163:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2164:     my $cid=$env{'request.course.id'}; 
1.109     www      2165:     if ($cid) {
1.391     matthew  2166:         # delete the stored spreadsheets for
                   2167:         # - the student level sheet of this user in course's homespace
                   2168:         # - the assessment level sheet for this resource 
                   2169:         #   for this user in user's homespace
1.553     albertel 2170: 	# - current conditional state info
1.325     www      2171: 	my $key=$uname.':'.$udom.':';
1.109     www      2172:         my $status=
1.299     matthew  2173: 	    &del('nohist_calculatedsheets',
1.391     matthew  2174: 		 [$key.'studentcalc:'],
1.620     albertel 2175: 		 $env{'course.'.$cid.'.domain'},
                   2176: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2177: 		.' '.
                   2178: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2179: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2180:         unless ($status eq 'ok ok') {
                   2181:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2182:                     $uname.' at '.$udom.' for '.
1.109     www      2183: 		    $symb.': '.$status);
1.133     albertel 2184:         }
1.553     albertel 2185: 	&delenv('user.state.'.$cid);
1.109     www      2186:     }
                   2187: }
                   2188: 
1.265     albertel 2189: sub get_scalar {
                   2190:     my ($string,$end) = @_;
                   2191:     my $value;
                   2192:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2193: 	$value = $1;
                   2194:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2195: 	$value = $1;
                   2196:     }
                   2197:     return &unescape($value);
                   2198: }
                   2199: 
                   2200: sub array2str {
                   2201:   my (@array) = @_;
                   2202:   my $result=&arrayref2str(\@array);
                   2203:   $result=~s/^__ARRAY_REF__//;
                   2204:   $result=~s/__END_ARRAY_REF__$//;
                   2205:   return $result;
                   2206: }
                   2207: 
1.204     albertel 2208: sub arrayref2str {
                   2209:   my ($arrayref) = @_;
1.265     albertel 2210:   my $result='__ARRAY_REF__';
1.204     albertel 2211:   foreach my $elem (@$arrayref) {
1.265     albertel 2212:     if(ref($elem) eq 'ARRAY') {
                   2213:       $result.=&arrayref2str($elem).'&';
                   2214:     } elsif(ref($elem) eq 'HASH') {
                   2215:       $result.=&hashref2str($elem).'&';
                   2216:     } elsif(ref($elem)) {
                   2217:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2218:     } else {
                   2219:       $result.=&escape($elem).'&';
                   2220:     }
                   2221:   }
                   2222:   $result=~s/\&$//;
1.265     albertel 2223:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2224:   return $result;
                   2225: }
                   2226: 
1.168     albertel 2227: sub hash2str {
1.204     albertel 2228:   my (%hash) = @_;
                   2229:   my $result=&hashref2str(\%hash);
1.265     albertel 2230:   $result=~s/^__HASH_REF__//;
                   2231:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2232:   return $result;
                   2233: }
                   2234: 
                   2235: sub hashref2str {
                   2236:   my ($hashref)=@_;
1.265     albertel 2237:   my $result='__HASH_REF__';
1.495     albertel 2238:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2239:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2240:       $result.=&arrayref2str($_).'=';
1.204     albertel 2241:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2242:       $result.=&hashref2str($_).'=';
1.204     albertel 2243:     } elsif (ref($_)) {
1.265     albertel 2244:       $result.='=';
                   2245:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2246:     } else {
1.265     albertel 2247: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2248:     }
                   2249: 
1.265     albertel 2250:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2251:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2252:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2253:       $result.=&hashref2str($hashref->{$_}).'&';
                   2254:     } elsif(ref($hashref->{$_})) {
                   2255:        $result.='&';
                   2256:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2257:     } else {
1.265     albertel 2258:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2259:     }
                   2260:   }
1.168     albertel 2261:   $result=~s/\&$//;
1.265     albertel 2262:   $result .= '__END_HASH_REF__';
1.168     albertel 2263:   return $result;
                   2264: }
                   2265: 
                   2266: sub str2hash {
1.265     albertel 2267:     my ($string)=@_;
                   2268:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2269:     return %$hash;
                   2270: }
                   2271: 
                   2272: sub str2hashref {
1.168     albertel 2273:   my ($string) = @_;
1.265     albertel 2274: 
                   2275:   my %hash;
                   2276: 
                   2277:   if($string !~ /^__HASH_REF__/) {
                   2278:       if (! ($string eq '' || !defined($string))) {
                   2279: 	  $hash{'error'}='Not hash reference';
                   2280:       }
                   2281:       return (\%hash, $string);
                   2282:   }
                   2283: 
                   2284:   $string =~ s/^__HASH_REF__//;
                   2285: 
                   2286:   while($string !~ /^__END_HASH_REF__/) {
                   2287:       #key
                   2288:       my $key='';
                   2289:       if($string =~ /^__HASH_REF__/) {
                   2290:           ($key, $string)=&str2hashref($string);
                   2291:           if(defined($key->{'error'})) {
                   2292:               $hash{'error'}='Bad data';
                   2293:               return (\%hash, $string);
                   2294:           }
                   2295:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2296:           ($key, $string)=&str2arrayref($string);
                   2297:           if($key->[0] eq 'Array reference error') {
                   2298:               $hash{'error'}='Bad data';
                   2299:               return (\%hash, $string);
                   2300:           }
                   2301:       } else {
                   2302:           $string =~ s/^(.*?)=//;
1.267     albertel 2303: 	  $key=&unescape($1);
1.265     albertel 2304:       }
                   2305:       $string =~ s/^=//;
                   2306: 
                   2307:       #value
                   2308:       my $value='';
                   2309:       if($string =~ /^__HASH_REF__/) {
                   2310:           ($value, $string)=&str2hashref($string);
                   2311:           if(defined($value->{'error'})) {
                   2312:               $hash{'error'}='Bad data';
                   2313:               return (\%hash, $string);
                   2314:           }
                   2315:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2316:           ($value, $string)=&str2arrayref($string);
                   2317:           if($value->[0] eq 'Array reference error') {
                   2318:               $hash{'error'}='Bad data';
                   2319:               return (\%hash, $string);
                   2320:           }
                   2321:       } else {
                   2322: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2323:       }
                   2324:       $string =~ s/^&//;
                   2325: 
                   2326:       $hash{$key}=$value;
1.204     albertel 2327:   }
1.265     albertel 2328: 
                   2329:   $string =~ s/^__END_HASH_REF__//;
                   2330: 
                   2331:   return (\%hash, $string);
1.204     albertel 2332: }
                   2333: 
                   2334: sub str2array {
1.265     albertel 2335:     my ($string)=@_;
                   2336:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2337:     return @$array;
                   2338: }
                   2339: 
                   2340: sub str2arrayref {
1.204     albertel 2341:   my ($string) = @_;
1.265     albertel 2342:   my @array;
                   2343: 
                   2344:   if($string !~ /^__ARRAY_REF__/) {
                   2345:       if (! ($string eq '' || !defined($string))) {
                   2346: 	  $array[0]='Array reference error';
                   2347:       }
                   2348:       return (\@array, $string);
                   2349:   }
                   2350: 
                   2351:   $string =~ s/^__ARRAY_REF__//;
                   2352: 
                   2353:   while($string !~ /^__END_ARRAY_REF__/) {
                   2354:       my $value='';
                   2355:       if($string =~ /^__HASH_REF__/) {
                   2356:           ($value, $string)=&str2hashref($string);
                   2357:           if(defined($value->{'error'})) {
                   2358:               $array[0] ='Array reference error';
                   2359:               return (\@array, $string);
                   2360:           }
                   2361:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2362:           ($value, $string)=&str2arrayref($string);
                   2363:           if($value->[0] eq 'Array reference error') {
                   2364:               $array[0] ='Array reference error';
                   2365:               return (\@array, $string);
                   2366:           }
                   2367:       } else {
                   2368: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2369:       }
                   2370:       $string =~ s/^&//;
                   2371: 
                   2372:       push(@array, $value);
1.191     harris41 2373:   }
1.265     albertel 2374: 
                   2375:   $string =~ s/^__END_ARRAY_REF__//;
                   2376: 
                   2377:   return (\@array, $string);
1.168     albertel 2378: }
                   2379: 
1.167     albertel 2380: # -------------------------------------------------------------------Temp Store
                   2381: 
1.168     albertel 2382: sub tmpreset {
                   2383:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2384:   if (!$symb) {
                   2385:     $symb=&symbread();
1.620     albertel 2386:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2387:   }
                   2388:   $symb=escape($symb);
                   2389: 
1.620     albertel 2390:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2391:   $namespace=~s/\//\_/g;
                   2392:   $namespace=~s/\W//g;
                   2393: 
1.620     albertel 2394:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2395:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2396:   if ($domain eq 'public' && $stuname eq 'public') {
                   2397:       $stuname=$ENV{'REMOTE_ADDR'};
                   2398:   }
1.168     albertel 2399:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2400:   my %hash;
                   2401:   if (tie(%hash,'GDBM_File',
                   2402: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2403: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2404:     foreach my $key (keys %hash) {
1.180     albertel 2405:       if ($key=~ /:$symb/) {
1.168     albertel 2406: 	delete($hash{$key});
                   2407:       }
                   2408:     }
                   2409:   }
                   2410: }
                   2411: 
1.167     albertel 2412: sub tmpstore {
1.168     albertel 2413:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2414: 
                   2415:   if (!$symb) {
                   2416:     $symb=&symbread();
1.620     albertel 2417:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2418:   }
                   2419:   $symb=escape($symb);
                   2420: 
                   2421:   if (!$namespace) {
                   2422:     # I don't think we would ever want to store this for a course.
                   2423:     # it seems this will only be used if we don't have a course.
1.620     albertel 2424:     #$namespace=$env{'request.course.id'};
1.168     albertel 2425:     #if (!$namespace) {
1.620     albertel 2426:       $namespace=$env{'request.state'};
1.168     albertel 2427:     #}
                   2428:   }
                   2429:   $namespace=~s/\//\_/g;
                   2430:   $namespace=~s/\W//g;
1.620     albertel 2431:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2432:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2433:   if ($domain eq 'public' && $stuname eq 'public') {
                   2434:       $stuname=$ENV{'REMOTE_ADDR'};
                   2435:   }
1.168     albertel 2436:   my $now=time;
                   2437:   my %hash;
                   2438:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2439:   if (tie(%hash,'GDBM_File',
                   2440: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2441: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2442:     $hash{"version:$symb"}++;
                   2443:     my $version=$hash{"version:$symb"};
                   2444:     my $allkeys=''; 
                   2445:     foreach my $key (keys(%$storehash)) {
                   2446:       $allkeys.=$key.':';
1.591     albertel 2447:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2448:     }
                   2449:     $hash{"$version:$symb:timestamp"}=$now;
                   2450:     $allkeys.='timestamp';
                   2451:     $hash{"$version:keys:$symb"}=$allkeys;
                   2452:     if (untie(%hash)) {
                   2453:       return 'ok';
                   2454:     } else {
                   2455:       return "error:$!";
                   2456:     }
                   2457:   } else {
                   2458:     return "error:$!";
                   2459:   }
                   2460: }
1.167     albertel 2461: 
1.168     albertel 2462: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2463: 
1.168     albertel 2464: sub tmprestore {
                   2465:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2466: 
1.168     albertel 2467:   if (!$symb) {
                   2468:     $symb=&symbread();
1.620     albertel 2469:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2470:   }
                   2471:   $symb=escape($symb);
                   2472: 
1.620     albertel 2473:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2474: 
1.620     albertel 2475:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2476:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2477:   if ($domain eq 'public' && $stuname eq 'public') {
                   2478:       $stuname=$ENV{'REMOTE_ADDR'};
                   2479:   }
1.168     albertel 2480:   my %returnhash;
                   2481:   $namespace=~s/\//\_/g;
                   2482:   $namespace=~s/\W//g;
                   2483:   my %hash;
                   2484:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2485:   if (tie(%hash,'GDBM_File',
                   2486: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2487: 	  &GDBM_READER(),0640)) {
1.168     albertel 2488:     my $version=$hash{"version:$symb"};
                   2489:     $returnhash{'version'}=$version;
                   2490:     my $scope;
                   2491:     for ($scope=1;$scope<=$version;$scope++) {
                   2492:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2493:       my @keys=split(/:/,$vkeys);
                   2494:       my $key;
                   2495:       $returnhash{"$scope:keys"}=$vkeys;
                   2496:       foreach $key (@keys) {
1.591     albertel 2497: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2498: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2499:       }
                   2500:     }
1.168     albertel 2501:     if (!(untie(%hash))) {
                   2502:       return "error:$!";
                   2503:     }
                   2504:   } else {
                   2505:     return "error:$!";
                   2506:   }
                   2507:   return %returnhash;
1.167     albertel 2508: }
                   2509: 
1.9       www      2510: # ----------------------------------------------------------------------- Store
                   2511: 
                   2512: sub store {
1.124     www      2513:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2514:     my $home='';
                   2515: 
1.168     albertel 2516:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2517: 
1.213     www      2518:     $symb=&symbclean($symb);
1.122     albertel 2519:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2520: 
1.620     albertel 2521:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2522:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2523: 
                   2524:     &devalidate($symb,$stuname,$domain);
1.109     www      2525: 
                   2526:     $symb=escape($symb);
1.187     www      2527:     if (!$namespace) { 
1.620     albertel 2528:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2529:           return ''; 
                   2530:        } 
                   2531:     }
1.620     albertel 2532:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2533: 
                   2534:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2535:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2536: 
1.12      www      2537:     my $namevalue='';
1.191     harris41 2538:     foreach (keys %$storehash) {
1.591     albertel 2539:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2540:     }
1.12      www      2541:     $namevalue=~s/\&$//;
1.187     www      2542:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2543:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2544: }
                   2545: 
1.47      www      2546: # -------------------------------------------------------------- Critical Store
                   2547: 
                   2548: sub cstore {
1.124     www      2549:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2550:     my $home='';
                   2551: 
1.168     albertel 2552:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2553: 
1.213     www      2554:     $symb=&symbclean($symb);
1.122     albertel 2555:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2556: 
1.620     albertel 2557:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2558:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2559: 
                   2560:     &devalidate($symb,$stuname,$domain);
1.109     www      2561: 
                   2562:     $symb=escape($symb);
1.187     www      2563:     if (!$namespace) { 
1.620     albertel 2564:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2565:           return ''; 
                   2566:        } 
                   2567:     }
1.620     albertel 2568:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2569: 
                   2570:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2571:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2572: 
1.47      www      2573:     my $namevalue='';
1.191     harris41 2574:     foreach (keys %$storehash) {
1.591     albertel 2575:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2576:     }
1.47      www      2577:     $namevalue=~s/\&$//;
1.187     www      2578:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2579:     return critical
                   2580:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2581: }
                   2582: 
1.9       www      2583: # --------------------------------------------------------------------- Restore
                   2584: 
                   2585: sub restore {
1.124     www      2586:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2587:     my $home='';
                   2588: 
1.168     albertel 2589:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2590: 
1.122     albertel 2591:     if (!$symb) {
                   2592:       unless ($symb=escape(&symbread())) { return ''; }
                   2593:     } else {
1.213     www      2594:       $symb=&escape(&symbclean($symb));
1.122     albertel 2595:     }
1.188     www      2596:     if (!$namespace) { 
1.620     albertel 2597:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2598:           return ''; 
                   2599:        } 
                   2600:     }
1.620     albertel 2601:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2602:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2603:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2604:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2605: 
1.12      www      2606:     my %returnhash=();
1.191     harris41 2607:     foreach (split(/\&/,$answer)) {
1.12      www      2608: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2609:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2610:     }
1.75      www      2611:     my $version;
                   2612:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2613:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2614:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2615:        }
1.75      www      2616:     }
1.13      www      2617:     return %returnhash;
1.34      www      2618: }
                   2619: 
                   2620: # ---------------------------------------------------------- Course Description
                   2621: 
                   2622: sub coursedescription {
1.731     albertel 2623:     my ($courseid,$args)=@_;
1.34      www      2624:     $courseid=~s/^\///;
1.49      www      2625:     $courseid=~s/\_/\//g;
1.34      www      2626:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2627:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2628:     my $normalid=$cdomain.'_'.$cnum;
                   2629:     # need to always cache even if we get errors otherwise we keep 
                   2630:     # trying and trying and trying to get the course description.
                   2631:     my %envhash=();
                   2632:     my %returnhash=();
1.731     albertel 2633:     
                   2634:     my $expiretime=600;
                   2635:     if ($env{'request.course.id'} eq $normalid) {
                   2636: 	$expiretime=120;
                   2637:     }
                   2638: 
                   2639:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2640:     if (!$args->{'freshen_cache'}
                   2641: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2642: 	foreach my $key (keys(%env)) {
                   2643: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2644: 	    my ($setting) = $1;
                   2645: 	    $returnhash{$setting} = $env{$key};
                   2646: 	}
                   2647: 	return %returnhash;
                   2648:     }
                   2649: 
                   2650:     # get the data agin
                   2651:     if (!$args->{'one_time'}) {
                   2652: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2653:     }
1.34      www      2654:     if ($chome ne 'no_host') {
1.302     albertel 2655:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2656:        if (!exists($returnhash{'con_lost'})) {
                   2657:            $returnhash{'home'}= $chome;
                   2658: 	   $returnhash{'domain'} = $cdomain;
                   2659: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2660:            if (!defined($returnhash{'type'})) {
                   2661:                $returnhash{'type'} = 'Course';
                   2662:            }
1.130     albertel 2663:            while (my ($name,$value) = each %returnhash) {
1.53      www      2664:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2665:            }
1.270     www      2666:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2667:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2668: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2669:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2670:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2671:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2672:        }
                   2673:     }
1.731     albertel 2674:     if (!$args->{'one_time'}) {
                   2675: 	&appenv(%envhash);
                   2676:     }
1.302     albertel 2677:     return %returnhash;
1.461     www      2678: }
                   2679: 
                   2680: # -------------------------------------------------See if a user is privileged
                   2681: 
                   2682: sub privileged {
                   2683:     my ($username,$domain)=@_;
                   2684:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2685: 			&homeserver($username,$domain));
                   2686:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2687:     my $now=time;
                   2688:     if ($rolesdump ne '') {
                   2689:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2690: 	    if ($_!~/^rolesdef_/) {
1.461     www      2691: 		my ($area,$role)=split(/=/,$_);
                   2692: 		$area=~s/\_\w\w$//;
                   2693: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2694: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2695: 		    my $active=1;
                   2696: 		    if ($tend) {
                   2697: 			if ($tend<$now) { $active=0; }
                   2698: 		    }
                   2699: 		    if ($tstart) {
                   2700: 			if ($tstart>$now) { $active=0; }
                   2701: 		    }
                   2702: 		    if ($active) { return 1; }
                   2703: 		}
                   2704: 	    }
                   2705: 	}
                   2706:     }
                   2707:     return 0;
1.9       www      2708: }
1.1       albertel 2709: 
1.103     harris41 2710: # -------------------------------------------------------- Get user privileges
1.11      www      2711: 
                   2712: sub rolesinit {
                   2713:     my ($domain,$username,$authhost)=@_;
                   2714:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2715:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2716:     my %allroles=();
1.678     raeburn  2717:     my %allgroups=();   
1.11      www      2718:     my $now=time;
1.743     albertel 2719:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2720:     my $group_privs;
1.11      www      2721: 
                   2722:     if ($rolesdump ne '') {
1.191     harris41 2723:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2724: 	  if ($_!~/^rolesdef_/) {
1.11      www      2725:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2726: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2727:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2728: 	    if ($role=~/^cr/) { 
1.655     albertel 2729: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2730: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2731: 		    ($tend,$tstart)=split('_',$trest);
                   2732: 		} else {
                   2733: 		    $trole=$role;
                   2734: 		}
1.678     raeburn  2735:             } elsif ($role =~ m|^gr/|) {
                   2736:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2737:                 ($trole,$group_privs) = split(/\//,$trole);
                   2738:                 $group_privs = &unescape($group_privs);
1.587     albertel 2739: 	    } else {
                   2740: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2741: 	    }
1.743     albertel 2742: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2743: 					 $username);
                   2744: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2745:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2746:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2747:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2748: 		my $spec=$trole.'.'.$area;
                   2749: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2750: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2751:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2752:                 } elsif ($trole eq 'gr') {
                   2753:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2754: 		} else {
1.567     raeburn  2755:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2756: 		}
1.12      www      2757:             }
1.662     raeburn  2758:           }
1.191     harris41 2759:         }
1.743     albertel 2760:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2761:         $userroles{'user.adv'}    = $adv;
                   2762: 	$userroles{'user.author'} = $author;
1.620     albertel 2763:         $env{'user.adv'}=$adv;
1.11      www      2764:     }
1.743     albertel 2765:     return \%userroles;  
1.11      www      2766: }
                   2767: 
1.567     raeburn  2768: sub set_arearole {
                   2769:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2770: # log the associated role with the area
                   2771:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2772:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2773: }
                   2774: 
                   2775: sub custom_roleprivs {
                   2776:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2777:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2778:     my $homsvr=homeserver($rauthor,$rdomain);
                   2779:     if ($hostname{$homsvr} ne '') {
                   2780:         my ($rdummy,$roledef)=
                   2781:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2782:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2783:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2784:             if (defined($syspriv)) {
                   2785:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2786:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2787:             }
                   2788:             if ($tdomain ne '') {
                   2789:                 if (defined($dompriv)) {
                   2790:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2791:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2792:                 }
                   2793:                 if (($trest ne '') && (defined($coursepriv))) {
                   2794:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2795:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2796:                 }
                   2797:             }
                   2798:         }
                   2799:     }
                   2800: }
                   2801: 
1.678     raeburn  2802: sub group_roleprivs {
                   2803:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2804:     my $access = 1;
                   2805:     my $now = time;
                   2806:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2807:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2808:     if ($access) {
                   2809:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2810:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2811:     }
                   2812: }
1.567     raeburn  2813: 
                   2814: sub standard_roleprivs {
                   2815:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2816:     if (defined($pr{$trole.':s'})) {
                   2817:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2818:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2819:     }
                   2820:     if ($tdomain ne '') {
                   2821:         if (defined($pr{$trole.':d'})) {
                   2822:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2823:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2824:         }
                   2825:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2826:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2827:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2828:         }
                   2829:     }
                   2830: }
                   2831: 
                   2832: sub set_userprivs {
1.678     raeburn  2833:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2834:     my $author=0;
                   2835:     my $adv=0;
1.678     raeburn  2836:     my %grouproles = ();
                   2837:     if (keys(%{$allgroups}) > 0) {
                   2838:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2839:             my ($trole,$area,$sec,$extendedarea);
                   2840:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2841:                 $trole = $1;
                   2842:                 $area = $2;
1.681     raeburn  2843:                 $sec = $3;
                   2844:                 $extendedarea = $area.$sec;
                   2845:                 if (exists($$allgroups{$area})) {
                   2846:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2847:                         my $spec = $trole.'.'.$extendedarea;
                   2848:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2849:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2850:                     }
                   2851:                 }
                   2852:             }
                   2853:         }
                   2854:     }
                   2855:     foreach (keys(%grouproles)) {
                   2856:         $$allroles{$_} = $grouproles{$_};
                   2857:     }
1.567     raeburn  2858:     foreach (keys %{$allroles}) {
                   2859:         my %thesepriv=();
                   2860:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2861:         foreach (split(/:/,$$allroles{$_})) {
                   2862:             if ($_ ne '') {
                   2863:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2864:                 if ($restrictions eq '') {
                   2865:                     $thesepriv{$privilege}='F';
                   2866:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2867:                     $thesepriv{$privilege}.=$restrictions;
                   2868:                 }
                   2869:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2870:             }
                   2871:         }
                   2872:         my $thesestr='';
                   2873:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2874:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2875:     }
                   2876:     return ($author,$adv);
                   2877: }
                   2878: 
1.12      www      2879: # --------------------------------------------------------------- get interface
                   2880: 
                   2881: sub get {
1.131     albertel 2882:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2883:    my $items='';
1.191     harris41 2884:    foreach (@$storearr) {
1.12      www      2885:        $items.=escape($_).'&';
1.191     harris41 2886:    }
1.12      www      2887:    $items=~s/\&$//;
1.620     albertel 2888:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2889:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2890:    my $uhome=&homeserver($uname,$udomain);
                   2891: 
1.133     albertel 2892:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2893:    my @pairs=split(/\&/,$rep);
1.273     albertel 2894:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2895:      return @pairs;
                   2896:    }
1.15      www      2897:    my %returnhash=();
1.42      www      2898:    my $i=0;
1.191     harris41 2899:    foreach (@$storearr) {
1.557     albertel 2900:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2901:       $i++;
1.191     harris41 2902:    }
1.15      www      2903:    return %returnhash;
1.27      www      2904: }
                   2905: 
                   2906: # --------------------------------------------------------------- del interface
                   2907: 
                   2908: sub del {
1.133     albertel 2909:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2910:    my $items='';
1.191     harris41 2911:    foreach (@$storearr) {
1.27      www      2912:        $items.=escape($_).'&';
1.191     harris41 2913:    }
1.27      www      2914:    $items=~s/\&$//;
1.620     albertel 2915:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2916:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2917:    my $uhome=&homeserver($uname,$udomain);
                   2918: 
                   2919:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2920: }
                   2921: 
                   2922: # -------------------------------------------------------------- dump interface
                   2923: 
                   2924: sub dump {
1.702     albertel 2925:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.620     albertel 2926:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2927:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2928:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2929:    if ($regexp) {
                   2930:        $regexp=&escape($regexp);
                   2931:    } else {
                   2932:        $regexp='.';
                   2933:    }
1.702     albertel 2934:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.12      www      2935:    my @pairs=split(/\&/,$rep);
                   2936:    my %returnhash=();
1.191     harris41 2937:    foreach (@pairs) {
1.702     albertel 2938:       my ($key,$value)=split(/=/,$_,2);
1.557     albertel 2939:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2940:    }
                   2941:    return %returnhash;
1.407     www      2942: }
                   2943: 
1.717     albertel 2944: # --------------------------------------------------------- dumpstore interface
                   2945: 
                   2946: sub dumpstore {
                   2947:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2948:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2949: }
                   2950: 
1.407     www      2951: # -------------------------------------------------------------- keys interface
                   2952: 
                   2953: sub getkeys {
                   2954:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2955:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2956:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2957:    my $uhome=&homeserver($uname,$udomain);
                   2958:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2959:    my @keyarray=();
                   2960:    foreach (split(/\&/,$rep)) {
                   2961:       push (@keyarray,&unescape($_));
                   2962:    }
                   2963:    return @keyarray;
1.318     matthew  2964: }
                   2965: 
1.319     matthew  2966: # --------------------------------------------------------------- currentdump
                   2967: sub currentdump {
1.328     matthew  2968:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2969:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2970:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2971:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2972:    my $uhome = &homeserver($sname,$sdom);
                   2973:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2974:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2975:    #
1.318     matthew  2976:    my %returnhash=();
1.319     matthew  2977:    #
                   2978:    if ($rep eq "unknown_cmd") { 
                   2979:        # an old lond will not know currentdump
                   2980:        # Do a dump and make it look like a currentdump
1.326     matthew  2981:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2982:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2983:        my %hash = @tmp;
                   2984:        @tmp=();
1.424     matthew  2985:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2986:    } else {
                   2987:        my @pairs=split(/\&/,$rep);
                   2988:        foreach (@pairs) {
                   2989:            my ($key,$value)=split(/=/,$_);
                   2990:            my ($symb,$param) = split(/:/,$key);
                   2991:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2992:                                                         &thaw_unescape($value);
1.319     matthew  2993:        }
1.191     harris41 2994:    }
1.12      www      2995:    return %returnhash;
1.424     matthew  2996: }
                   2997: 
                   2998: sub convert_dump_to_currentdump{
                   2999:     my %hash = %{shift()};
                   3000:     my %returnhash;
                   3001:     # Code ripped from lond, essentially.  The only difference
                   3002:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3003:     # we might run in to problems with parameter names =~ /^v\./
                   3004:     while (my ($key,$value) = each(%hash)) {
                   3005:         my ($v,$symb,$param) = split(/:/,$key);
                   3006:         next if ($v eq 'version' || $symb eq 'keys');
                   3007:         next if (exists($returnhash{$symb}) &&
                   3008:                  exists($returnhash{$symb}->{$param}) &&
                   3009:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3010:         $returnhash{$symb}->{$param}=$value;
                   3011:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3012:     }
                   3013:     #
                   3014:     # Remove all of the keys in the hashes which keep track of
                   3015:     # the version of the parameter.
                   3016:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3017:         # use a foreach because we are going to delete from the hash.
                   3018:         foreach my $key (keys(%$param_hash)) {
                   3019:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3020:         }
                   3021:     }
                   3022:     return \%returnhash;
1.12      www      3023: }
                   3024: 
1.627     albertel 3025: # ------------------------------------------------------ critical inc interface
                   3026: 
                   3027: sub cinc {
                   3028:     return &inc(@_,'critical');
                   3029: }
                   3030: 
1.449     matthew  3031: # --------------------------------------------------------------- inc interface
                   3032: 
                   3033: sub inc {
1.627     albertel 3034:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3035:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3036:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3037:     my $uhome=&homeserver($uname,$udomain);
                   3038:     my $items='';
                   3039:     if (! ref($store)) {
                   3040:         # got a single value, so use that instead
                   3041:         $items = &escape($store).'=&';
                   3042:     } elsif (ref($store) eq 'SCALAR') {
                   3043:         $items = &escape($$store).'=&';        
                   3044:     } elsif (ref($store) eq 'ARRAY') {
                   3045:         $items = join('=&',map {&escape($_);} @{$store});
                   3046:     } elsif (ref($store) eq 'HASH') {
                   3047:         while (my($key,$value) = each(%{$store})) {
                   3048:             $items.= &escape($key).'='.&escape($value).'&';
                   3049:         }
                   3050:     }
                   3051:     $items=~s/\&$//;
1.627     albertel 3052:     if ($critical) {
                   3053: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3054:     } else {
                   3055: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3056:     }
1.449     matthew  3057: }
                   3058: 
1.12      www      3059: # --------------------------------------------------------------- put interface
                   3060: 
                   3061: sub put {
1.134     albertel 3062:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3063:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3064:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3065:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3066:    my $items='';
1.191     harris41 3067:    foreach (keys %$storehash) {
1.557     albertel 3068:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3069:    }
1.12      www      3070:    $items=~s/\&$//;
1.134     albertel 3071:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3072: }
                   3073: 
1.631     albertel 3074: # ------------------------------------------------------------ newput interface
                   3075: 
                   3076: sub newput {
                   3077:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3078:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3079:    if (!$uname) { $uname=$env{'user.name'}; }
                   3080:    my $uhome=&homeserver($uname,$udomain);
                   3081:    my $items='';
                   3082:    foreach my $key (keys(%$storehash)) {
                   3083:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3084:    }
                   3085:    $items=~s/\&$//;
                   3086:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3087: }
                   3088: 
                   3089: # ---------------------------------------------------------  putstore interface
                   3090: 
1.524     raeburn  3091: sub putstore {
1.715     albertel 3092:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3093:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3094:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3095:    my $uhome=&homeserver($uname,$udomain);
                   3096:    my $items='';
1.715     albertel 3097:    foreach my $key (keys(%$storehash)) {
                   3098:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3099:    }
1.715     albertel 3100:    $items=~s/\&$//;
1.716     albertel 3101:    my $esc_symb=&escape($symb);
                   3102:    my $esc_v=&escape($version);
1.715     albertel 3103:    my $reply =
1.716     albertel 3104:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3105: 	      $uhome);
                   3106:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3107:        # gfall back to way things use to be done
1.715     albertel 3108:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3109: 			    $uname);
1.524     raeburn  3110:    }
1.715     albertel 3111:    return $reply;
                   3112: }
                   3113: 
                   3114: sub old_putstore {
1.716     albertel 3115:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3116:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3117:     if (!$uname) { $uname=$env{'user.name'}; }
                   3118:     my $uhome=&homeserver($uname,$udomain);
                   3119:     my %newstorehash;
                   3120:     foreach (keys %$storehash) {
                   3121: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3122: 	$newstorehash{$key} = $storehash->{$_};
                   3123:     }
                   3124:     my $items='';
                   3125:     my %allitems = ();
                   3126:     foreach (keys %newstorehash) {
                   3127: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3128: 	    my $key = $1.':keys:'.$2;
                   3129: 	    $allitems{$key} .= $3.':';
                   3130: 	}
                   3131: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3132:     }
                   3133:     foreach (keys %allitems) {
                   3134: 	$allitems{$_} =~ s/\:$//;
                   3135: 	$items.= $_.'='.$allitems{$_}.'&';
                   3136:     }
                   3137:     $items=~s/\&$//;
                   3138:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3139: }
                   3140: 
1.47      www      3141: # ------------------------------------------------------ critical put interface
                   3142: 
                   3143: sub cput {
1.134     albertel 3144:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3145:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3146:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3147:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3148:    my $items='';
1.191     harris41 3149:    foreach (keys %$storehash) {
1.715     albertel 3150:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3151:    }
1.47      www      3152:    $items=~s/\&$//;
1.134     albertel 3153:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3154: }
                   3155: 
                   3156: # -------------------------------------------------------------- eget interface
                   3157: 
                   3158: sub eget {
1.133     albertel 3159:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3160:    my $items='';
1.191     harris41 3161:    foreach (@$storearr) {
1.12      www      3162:        $items.=escape($_).'&';
1.191     harris41 3163:    }
1.12      www      3164:    $items=~s/\&$//;
1.620     albertel 3165:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3166:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3167:    my $uhome=&homeserver($uname,$udomain);
                   3168:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3169:    my @pairs=split(/\&/,$rep);
                   3170:    my %returnhash=();
1.42      www      3171:    my $i=0;
1.191     harris41 3172:    foreach (@$storearr) {
1.557     albertel 3173:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3174:       $i++;
1.191     harris41 3175:    }
1.12      www      3176:    return %returnhash;
                   3177: }
                   3178: 
1.667     albertel 3179: # ------------------------------------------------------------ tmpput interface
                   3180: sub tmpput {
                   3181:     my ($storehash,$server)=@_;
                   3182:     my $items='';
                   3183:     foreach (keys(%$storehash)) {
                   3184: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3185:     }
                   3186:     $items=~s/\&$//;
                   3187:     return &reply("tmpput:$items",$server);
                   3188: }
                   3189: 
                   3190: # ------------------------------------------------------------ tmpget interface
                   3191: sub tmpget {
1.688     albertel 3192:     my ($token,$server)=@_;
                   3193:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3194:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3195:     my %returnhash;
                   3196:     foreach my $item (split(/\&/,$rep)) {
                   3197: 	my ($key,$value)=split(/=/,$item);
                   3198: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3199:     }
                   3200:     return %returnhash;
                   3201: }
                   3202: 
1.688     albertel 3203: # ------------------------------------------------------------ tmpget interface
                   3204: sub tmpdel {
                   3205:     my ($token,$server)=@_;
                   3206:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3207:     return &reply("tmpdel:$token",$server);
                   3208: }
                   3209: 
1.341     www      3210: # ---------------------------------------------- Custom access rule evaluation
                   3211: 
                   3212: sub customaccess {
                   3213:     my ($priv,$uri)=@_;
1.620     albertel 3214:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3215:     $urealm=~s/^\W//;
                   3216:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3217:     my $access=0;
                   3218:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3219: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3220:         if ($role) {
                   3221: 	   if ($role ne $urole) { next; }
                   3222:         }
                   3223:         foreach (split(/\s*\,\s*/,$realm)) {
                   3224:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3225:             if ($tdom) {
                   3226: 		if ($tdom ne $udom) { next; }
                   3227:             }
                   3228:             if ($tcrs) {
                   3229: 		if ($tcrs ne $ucrs) { next; }
                   3230:             }
                   3231:             if ($tsec) {
                   3232: 		if ($tsec ne $usec) { next; }
                   3233:             }
                   3234:             $access=($effect eq 'allow');
                   3235:             last;
1.342     www      3236:         }
1.402     bowersj2 3237: 	if ($realm eq '' && $role eq '') {
                   3238:             $access=($effect eq 'allow');
                   3239: 	}
1.341     www      3240:     }
                   3241:     return $access;
                   3242: }
                   3243: 
1.103     harris41 3244: # ------------------------------------------------- Check for a user privilege
1.12      www      3245: 
                   3246: sub allowed {
1.579     albertel 3247:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3248:     my $ver_orguri=$uri;
1.439     www      3249:     $uri=&deversion($uri);
1.152     www      3250:     my $orguri=$uri;
1.52      www      3251:     $uri=&declutter($uri);
1.545     banghart 3252:     
1.620     albertel 3253:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3254: # Free bre access to adm and meta resources
1.529     albertel 3255:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3256: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3257: 	return 'F';
1.159     www      3258:     }
                   3259: 
1.545     banghart 3260: # Free bre access to user's own portfolio contents
1.714     raeburn  3261:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3262:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3263: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3264:         return 'F';
                   3265:     }
                   3266: 
1.714     raeburn  3267: # bre access to group if user has rgf priv for this group and course.
                   3268:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3269:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3270:         if (exists($env{'request.course.id'})) {
                   3271:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3272:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3273:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3274:                 my $courseprivid=$env{'request.course.id'};
                   3275:                 $courseprivid=~s/\_/\//;
                   3276:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3277:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3278:                     return $1; 
                   3279:                 }
                   3280:             }
                   3281:         }
                   3282:     }
                   3283: 
1.159     www      3284: # Free bre to public access
                   3285: 
                   3286:     if ($priv eq 'bre') {
1.238     www      3287:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3288: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3289:            return 'F'; 
                   3290:         }
1.238     www      3291:         if ($copyright eq 'priv') {
                   3292:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3293: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3294: 		return '';
                   3295:             }
                   3296:         }
                   3297:         if ($copyright eq 'domain') {
                   3298:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3299: 	    unless (($env{'user.domain'} eq $1) ||
                   3300:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3301: 		return '';
                   3302:             }
1.262     matthew  3303:         }
1.620     albertel 3304:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3305:             # Library role, so allow browsing of resources in this domain.
                   3306:             return 'F';
1.238     www      3307:         }
1.341     www      3308:         if ($copyright eq 'custom') {
                   3309: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3310:         }
1.14      www      3311:     }
1.264     matthew  3312:     # Domain coordinator is trying to create a course
1.620     albertel 3313:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3314:         # uri is the requested domain in this case.
                   3315:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3316:         # a role of dc for the domain in question.
1.620     albertel 3317:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3318:     }
1.29      www      3319: 
1.52      www      3320:     my $thisallowed='';
                   3321:     my $statecond=0;
                   3322:     my $courseprivid='';
                   3323: 
                   3324: # Course
                   3325: 
1.620     albertel 3326:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3327:        $thisallowed.=$1;
                   3328:     }
1.29      www      3329: 
1.52      www      3330: # Domain
                   3331: 
1.620     albertel 3332:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3333:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3334:        $thisallowed.=$1;
                   3335:     }
1.52      www      3336: 
                   3337: # Course: uri itself is a course
1.66      www      3338:     my $courseuri=$uri;
                   3339:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3340:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3341: 
1.620     albertel 3342:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3343:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3344:        $thisallowed.=$1;
                   3345:     }
1.29      www      3346: 
1.678     raeburn  3347: # Group: uri itself is a group
                   3348:     my $groupuri=$uri;
                   3349:     $groupuri=~s/^([^\/])/\/$1/;
                   3350:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3351:        =~/\Q$priv\E\&([^\:]*)/) {
                   3352:        $thisallowed.=$1;
                   3353:     }
                   3354: 
1.665     albertel 3355: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3356: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3357:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3358: 	$thisallowed='';
1.671     raeburn  3359:         my ($match)=&is_on_map($uri);
                   3360:         if ($match) {
                   3361:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3362:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3363:                 $thisallowed.=$1;
                   3364:             }
                   3365:         } else {
1.705     albertel 3366:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3367:             if ($refuri) {
                   3368:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3369:                     $thisallowed='F';
1.671     raeburn  3370:                 } else {
                   3371:                     $refuri=&declutter($refuri);
                   3372:                     my ($match) = &is_on_map($refuri);
                   3373:                     if ($match) {
                   3374:                         $thisallowed='F';
                   3375:                     }
1.669     raeburn  3376:                 }
1.671     raeburn  3377:             }
                   3378:         }
1.314     www      3379:     }
1.492     albertel 3380: 
1.52      www      3381: # Full access at system, domain or course-wide level? Exit.
1.29      www      3382: 
                   3383:     if ($thisallowed=~/F/) {
                   3384: 	return 'F';
                   3385:     }
                   3386: 
1.52      www      3387: # If this is generating or modifying users, exit with special codes
1.29      www      3388: 
1.643     www      3389:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3390: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3391: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3392: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3393: 	    unless ($auname) { return $thisallowed; }
                   3394: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3395: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3396: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3397: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3398: 	}
1.52      www      3399: 	return $thisallowed;
                   3400:     }
                   3401: #
1.103     harris41 3402: # Gathered so far: system, domain and course wide privileges
1.52      www      3403: #
                   3404: # Course: See if uri or referer is an individual resource that is part of 
                   3405: # the course
                   3406: 
1.620     albertel 3407:     if ($env{'request.course.id'}) {
1.232     www      3408: 
1.620     albertel 3409:        $courseprivid=$env{'request.course.id'};
                   3410:        if ($env{'request.course.sec'}) {
                   3411:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3412:        }
                   3413:        $courseprivid=~s/\_/\//;
                   3414:        my $checkreferer=1;
1.232     www      3415:        my ($match,$cond)=&is_on_map($uri);
                   3416:        if ($match) {
                   3417:            $statecond=$cond;
1.620     albertel 3418:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3419:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3420:                $thisallowed.=$1;
                   3421:                $checkreferer=0;
                   3422:            }
1.29      www      3423:        }
1.83      www      3424:        
1.148     www      3425:        if ($checkreferer) {
1.620     albertel 3426: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3427:             unless ($refuri) {
1.620     albertel 3428:                 foreach (keys %env) {
1.148     www      3429: 		    if ($_=~/^httpref\..*\*/) {
                   3430: 			my $pattern=$_;
1.156     www      3431:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3432:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3433:                         $pattern=~s/\//\\\//g;
1.152     www      3434:                         if ($orguri=~/$pattern/) {
1.620     albertel 3435: 			    $refuri=$env{$_};
1.148     www      3436:                         }
                   3437:                     }
1.191     harris41 3438:                 }
1.148     www      3439:             }
1.232     www      3440: 
1.148     www      3441:          if ($refuri) { 
1.152     www      3442: 	  $refuri=&declutter($refuri);
1.232     www      3443:           my ($match,$cond)=&is_on_map($refuri);
                   3444:             if ($match) {
                   3445:               my $refstatecond=$cond;
1.620     albertel 3446:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3447:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3448:                   $thisallowed.=$1;
1.53      www      3449:                   $uri=$refuri;
                   3450:                   $statecond=$refstatecond;
1.52      www      3451:               }
                   3452:           }
1.148     www      3453:         }
1.29      www      3454:        }
1.52      www      3455:    }
1.29      www      3456: 
1.52      www      3457: #
1.103     harris41 3458: # Gathered now: all privileges that could apply, and condition number
1.52      www      3459: # 
                   3460: #
                   3461: # Full or no access?
                   3462: #
1.29      www      3463: 
1.52      www      3464:     if ($thisallowed=~/F/) {
                   3465: 	return 'F';
                   3466:     }
1.29      www      3467: 
1.52      www      3468:     unless ($thisallowed) {
                   3469:         return '';
                   3470:     }
1.29      www      3471: 
1.52      www      3472: # Restrictions exist, deal with them
                   3473: #
                   3474: #   C:according to course preferences
                   3475: #   R:according to resource settings
                   3476: #   L:unless locked
                   3477: #   X:according to user session state
                   3478: #
                   3479: 
                   3480: # Possibly locked functionality, check all courses
1.54      www      3481: # Locks might take effect only after 10 minutes cache expiration for other
                   3482: # courses, and 2 minutes for current course
1.52      www      3483: 
                   3484:     my $envkey;
                   3485:     if ($thisallowed=~/L/) {
1.620     albertel 3486:         foreach $envkey (keys %env) {
1.54      www      3487:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3488:                my $courseid=$2;
                   3489:                my $roleid=$1.'.'.$2;
1.92      www      3490:                $courseid=~s/^\///;
1.54      www      3491:                my $expiretime=600;
1.620     albertel 3492:                if ($env{'request.role'} eq $roleid) {
1.54      www      3493: 		  $expiretime=120;
                   3494:                }
                   3495: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3496:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3497:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3498: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3499:                }
1.620     albertel 3500:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3501:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3502: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3503:                        &log($env{'user.domain'},$env{'user.name'},
                   3504:                             $env{'user.home'},
1.57      www      3505:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3506:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3507:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3508: 		       return '';
                   3509:                    }
                   3510:                }
1.620     albertel 3511:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3512:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3513: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3514:                        &log($env{'user.domain'},$env{'user.name'},
                   3515:                             $env{'user.home'},
1.57      www      3516:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3517:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3518:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3519: 		       return '';
                   3520:                    }
                   3521:                }
                   3522: 	   }
1.29      www      3523:        }
1.52      www      3524:     }
                   3525:    
                   3526: #
                   3527: # Rest of the restrictions depend on selected course
                   3528: #
                   3529: 
1.620     albertel 3530:     unless ($env{'request.course.id'}) {
1.52      www      3531:        return '1';
                   3532:     }
1.29      www      3533: 
1.52      www      3534: #
                   3535: # Now user is definitely in a course
                   3536: #
1.53      www      3537: 
                   3538: 
                   3539: # Course preferences
                   3540: 
                   3541:    if ($thisallowed=~/C/) {
1.620     albertel 3542:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3543:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3544:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3545: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3546: 	   if ($priv ne 'pch') { 
                   3547: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3548: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3549: 			$env{'request.course.id'});
                   3550: 	   }
1.237     www      3551:            return '';
                   3552:        }
                   3553: 
1.620     albertel 3554:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3555: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3556: 	   if ($priv ne 'pch') { 
                   3557: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3558: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3559: 			$env{'request.course.id'});
                   3560: 	   }
1.54      www      3561:            return '';
                   3562:        }
1.53      www      3563:    }
                   3564: 
                   3565: # Resource preferences
                   3566: 
                   3567:    if ($thisallowed=~/R/) {
1.620     albertel 3568:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3569:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3570: 	   if ($priv ne 'pch') { 
                   3571: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3572: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3573: 	   }
                   3574: 	   return '';
1.54      www      3575:        }
1.53      www      3576:    }
1.30      www      3577: 
1.246     www      3578: # Restricted by state or randomout?
1.30      www      3579: 
1.52      www      3580:    if ($thisallowed=~/X/) {
1.620     albertel 3581:       if ($env{'acc.randomout'}) {
1.579     albertel 3582: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3583:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3584:             return ''; 
                   3585:          }
1.247     www      3586:       }
                   3587:       if (&condval($statecond)) {
1.52      www      3588: 	 return '2';
                   3589:       } else {
                   3590:          return '';
                   3591:       }
                   3592:    }
1.30      www      3593: 
1.52      www      3594:    return 'F';
1.232     www      3595: }
                   3596: 
1.710     albertel 3597: sub split_uri_for_cond {
                   3598:     my $uri=&deversion(&declutter(shift));
                   3599:     my @uriparts=split(/\//,$uri);
                   3600:     my $filename=pop(@uriparts);
                   3601:     my $pathname=join('/',@uriparts);
                   3602:     return ($pathname,$filename);
                   3603: }
1.232     www      3604: # --------------------------------------------------- Is a resource on the map?
                   3605: 
                   3606: sub is_on_map {
1.710     albertel 3607:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3608:     #Trying to find the conditional for the file
1.620     albertel 3609:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3610: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3611:     if ($match) {
1.289     bowersj2 3612: 	return (1,$1);
                   3613:     } else {
1.434     www      3614: 	return (0,0);
1.289     bowersj2 3615:     }
1.12      www      3616: }
                   3617: 
1.427     www      3618: # --------------------------------------------------------- Get symb from alias
                   3619: 
                   3620: sub get_symb_from_alias {
                   3621:     my $symb=shift;
                   3622:     my ($map,$resid,$url)=&decode_symb($symb);
                   3623: # Already is a symb
                   3624:     if ($url) { return $symb; }
                   3625: # Must be an alias
                   3626:     my $aliassymb='';
                   3627:     my %bighash;
1.620     albertel 3628:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3629:                             &GDBM_READER(),0640)) {
                   3630:         my $rid=$bighash{'mapalias_'.$symb};
                   3631: 	if ($rid) {
                   3632: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3633: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3634: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3635: 	}
                   3636:         untie %bighash;
                   3637:     }
                   3638:     return $aliassymb;
                   3639: }
                   3640: 
1.12      www      3641: # ----------------------------------------------------------------- Define Role
                   3642: 
                   3643: sub definerole {
                   3644:   if (allowed('mcr','/')) {
                   3645:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3646:     foreach (split(':',$sysrole)) {
1.21      www      3647: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3648:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3649:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3650: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3651:                return "refused:s:$crole&$cqual"; 
                   3652:             }
                   3653:         }
1.191     harris41 3654:     }
1.392     www      3655:     foreach (split(':',$domrole)) {
1.21      www      3656: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3657:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3658:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3659: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3660:                return "refused:d:$crole&$cqual"; 
                   3661:             }
                   3662:         }
1.191     harris41 3663:     }
1.392     www      3664:     foreach (split(':',$courole)) {
1.21      www      3665: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3666:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3667:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3668: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3669:                return "refused:c:$crole&$cqual"; 
                   3670:             }
                   3671:         }
1.191     harris41 3672:     }
1.620     albertel 3673:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3674:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3675: 	        "rolesdef_$rolename=".
                   3676:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3677:     return reply($command,$env{'user.home'});
1.12      www      3678:   } else {
                   3679:     return 'refused';
                   3680:   }
1.105     harris41 3681: }
                   3682: 
                   3683: # ---------------- Make a metadata query against the network of library servers
                   3684: 
                   3685: sub metadata_query {
1.244     matthew  3686:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3687:     my %rhash;
1.244     matthew  3688:     my @server_list = (defined($server_array) ? @$server_array
                   3689:                                               : keys(%libserv) );
                   3690:     for my $server (@server_list) {
1.118     harris41 3691: 	unless ($custom or $customshow) {
                   3692: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3693: 	    $rhash{$server}=$reply;
                   3694: 	}
                   3695: 	else {
                   3696: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3697: 			     &escape($custom).':'.&escape($customshow),
                   3698: 			     $server);
                   3699: 	    $rhash{$server}=$reply;
                   3700: 	}
1.112     harris41 3701:     }
1.118     harris41 3702:     return \%rhash;
1.240     www      3703: }
                   3704: 
                   3705: # ----------------------------------------- Send log queries and wait for reply
                   3706: 
                   3707: sub log_query {
                   3708:     my ($uname,$udom,$query,%filters)=@_;
                   3709:     my $uhome=&homeserver($uname,$udom);
                   3710:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3711:     my $uhost=$hostname{$uhome};
1.241     www      3712:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3713:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3714:                        $uhome);
1.479     albertel 3715:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3716:     return get_query_reply($queryid);
                   3717: }
                   3718: 
1.508     raeburn  3719: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3720: 
                   3721: sub fetch_enrollment_query {
1.511     raeburn  3722:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3723:     my $homeserver;
1.547     raeburn  3724:     my $maxtries = 1;
1.508     raeburn  3725:     if ($context eq 'automated') {
                   3726:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3727:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3728:     } else {
                   3729:         $homeserver = &homeserver($cnum,$dom);
                   3730:     }
1.506     raeburn  3731:     my $host=$hostname{$homeserver};
                   3732:     my $cmd = '';
                   3733:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3734:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3735:     }
                   3736:     $cmd =~ s/%%$//;
                   3737:     $cmd = &escape($cmd);
                   3738:     my $query = 'fetchenrollment';
1.620     albertel 3739:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3740:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3741:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3742:         return 'error: '.$queryid;
                   3743:     }
1.506     raeburn  3744:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3745:     my $tries = 1;
                   3746:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3747:         $reply = &get_query_reply($queryid);
                   3748:         $tries ++;
                   3749:     }
1.526     raeburn  3750:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3751:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3752:     } else {
1.515     raeburn  3753:         my @responses = split/:/,$reply;
                   3754:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3755:             foreach (@responses) {
                   3756:                 my ($key,$value) = split/=/,$_;
                   3757:                 $$replyref{$key} = $value;
                   3758:             }
                   3759:         } else {
1.506     raeburn  3760:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3761:             foreach (@responses) {
                   3762:                 my ($key,$value) = split/=/,$_;
                   3763:                 $$replyref{$key} = $value;
                   3764:                 if ($value > 0) {
                   3765:                     foreach (@{$$affiliatesref{$key}}) {
                   3766:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3767:                         my $destname = $pathname.'/'.$filename;
                   3768:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3769:                         if ($xml_classlist =~ /^error/) {
                   3770:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3771:                         } else {
1.506     raeburn  3772:                             if ( open(FILE,">$destname") ) {
                   3773:                                 print FILE &unescape($xml_classlist);
                   3774:                                 close(FILE);
1.526     raeburn  3775:                             } else {
                   3776:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3777:                             }
                   3778:                         }
                   3779:                     }
                   3780:                 }
                   3781:             }
                   3782:         }
                   3783:         return 'ok';
                   3784:     }
                   3785:     return 'error';
                   3786: }
                   3787: 
1.242     www      3788: sub get_query_reply {
                   3789:     my $queryid=shift;
1.240     www      3790:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3791:     my $reply='';
                   3792:     for (1..100) {
                   3793: 	sleep 2;
                   3794:         if (-e $replyfile.'.end') {
1.448     albertel 3795: 	    if (open(my $fh,$replyfile)) {
1.240     www      3796:                $reply.=<$fh>;
1.448     albertel 3797:                close($fh);
1.240     www      3798: 	   } else { return 'error: reply_file_error'; }
1.242     www      3799:            return &unescape($reply);
                   3800: 	}
1.240     www      3801:     }
1.242     www      3802:     return 'timeout:'.$queryid;
1.240     www      3803: }
                   3804: 
                   3805: sub courselog_query {
1.241     www      3806: #
                   3807: # possible filters:
                   3808: # url: url or symb
                   3809: # username
                   3810: # domain
                   3811: # action: view, submit, grade
                   3812: # start: timestamp
                   3813: # end: timestamp
                   3814: #
1.240     www      3815:     my (%filters)=@_;
1.620     albertel 3816:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3817:     if ($filters{'url'}) {
                   3818: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3819:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3820:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3821:     }
1.620     albertel 3822:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3823:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3824:     return &log_query($cname,$cdom,'courselog',%filters);
                   3825: }
                   3826: 
                   3827: sub userlog_query {
                   3828:     my ($uname,$udom,%filters)=@_;
                   3829:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3830: }
                   3831: 
1.506     raeburn  3832: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3833: 
                   3834: sub auto_run {
1.508     raeburn  3835:     my ($cnum,$cdom) = @_;
                   3836:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3837:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3838:     return $response;
                   3839: }
                   3840:                                                                                    
                   3841: sub auto_get_sections {
1.508     raeburn  3842:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3843:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3844:     my @secs = ();
1.511     raeburn  3845:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3846:     unless ($response eq 'refused') {
                   3847:         @secs = split/:/,$response;
                   3848:     }
                   3849:     return @secs;
                   3850: }
                   3851:                                                                                    
                   3852: sub auto_new_course {
1.508     raeburn  3853:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3854:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3855:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3856:     return $response;
                   3857: }
                   3858:                                                                                    
                   3859: sub auto_validate_courseID {
1.508     raeburn  3860:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3861:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3862:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3863:     return $response;
                   3864: }
                   3865:                                                                                    
                   3866: sub auto_create_password {
1.508     raeburn  3867:     my ($cnum,$cdom,$authparam) = @_;
                   3868:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3869:     my $create_passwd = 0;
                   3870:     my $authchk = '';
1.511     raeburn  3871:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3872:     if ($response eq 'refused') {
                   3873:         $authchk = 'refused';
                   3874:     } else {
                   3875:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3876:     }
                   3877:     return ($authparam,$create_passwd,$authchk);
                   3878: }
                   3879: 
1.706     raeburn  3880: sub auto_photo_permission {
                   3881:     my ($cnum,$cdom,$students) = @_;
                   3882:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 3883:     my ($outcome,$perm_reqd,$conditions) = 
                   3884: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 3885:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3886: 	return (undef,undef);
                   3887:     }
1.706     raeburn  3888:     return ($outcome,$perm_reqd,$conditions);
                   3889: }
                   3890: 
                   3891: sub auto_checkphotos {
                   3892:     my ($uname,$udom,$pid) = @_;
                   3893:     my $homeserver = &homeserver($uname,$udom);
                   3894:     my ($result,$resulttype);
                   3895:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 3896: 				   &escape($uname).':'.&escape($pid),
                   3897: 				   $homeserver));
1.709     albertel 3898:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3899: 	return (undef,undef);
                   3900:     }
1.706     raeburn  3901:     if ($outcome) {
                   3902:         ($result,$resulttype) = split(/:/,$outcome);
                   3903:     } 
                   3904:     return ($result,$resulttype);
                   3905: }
                   3906: 
                   3907: sub auto_photochoice {
                   3908:     my ($cnum,$cdom) = @_;
                   3909:     my $homeserver = &homeserver($cnum,$cdom);
                   3910:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 3911: 						       &escape($cdom),
                   3912: 						       $homeserver)));
1.709     albertel 3913:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3914: 	return (undef,undef);
                   3915:     }
1.706     raeburn  3916:     return ($update,$comment);
                   3917: }
                   3918: 
                   3919: sub auto_photoupdate {
                   3920:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   3921:     my $homeserver = &homeserver($cnum,$dom);
                   3922:     my $host=$hostname{$homeserver};
                   3923:     my $cmd = '';
                   3924:     my $maxtries = 1;
                   3925:     foreach (keys %{$affiliatesref}) {
                   3926:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   3927:     }
                   3928:     $cmd =~ s/%%$//;
                   3929:     $cmd = &escape($cmd);
                   3930:     my $query = 'institutionalphotos';
                   3931:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   3932:     unless ($queryid=~/^\Q$host\E\_/) {
                   3933:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   3934:         return 'error: '.$queryid;
                   3935:     }
                   3936:     my $reply = &get_query_reply($queryid);
                   3937:     my $tries = 1;
                   3938:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3939:         $reply = &get_query_reply($queryid);
                   3940:         $tries ++;
                   3941:     }
                   3942:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   3943:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   3944:     } else {
                   3945:         my @responses = split(/:/,$reply);
                   3946:         my $outcome = shift(@responses); 
                   3947:         foreach my $item (@responses) {
                   3948:             my ($key,$value) = split(/=/,$item);
                   3949:             $$photo{$key} = $value;
                   3950:         }
                   3951:         return $outcome;
                   3952:     }
                   3953:     return 'error';
                   3954: }
                   3955: 
1.521     raeburn  3956: sub auto_instcode_format {
                   3957:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3958:     my $courses = '';
                   3959:     my $homeserver;
                   3960:     if ($caller eq 'global') {
1.584     raeburn  3961:         foreach my $tryserver (keys %libserv) {
                   3962:             if ($hostdom{$tryserver} eq $codedom) {
                   3963:                 $homeserver = $tryserver;
                   3964:                 last;
                   3965:             }
                   3966:         }
1.620     albertel 3967:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3968:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3969:         }
1.521     raeburn  3970:     } else {
                   3971:         $homeserver = &homeserver($caller,$codedom);
                   3972:     }
                   3973:     foreach (keys %{$instcodes}) {
                   3974:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3975:     }
                   3976:     chop($courses);
                   3977:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3978:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3979:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3980:         %{$codes} = &str2hash($codes_str);
                   3981:         @{$codetitles} = &str2array($codetitles_str);
                   3982:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3983:         %{$cat_order} = &str2hash($cat_order_str);
                   3984:         return 'ok';
                   3985:     }
                   3986:     return $response;
                   3987: }
                   3988: 
1.679     raeburn  3989: # ------------------------------------------------------- Course Group routines
                   3990: 
                   3991: sub get_coursegroups {
1.683     raeburn  3992:     my ($cdom,$cnum,$group) = @_;
                   3993:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  3994: }
                   3995: 
                   3996: sub modify_coursegroup {
                   3997:     my ($cdom,$cnum,$groupsettings) = @_;
                   3998:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   3999: }
                   4000: 
                   4001: sub modify_group_roles {
                   4002:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4003:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4004:     my $role = 'gr/'.&escape($userprivs);
                   4005:     my ($uname,$udom) = split(/:/,$user);
                   4006:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4007:     if ($result eq 'ok') {
                   4008:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4009:     }
1.679     raeburn  4010:     return $result;
                   4011: }
                   4012: 
                   4013: sub modify_coursegroup_membership {
                   4014:     my ($cdom,$cnum,$membership) = @_;
                   4015:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4016:     return $result;
                   4017: }
                   4018: 
1.682     raeburn  4019: sub get_active_groups {
                   4020:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4021:     my $now = time;
                   4022:     my %groups = ();
                   4023:     foreach my $key (keys(%env)) {
                   4024:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4025:             my ($start,$end) = split(/\./,$env{$key});
                   4026:             if (($end!=0) && ($end<$now)) { next; }
                   4027:             if (($start!=0) && ($start>$now)) { next; }
                   4028:             if ($1 eq $cdom && $2 eq $cnum) {
                   4029:                 $groups{$3} = $env{$key} ;
                   4030:             }
                   4031:         }
                   4032:     }
                   4033:     return %groups;
                   4034: }
                   4035: 
1.683     raeburn  4036: sub get_group_membership {
                   4037:     my ($cdom,$cnum,$group) = @_;
                   4038:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4039: }
                   4040: 
                   4041: sub get_users_groups {
                   4042:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4043:     my @usersgroups;
1.683     raeburn  4044:     my $cachetime=1800;
                   4045:     $courseid=~s/\_/\//g;
                   4046:     $courseid=~s/^(\w)/\/$1/;
                   4047: 
                   4048:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4049:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4050:     if (defined($cached)) {
1.734     albertel 4051:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4052:     } else {  
                   4053:         $grouplist = '';
                   4054:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4055:         my ($tmp) = keys(%roleshash);
                   4056:         if ($tmp=~/^error:/) {
                   4057:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4058:         } else {
                   4059:             my $access_end = $env{'course.'.$courseid.
                   4060:                                   '.default_enrollment_end_date'};
                   4061:             my $now = time;
1.734     albertel 4062:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4063:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4064:                     my $group = $1;
                   4065:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4066:                         my $start = $2;
                   4067:                         my $end = $1;
                   4068:                         if ($start == -1) { next; } # deleted from group
                   4069:                         if (($start!=0) && ($start>$now)) { next; }
                   4070:                         if (($end!=0) && ($end<$now)) {
                   4071:                             if ($access_end && $access_end < $now) {
                   4072:                                 if ($access_end - $end < 86400) {
                   4073:                                     push(@usersgroups,$group);
                   4074:                                 }
                   4075:                             }
                   4076:                             next;
                   4077:                         }
                   4078:                         push(@usersgroups,$group);
                   4079:                     }
1.683     raeburn  4080:                 }
                   4081:             }
1.733     raeburn  4082:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4083:             $grouplist = join(':',@usersgroups);
                   4084:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4085:         }
                   4086:     }
1.733     raeburn  4087:     return @usersgroups;
1.683     raeburn  4088: }
                   4089: 
                   4090: sub devalidate_getgroups_cache {
                   4091:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4092:     my $courseid = $cdom.'_'.$cnum;
                   4093:     $courseid=~s/\_/\//g;
                   4094:     $courseid=~s/^(\w)/\/$1/;
                   4095:     my $hashid="$udom:$uname:$courseid";
                   4096:     &devalidate_cache_new('getgroups',$hashid);
                   4097: }
                   4098: 
1.12      www      4099: # ------------------------------------------------------------------ Plain Text
                   4100: 
                   4101: sub plaintext {
1.742     raeburn  4102:     my ($short,$type,$cid) = @_;
                   4103:     if (!defined($cid)) {
                   4104:         $cid = $env{'request.course.id'};
                   4105:     }
                   4106:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4107:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4108:                                           '.plaintext'});
                   4109:     }
                   4110:     my %rolenames = (
                   4111:                       Course => 'std',
                   4112:                       Group => 'alt1',
                   4113:                     );
                   4114:     if (defined($type) && 
                   4115:          defined($rolenames{$type}) && 
                   4116:          defined($prp{$short}{$rolenames{$type}})) {
                   4117:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4118:     } else {
                   4119:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4120:     }
1.12      www      4121: }
                   4122: 
                   4123: # ----------------------------------------------------------------- Assign Role
                   4124: 
                   4125: sub assignrole {
1.357     www      4126:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4127:     my $mrole;
                   4128:     if ($role =~ /^cr\//) {
1.393     www      4129:         my $cwosec=$url;
                   4130:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4131: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4132:            &logthis('Refused custom assignrole: '.
                   4133:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4134: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4135:            return 'refused'; 
                   4136:         }
1.21      www      4137:         $mrole='cr';
1.678     raeburn  4138:     } elsif ($role =~ /^gr\//) {
                   4139:         my $cwogrp=$url;
                   4140:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4141:         unless (&allowed('mdg',$cwogrp)) {
                   4142:             &logthis('Refused group assignrole: '.
                   4143:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4144:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4145:             return 'refused';
                   4146:         }
                   4147:         $mrole='gr';
1.21      www      4148:     } else {
1.82      www      4149:         my $cwosec=$url;
1.83      www      4150:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4151:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4152:            &logthis('Refused assignrole: '.
                   4153:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4154: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4155:            return 'refused'; 
                   4156:         }
1.21      www      4157:         $mrole=$role;
                   4158:     }
1.620     albertel 4159:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4160:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4161:     if ($end) { $command.='_'.$end; }
1.21      www      4162:     if ($start) {
                   4163: 	if ($end) { 
1.81      www      4164:            $command.='_'.$start; 
1.21      www      4165:         } else {
1.81      www      4166:            $command.='_0_'.$start;
1.21      www      4167:         }
                   4168:     }
1.739     raeburn  4169:     my $origstart = $start;
                   4170:     my $origend = $end;
1.357     www      4171: # actually delete
                   4172:     if ($deleteflag) {
1.373     www      4173: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4174: # modify command to delete the role
1.620     albertel 4175:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4176:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4177: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4178: # set start and finish to negative values for userrolelog
                   4179:            $start=-1;
                   4180:            $end=-1;
                   4181:         }
                   4182:     }
                   4183: # send command
1.349     www      4184:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4185: # log new user role if status is ok
1.349     www      4186:     if ($answer eq 'ok') {
1.663     raeburn  4187: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4188: # for course roles, perform group memberships changes triggered by role change.
                   4189:         unless ($role =~ /^gr/) {
                   4190:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4191:                                              $origstart);
                   4192:         }
1.349     www      4193:     }
                   4194:     return $answer;
1.169     harris41 4195: }
                   4196: 
                   4197: # -------------------------------------------------- Modify user authentication
1.197     www      4198: # Overrides without validation
                   4199: 
1.169     harris41 4200: sub modifyuserauth {
                   4201:     my ($udom,$uname,$umode,$upass)=@_;
                   4202:     my $uhome=&homeserver($uname,$udom);
1.197     www      4203:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4204:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4205:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4206:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4207:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4208: 		     &escape($upass),$uhome);
1.620     albertel 4209:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4210:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4211:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4212:     &log($udom,,$uname,$uhome,
1.620     albertel 4213:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4214:                                      $env{'user.name'}.', '.$umode.
1.197     www      4215:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4216:     unless ($reply eq 'ok') {
1.197     www      4217:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4218: 	return 'error: '.$reply;
                   4219:     }   
1.170     harris41 4220:     return 'ok';
1.80      www      4221: }
                   4222: 
1.81      www      4223: # --------------------------------------------------------------- Modify a user
1.80      www      4224: 
1.81      www      4225: sub modifyuser {
1.206     matthew  4226:     my ($udom,    $uname, $uid,
                   4227:         $umode,   $upass, $first,
                   4228:         $middle,  $last,  $gene,
1.387     www      4229:         $forceid, $desiredhome, $email)=@_;
1.198     www      4230:     $udom=~s/\W//g;
                   4231:     $uname=~s/\W//g;
1.81      www      4232:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4233:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4234: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4235:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4236:                                      ' desiredhome not specified'). 
1.620     albertel 4237:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4238:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4239:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4240: # ----------------------------------------------------------------- Create User
1.406     albertel 4241:     if (($uhome eq 'no_host') && 
                   4242: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4243:         my $unhome='';
1.209     matthew  4244:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4245:             $unhome = $desiredhome;
1.620     albertel 4246: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4247: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4248:         } else { # load balancing routine for determining $unhome
1.80      www      4249:             my $tryserver;
1.81      www      4250:             my $loadm=10000000;
1.80      www      4251:             foreach $tryserver (keys %libserv) {
                   4252: 	       if ($hostdom{$tryserver} eq $udom) {
                   4253:                   my $answer=reply('load',$tryserver);
                   4254:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4255: 		      $loadm=$answer;
                   4256:                       $unhome=$tryserver;
                   4257:                   }
                   4258: 	       }
                   4259: 	    }
                   4260:         }
                   4261:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4262: 	    return 'error: unable to find a home server for '.$uname.
                   4263:                    ' in domain '.$udom;
1.80      www      4264:         }
                   4265:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4266:                          &escape($upass),$unhome);
                   4267: 	unless ($reply eq 'ok') {
                   4268:             return 'error: '.$reply;
                   4269:         }   
1.230     stredwic 4270:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4271:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4272: 	    return 'error: unable verify users home machine.';
1.80      www      4273:         }
1.209     matthew  4274:     }   # End of creation of new user
1.80      www      4275: # ---------------------------------------------------------------------- Add ID
                   4276:     if ($uid) {
                   4277:        $uid=~tr/A-Z/a-z/;
                   4278:        my %uidhash=&idrget($udom,$uname);
1.196     www      4279:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4280:          && (!$forceid)) {
1.80      www      4281: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4282: 	      return 'error: user id "'.$uid.'" does not match '.
                   4283:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4284:           }
                   4285:        } else {
                   4286: 	  &idput($udom,($uname => $uid));
                   4287:        }
                   4288:     }
                   4289: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4290:     my @tmp=&get('environment',
1.134     albertel 4291: 		   ['firstname','middlename','lastname','generation'],
                   4292: 		   $udom,$uname);
1.313     matthew  4293:     my %names;
                   4294:     if ($tmp[0] =~ m/^error:.*/) { 
                   4295:         %names=(); 
                   4296:     } else {
                   4297:         %names = @tmp;
                   4298:     }
1.388     www      4299: #
                   4300: # Make sure to not trash student environment if instructor does not bother
                   4301: # to supply name and email information
                   4302: #
                   4303:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4304:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4305:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4306:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4307:     if ($email) {
                   4308:        $email=~s/[^\w\@\.\-\,]//gs;
                   4309:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4310: 			   $names{'critnotification'} = $email;
                   4311: 			   $names{'permanentemail'} = $email; }
                   4312:     }
1.134     albertel 4313:     my $reply = &put('environment', \%names, $udom,$uname);
                   4314:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4315:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4316:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4317:              $umode.', '.$first.', '.$middle.', '.
                   4318: 	     $last.', '.$gene.' by '.
1.620     albertel 4319:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4320:     return 'ok';
1.80      www      4321: }
                   4322: 
1.81      www      4323: # -------------------------------------------------------------- Modify student
1.80      www      4324: 
1.81      www      4325: sub modifystudent {
                   4326:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4327:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4328:     if (!$cid) {
1.620     albertel 4329: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4330: 	    return 'not_in_class';
                   4331: 	}
1.80      www      4332:     }
                   4333: # --------------------------------------------------------------- Make the user
1.81      www      4334:     my $reply=&modifyuser
1.209     matthew  4335: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4336:          $desiredhome,$email);
1.80      www      4337:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4338:     # This will cause &modify_student_enrollment to get the uid from the
                   4339:     # students environment
                   4340:     $uid = undef if (!$forceid);
1.455     albertel 4341:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4342: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4343:     return $reply;
                   4344: }
                   4345: 
                   4346: sub modify_student_enrollment {
1.515     raeburn  4347:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4348:     my ($cdom,$cnum,$chome);
                   4349:     if (!$cid) {
1.620     albertel 4350: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4351: 	    return 'not_in_class';
                   4352: 	}
1.620     albertel 4353: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4354: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4355:     } else {
                   4356: 	($cdom,$cnum)=split(/_/,$cid);
                   4357:     }
1.620     albertel 4358:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4359:     if (!$chome) {
1.457     raeburn  4360: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4361:     }
1.455     albertel 4362:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4363:     # Make sure the user exists
1.81      www      4364:     my $uhome=&homeserver($uname,$udom);
                   4365:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4366: 	return 'error: no such user';
                   4367:     }
1.297     matthew  4368:     # Get student data if we were not given enough information
                   4369:     if (!defined($first)  || $first  eq '' || 
                   4370:         !defined($last)   || $last   eq '' || 
                   4371:         !defined($uid)    || $uid    eq '' || 
                   4372:         !defined($middle) || $middle eq '' || 
                   4373:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4374:         # They did not supply us with enough data to enroll the student, so
                   4375:         # we need to pick up more information.
1.297     matthew  4376:         my %tmp = &get('environment',
1.294     matthew  4377:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4378:                        ,$udom,$uname);
                   4379: 
1.455     albertel 4380:         #foreach (keys(%tmp)) {
                   4381:         #    &logthis("key $_ = ".$tmp{$_});
                   4382:         #}
1.294     matthew  4383:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4384:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4385:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4386:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4387:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4388:     }
1.556     albertel 4389:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4390:     my $reply=cput('classlist',
                   4391: 		   {"$uname:$udom" => 
1.515     raeburn  4392: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4393: 		   $cdom,$cnum);
1.81      www      4394:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4395: 	return 'error: '.$reply;
1.652     albertel 4396:     } else {
                   4397: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4398:     }
1.297     matthew  4399:     # Add student role to user
1.83      www      4400:     my $uurl='/'.$cid;
1.81      www      4401:     $uurl=~s/\_/\//g;
                   4402:     if ($usec) {
                   4403: 	$uurl.='/'.$usec;
                   4404:     }
                   4405:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4406: }
                   4407: 
1.556     albertel 4408: sub format_name {
                   4409:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4410:     my $name;
                   4411:     if ($first ne 'lastname') {
                   4412: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4413:     } else {
                   4414: 	if ($lastname=~/\S/) {
                   4415: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4416: 	    $name=~s/\s+,/,/;
                   4417: 	} else {
                   4418: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4419: 	}
                   4420:     }
                   4421:     $name=~s/^\s+//;
                   4422:     $name=~s/\s+$//;
                   4423:     $name=~s/\s+/ /g;
                   4424:     return $name;
                   4425: }
                   4426: 
1.84      www      4427: # ------------------------------------------------- Write to course preferences
                   4428: 
                   4429: sub writecoursepref {
                   4430:     my ($courseid,%prefs)=@_;
                   4431:     $courseid=~s/^\///;
                   4432:     $courseid=~s/\_/\//g;
                   4433:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4434:     my $chome=homeserver($cnum,$cdomain);
                   4435:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4436: 	return 'error: no such course';
                   4437:     }
                   4438:     my $cstring='';
1.191     harris41 4439:     foreach (keys %prefs) {
1.84      www      4440: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4441:     }
1.84      www      4442:     $cstring=~s/\&$//;
                   4443:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4444: }
                   4445: 
                   4446: # ---------------------------------------------------------- Make/modify course
                   4447: 
                   4448: sub createcourse {
1.741     raeburn  4449:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4450:         $course_owner,$crstype)=@_;
1.84      www      4451:     $url=&declutter($url);
                   4452:     my $cid='';
1.264     matthew  4453:     unless (&allowed('ccc',$udom)) {
1.84      www      4454:         return 'refused';
                   4455:     }
                   4456: # ------------------------------------------------------------------- Create ID
1.674     www      4457:    my $uname=int(1+rand(9)).
                   4458:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4459:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4460:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4461: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4462:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4463:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4464:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4465:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4466:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4467:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4468:            return 'error: unable to generate unique course-ID';
                   4469:        } 
                   4470:    }
1.264     matthew  4471: # ------------------------------------------------ Check supplied server name
1.620     albertel 4472:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4473:     if (! exists($libserv{$course_server})) {
                   4474:         return 'error:bad server name '.$course_server;
                   4475:     }
1.84      www      4476: # ------------------------------------------------------------- Make the course
                   4477:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4478:                       $course_server);
1.84      www      4479:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4480:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4481:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4482: 	return 'error: no such course';
                   4483:     }
1.271     www      4484: # ----------------------------------------------------------------- Course made
1.516     raeburn  4485: # log existence
                   4486:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4487:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4488:                   &escape($crstype),$uhome);
1.358     www      4489:     &flushcourselogs();
                   4490: # set toplevel url
1.271     www      4491:     my $topurl=$url;
                   4492:     unless ($nonstandard) {
                   4493: # ------------------------------------------ For standard courses, make top url
                   4494:         my $mapurl=&clutter($url);
1.278     www      4495:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4496:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4497: <map>
                   4498: <resource id="1" type="start"></resource>
                   4499: <resource id="2" src="$mapurl"></resource>
                   4500: <resource id="3" type="finish"></resource>
                   4501: <link index="1" from="1" to="2"></link>
                   4502: <link index="2" from="2" to="3"></link>
                   4503: </map>
                   4504: ENDINITMAP
                   4505:         $topurl=&declutter(
1.638     albertel 4506:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4507:                           );
                   4508:     }
                   4509: # ----------------------------------------------------------- Write preferences
1.84      www      4510:     &writecoursepref($udom.'_'.$uname,
                   4511:                      ('description' => $description,
1.271     www      4512:                       'url'         => $topurl));
1.84      www      4513:     return '/'.$udom.'/'.$uname;
                   4514: }
                   4515: 
1.21      www      4516: # ---------------------------------------------------------- Assign Custom Role
                   4517: 
                   4518: sub assigncustomrole {
1.357     www      4519:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4520:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4521:                        $end,$start,$deleteflag);
1.21      www      4522: }
                   4523: 
                   4524: # ----------------------------------------------------------------- Revoke Role
                   4525: 
                   4526: sub revokerole {
1.357     www      4527:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4528:     my $now=time;
1.357     www      4529:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4530: }
                   4531: 
                   4532: # ---------------------------------------------------------- Revoke Custom Role
                   4533: 
                   4534: sub revokecustomrole {
1.357     www      4535:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4536:     my $now=time;
1.357     www      4537:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4538:            $deleteflag);
1.17      www      4539: }
                   4540: 
1.533     banghart 4541: # ------------------------------------------------------------ Disk usage
1.535     albertel 4542: sub diskusage {
1.533     banghart 4543:     my ($udom,$uname,$directoryRoot)=@_;
                   4544:     $directoryRoot =~ s/\/$//;
1.535     albertel 4545:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4546:     return $listing;
1.512     banghart 4547: }
                   4548: 
1.566     banghart 4549: sub is_locked {
                   4550:     my ($file_name, $domain, $user) = @_;
                   4551:     my @check;
                   4552:     my $is_locked;
                   4553:     push @check, $file_name;
1.613     albertel 4554:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4555: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4556:     my ($tmp)=keys(%locked);
                   4557:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4558:     
1.566     banghart 4559:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4560:         $is_locked = 'false';
                   4561:         foreach my $entry (@{$locked{$file_name}}) {
                   4562:            if (ref($entry) eq 'ARRAY') { 
1.746   ! raeburn  4563:                $is_locked = 'true';
        !          4564:                last;
1.745     raeburn  4565:            }
                   4566:        }
1.566     banghart 4567:     } else {
                   4568:         $is_locked = 'false';
                   4569:     }
                   4570: }
                   4571: 
1.559     banghart 4572: # ------------------------------------------------------------- Mark as Read Only
                   4573: 
                   4574: sub mark_as_readonly {
                   4575:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4576:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4577:     my ($tmp)=keys(%current_permissions);
                   4578:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4579:     foreach my $file (@{$files}) {
1.561     banghart 4580:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4581:     }
1.613     albertel 4582:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4583:     return;
                   4584: }
                   4585: 
1.572     banghart 4586: # ------------------------------------------------------------Save Selected Files
                   4587: 
                   4588: sub save_selected_files {
                   4589:     my ($user, $path, @files) = @_;
                   4590:     my $filename = $user."savedfiles";
1.573     banghart 4591:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4592:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4593:     foreach my $file (@files) {
1.620     albertel 4594:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4595:     }
                   4596:     foreach my $file (@other_files) {
1.574     banghart 4597:         print (OUT $file."\n");
1.572     banghart 4598:     }
1.574     banghart 4599:     close (OUT);
1.572     banghart 4600:     return 'ok';
                   4601: }
                   4602: 
1.574     banghart 4603: sub clear_selected_files {
                   4604:     my ($user) = @_;
                   4605:     my $filename = $user."savedfiles";
                   4606:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4607:     print (OUT undef);
                   4608:     close (OUT);
                   4609:     return ("ok");    
                   4610: }
                   4611: 
1.572     banghart 4612: sub files_in_path {
                   4613:     my ($user, $path) = @_;
                   4614:     my $filename = $user."savedfiles";
                   4615:     my %return_files;
1.574     banghart 4616:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4617:     while (my $line_in = <IN>) {
1.574     banghart 4618:         chomp ($line_in);
                   4619:         my @paths_and_file = split (m!/!, $line_in);
                   4620:         my $file_part = pop (@paths_and_file);
                   4621:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4622:         $path_part.='/';
                   4623:         my $path_and_file = $path_part.$file_part;
                   4624:         if ($path_part eq $path) {
                   4625:             $return_files{$file_part}= 'selected';
                   4626:         }
                   4627:     }
1.574     banghart 4628:     close (IN);
                   4629:     return (\%return_files);
1.572     banghart 4630: }
                   4631: 
                   4632: # called in portfolio select mode, to show files selected NOT in current directory
                   4633: sub files_not_in_path {
                   4634:     my ($user, $path) = @_;
                   4635:     my $filename = $user."savedfiles";
                   4636:     my @return_files;
                   4637:     my $path_part;
1.574     banghart 4638:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4639:     while (<IN>) {
                   4640:         #ok, I know it's clunky, but I want it to work
                   4641:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4642:         my $file_part = pop (@paths_and_file);
                   4643:         chomp ($file_part);
                   4644:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4645:         $path_part .= '/';
                   4646:         my $path_and_file = $path_part.$file_part;
                   4647:         if ($path_part ne $path) {
1.574     banghart 4648:             push (@return_files, ($path_and_file));
1.572     banghart 4649:         }
                   4650:     }
1.574     banghart 4651:     close (OUT);
                   4652:     return (@return_files);
1.572     banghart 4653: }
                   4654: 
1.745     raeburn  4655: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4656: 
1.745     raeburn  4657: sub get_portfile_permissions {
1.746   ! raeburn  4658:     # returns a reference to a hash containing contents of file_permissions.db 
1.745     raeburn  4659:     my ($domain,$user) = @_;
1.613     albertel 4660:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4661:     my ($tmp)=keys(%current_permissions);
                   4662:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4663:     return \%current_permissions;
                   4664: }
                   4665: 
                   4666: #---------------------------------------------Get portfolio file access controls
                   4667: 
                   4668: sub get_access_controls  {
1.746   ! raeburn  4669:     # returns a hash containing access control information retrieved from
        !          4670:     # file_permissions.db. The hash contains key=value pairs where key is
        !          4671:     # the control type, end date and start date, in the form type_end_start
        !          4672:     # and value is a string containing access control settings (in XML),
        !          4673:     #
        !          4674:     # Internally access_controls are stored in file_permissions.db in an
        !          4675:     # array of arrays and a hash, where arrays are locks set when a portfolio   
        !          4676:     # file has been uploaded to an essayresponse problem in a course, and
        !          4677:     # the hash contains other data. Two keys are currently defined in the hash:  
        !          4678:     # access and accesscount. The value for accesscount is a scalar - equal to 
        !          4679:     # the next number to use as the first part of an access control key
        !          4680:     # when defining a new control. The value for access is an anonymous hash
        !          4681:     # where keys are access controls and values are settings.
        !          4682:     #    
1.745     raeburn  4683:     my ($current_permissions,$group,$file) = @_;
                   4684:     my @access_checks = ();
                   4685:     my %access; 
                   4686:     if (defined($file)) {
                   4687:         @access_checks = ($file);
                   4688:     } else {
                   4689:         @access_checks = keys(%{$current_permissions});
                   4690:     }
                   4691:     foreach my $file_name (@access_checks) {
                   4692:         my $value = $$current_permissions{$file_name};
                   4693:         if (defined($group)) {
                   4694:             if ($file_name !~ m-^\Q$group\E/-) {
                   4695:                 next;
                   4696:             }
                   4697:         }
                   4698:         if (ref($value) eq "ARRAY") {
                   4699:             foreach my $stored_what (@{$value}) {
1.746   ! raeburn  4700:                 if (ref($stored_what) eq 'HASH') {
        !          4701:                     $access{$file_name} = $$stored_what{'access'};
1.745     raeburn  4702:                 }
                   4703:             }
                   4704:         }
                   4705:     }
                   4706:     return %access;
                   4707: }
                   4708: 
                   4709: #------------------------------------------------------Get Marked as Read Only
                   4710: 
                   4711: sub get_marked_as_readonly {
                   4712:     my ($domain,$user,$what,$group) = @_;
                   4713:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 4714:     my @readonly_files;
1.629     banghart 4715:     my $cmp1=$what;
                   4716:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  4717:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   4718:         if (defined($group)) {
                   4719:             if ($file_name !~ m-^\Q$group\E/-) {
                   4720:                 next;
                   4721:             }
                   4722:         }
1.561     banghart 4723:         if (ref($value) eq "ARRAY"){
                   4724:             foreach my $stored_what (@{$value}) {
1.629     banghart 4725:                 my $cmp2=$stored_what;
1.746   ! raeburn  4726:                 if (ref($stored_what eq 'HASH')) {
        !          4727:                     next;
        !          4728:                 } elsif (ref($stored_what eq 'ARRAY')) {
        !          4729:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  4730:                 }
1.629     banghart 4731:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4732:                     push(@readonly_files, $file_name);
1.745     raeburn  4733:                     last;
1.563     banghart 4734:                 } elsif (!defined($what)) {
                   4735:                     push(@readonly_files, $file_name);
1.745     raeburn  4736:                     last;
1.561     banghart 4737:                 }
                   4738:             }
1.745     raeburn  4739:         }
1.561     banghart 4740:     }
                   4741:     return @readonly_files;
                   4742: }
1.577     banghart 4743: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4744: 
1.577     banghart 4745: sub get_marked_as_readonly_hash {
1.745     raeburn  4746:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 4747:     my %readonly_files;
1.745     raeburn  4748:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   4749:         if (defined($group)) {
                   4750:             if ($file_name !~ m-^\Q$group\E/-) {
                   4751:                 next;
                   4752:             }
                   4753:         }
1.577     banghart 4754:         if (ref($value) eq "ARRAY"){
                   4755:             foreach my $stored_what (@{$value}) {
1.745     raeburn  4756:                 if (ref($stored_what) eq 'ARRAY') {
1.746   ! raeburn  4757:                     if ($stored_what eq $what) {
        !          4758:                         $readonly_files{$file_name} = 'locked';
        !          4759:                     } elsif (!defined($what)) {
        !          4760:                         $readonly_files{$file_name} = 'locked';
1.745     raeburn  4761:                     }
                   4762:                 }
1.577     banghart 4763:             }
                   4764:         } 
                   4765:     }
                   4766:     return %readonly_files;
                   4767: }
1.559     banghart 4768: # ------------------------------------------------------------ Unmark as Read Only
                   4769: 
                   4770: sub unmark_as_readonly {
1.629     banghart 4771:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4772:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  4773:     my ($domain,$user,$what,$file_name,$group) = @_;
1.634     albertel 4774:     my $symb_crs = $what;
                   4775:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  4776:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 4777:     my ($tmp)=keys(%current_permissions);
                   4778:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4779:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 4780:     foreach my $file (@readonly_files) {
                   4781: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4782: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4783:         my @new_locks;
                   4784:         my @del_keys;
                   4785:         if (ref($current_locks) eq "ARRAY"){
                   4786:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4787:                 my $compare=$locker;
1.746   ! raeburn  4788:                 if (!ref($locker) eq 'ARRAY') {
        !          4789:                     push(@new_locks,$locker);
        !          4790:                 } else {   
1.745     raeburn  4791:                     $compare=join('',@{$locker});
1.746   ! raeburn  4792:                     if ($compare ne $symb_crs) {
        !          4793:                         push(@new_locks, $locker);
        !          4794:                     }
1.563     banghart 4795:                 }
                   4796:             }
1.650     albertel 4797:             if (scalar(@new_locks) > 0) {
1.563     banghart 4798:                 $current_permissions{$file} = \@new_locks;
                   4799:             } else {
                   4800:                 push(@del_keys, $file);
1.613     albertel 4801:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4802:                 delete($current_permissions{$file});
1.563     banghart 4803:             }
                   4804:         }
1.561     banghart 4805:     }
1.613     albertel 4806:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4807:     return;
                   4808: }
1.512     banghart 4809: 
1.17      www      4810: # ------------------------------------------------------------ Directory lister
                   4811: 
                   4812: sub dirlist {
1.253     stredwic 4813:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4814: 
1.18      www      4815:     $uri=~s/^\///;
                   4816:     $uri=~s/\/$//;
1.253     stredwic 4817:     my ($udom, $uname);
                   4818:     (undef,$udom,$uname)=split(/\//,$uri);
                   4819:     if(defined($userdomain)) {
                   4820:         $udom = $userdomain;
                   4821:     }
                   4822:     if(defined($username)) {
                   4823:         $uname = $username;
                   4824:     }
                   4825: 
                   4826:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4827:     if(defined($alternateDirectoryRoot)) {
                   4828:         $dirRoot = $alternateDirectoryRoot;
                   4829:         $dirRoot =~ s/\/$//;
                   4830:     }
                   4831: 
                   4832:     if($udom) {
                   4833:         if($uname) {
1.605     matthew  4834:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4835:                               homeserver($uname,$udom));
1.605     matthew  4836:             my @listing_results;
                   4837:             if ($listing eq 'unknown_cmd') {
                   4838:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4839:                                homeserver($uname,$udom));
                   4840:                 @listing_results = split(/:/,$listing);
                   4841:             } else {
                   4842:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4843:             }
                   4844:             return @listing_results;
1.253     stredwic 4845:         } elsif(!defined($alternateDirectoryRoot)) {
                   4846:             my $tryserver;
                   4847:             my %allusers=();
                   4848:             foreach $tryserver (keys %libserv) {
                   4849:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4850:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4851:                                       $udom, $tryserver);
1.605     matthew  4852:                     my @listing_results;
                   4853:                     if ($listing eq 'unknown_cmd') {
                   4854:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4855:                                        $udom, $tryserver);
                   4856:                         @listing_results = split(/:/,$listing);
                   4857:                     } else {
                   4858:                         @listing_results =
                   4859:                             map { &unescape($_); } split(/:/,$listing);
                   4860:                     }
                   4861:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4862:                         $listing_results[0] ne 'empty'       &&
                   4863:                         $listing_results[0] ne 'con_lost') {
                   4864:                         foreach (@listing_results) {
1.253     stredwic 4865:                             my ($entry,@stat)=split(/&/,$_);
                   4866:                             $allusers{$entry}=1;
                   4867:                         }
                   4868:                     }
1.191     harris41 4869:                 }
1.253     stredwic 4870:             }
                   4871:             my $alluserstr='';
                   4872:             foreach (sort keys %allusers) {
                   4873:                 $alluserstr.=$_.'&user:';
                   4874:             }
                   4875:             $alluserstr=~s/:$//;
                   4876:             return split(/:/,$alluserstr);
                   4877:         } else {
                   4878:             my @emptyResults = ();
                   4879:             push(@emptyResults, 'missing user name');
                   4880:             return split(':',@emptyResults);
                   4881:         }
                   4882:     } elsif(!defined($alternateDirectoryRoot)) {
                   4883:         my $tryserver;
                   4884:         my %alldom=();
                   4885:         foreach $tryserver (keys %libserv) {
                   4886:             $alldom{$hostdom{$tryserver}}=1;
                   4887:         }
                   4888:         my $alldomstr='';
                   4889:         foreach (sort keys %alldom) {
1.397     albertel 4890:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4891:         }
                   4892:         $alldomstr=~s/:$//;
                   4893:         return split(/:/,$alldomstr);       
                   4894:     } else {
                   4895:         my @emptyResults = ();
                   4896:         push(@emptyResults, 'missing domain');
                   4897:         return split(':',@emptyResults);
1.275     stredwic 4898:     }
                   4899: }
                   4900: 
                   4901: # --------------------------------------------- GetFileTimestamp
                   4902: # This function utilizes dirlist and returns the date stamp for
                   4903: # when it was last modified.  It will also return an error of -1
                   4904: # if an error occurs
                   4905: 
1.410     matthew  4906: ##
                   4907: ## FIXME: This subroutine assumes its caller knows something about the
                   4908: ## directory structure of the home server for the student ($root).
                   4909: ## Not a good assumption to make.  Since this is for looking up files
                   4910: ## in user directories, the full path should be constructed by lond, not
                   4911: ## whatever machine we request data from.
                   4912: ##
1.275     stredwic 4913: sub GetFileTimestamp {
                   4914:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4915:     $studentDomain=~s/\W//g;
                   4916:     $studentName=~s/\W//g;
                   4917:     my $subdir=$studentName.'__';
                   4918:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4919:     my $proname="$studentDomain/$subdir/$studentName";
                   4920:     $proname .= '/'.$filename;
1.375     matthew  4921:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4922:                                               $studentName, $root);
1.275     stredwic 4923:     my @stats = split('&', $fileStat);
                   4924:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4925:         # @stats contains first the filename, then the stat output
                   4926:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4927:     } else {
                   4928:         return -1;
1.253     stredwic 4929:     }
1.26      www      4930: }
                   4931: 
1.712     albertel 4932: sub stat_file {
                   4933:     my ($uri) = @_;
1.722     albertel 4934:     $uri = &clutter($uri);
                   4935: 
                   4936:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 4937:     if ($uri =~ m-^/adm/-) {
                   4938: 	$uri=~s-^/adm/wrapper/-/-;
                   4939: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 4940:     }
1.712     albertel 4941:     my ($udom,$uname,$file,$dir);
                   4942:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   4943: 	($udom,$uname,$file) =
                   4944: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   4945: 	$file = 'userfiles/'.$file;
1.740     www      4946: 	$dir = &propath($udom,$uname);
1.712     albertel 4947:     }
                   4948:     if ($uri =~ m-^/res/-) {
                   4949: 	($udom,$uname) = 
                   4950: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   4951: 	$file = $uri;
                   4952:     }
                   4953: 
                   4954:     if (!$udom || !$uname || !$file) {
                   4955: 	# unable to handle the uri
                   4956: 	return ();
                   4957:     }
                   4958: 
                   4959:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   4960:     my @stats = split('&', $result);
1.721     banghart 4961:     
1.712     albertel 4962:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   4963: 	shift(@stats); #filename is first
                   4964: 	return @stats;
                   4965:     }
                   4966:     return ();
                   4967: }
                   4968: 
1.26      www      4969: # -------------------------------------------------------- Value of a Condition
                   4970: 
1.713     albertel 4971: # gets the value of a specific preevaluated condition
                   4972: #    stored in the string  $env{user.state.<cid>}
                   4973: # or looks up a condition reference in the bighash and if if hasn't
                   4974: # already been evaluated recurses into docondval to get the value of
                   4975: # the condition, then memoizing it to 
                   4976: #   $env{user.state.<cid>.<condition>}
1.40      www      4977: sub directcondval {
                   4978:     my $number=shift;
1.620     albertel 4979:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4980: 	&Apache::lonuserstate::evalstate();
                   4981:     }
1.713     albertel 4982:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   4983: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   4984:     } elsif ($number =~ /^_/) {
                   4985: 	my $sub_condition;
                   4986: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   4987: 		&GDBM_READER(),0640)) {
                   4988: 	    $sub_condition=$bighash{'conditions'.$number};
                   4989: 	    untie(%bighash);
                   4990: 	}
                   4991: 	my $value = &docondval($sub_condition);
                   4992: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   4993: 	return $value;
                   4994:     }
1.620     albertel 4995:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4996:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4997:     } else {
                   4998:        return 2;
                   4999:     }
                   5000: }
                   5001: 
1.713     albertel 5002: # get the collection of conditions for this resource
1.26      www      5003: sub condval {
                   5004:     my $condidx=shift;
1.54      www      5005:     my $allpathcond='';
1.713     albertel 5006:     foreach my $cond (split(/\|/,$condidx)) {
                   5007: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5008: 	    $allpathcond.=
                   5009: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5010: 	}
1.191     harris41 5011:     }
1.54      www      5012:     $allpathcond=~s/\|$//;
1.713     albertel 5013:     return &docondval($allpathcond);
                   5014: }
                   5015: 
                   5016: #evaluates an expression of conditions
                   5017: sub docondval {
                   5018:     my ($allpathcond) = @_;
                   5019:     my $result=0;
                   5020:     if ($env{'request.course.id'}
                   5021: 	&& defined($allpathcond)) {
                   5022: 	my $operand='|';
                   5023: 	my @stack;
                   5024: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5025: 	    if ($chunk eq '(') {
                   5026: 		push @stack,($operand,$result);
                   5027: 	    } elsif ($chunk eq ')') {
                   5028: 		my $before=pop @stack;
                   5029: 		if (pop @stack eq '&') {
                   5030: 		    $result=$result>$before?$before:$result;
                   5031: 		} else {
                   5032: 		    $result=$result>$before?$result:$before;
                   5033: 		}
                   5034: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5035: 		$operand=$chunk;
                   5036: 	    } else {
                   5037: 		my $new=directcondval($chunk);
                   5038: 		if ($operand eq '&') {
                   5039: 		    $result=$result>$new?$new:$result;
                   5040: 		} else {
                   5041: 		    $result=$result>$new?$result:$new;
                   5042: 		}
                   5043: 	    }
                   5044: 	}
1.26      www      5045:     }
                   5046:     return $result;
1.421     albertel 5047: }
                   5048: 
                   5049: # ---------------------------------------------------- Devalidate courseresdata
                   5050: 
                   5051: sub devalidatecourseresdata {
                   5052:     my ($coursenum,$coursedomain)=@_;
                   5053:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5054:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5055: }
                   5056: 
1.200     www      5057: # --------------------------------------------------- Course Resourcedata Query
                   5058: 
1.624     albertel 5059: sub get_courseresdata {
                   5060:     my ($coursenum,$coursedomain)=@_;
1.200     www      5061:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5062:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5063:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5064:     my %dumpreply;
1.417     albertel 5065:     unless (defined($cached)) {
1.624     albertel 5066: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5067: 	$result=\%dumpreply;
1.251     albertel 5068: 	my ($tmp) = keys(%dumpreply);
                   5069: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5070: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5071: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5072: 	    return $tmp;
1.416     albertel 5073: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5074: 	    $result=undef;
1.599     albertel 5075: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5076: 	}
                   5077:     }
1.624     albertel 5078:     return $result;
                   5079: }
                   5080: 
1.633     albertel 5081: sub devalidateuserresdata {
                   5082:     my ($uname,$udom)=@_;
                   5083:     my $hashid="$udom:$uname";
                   5084:     &devalidate_cache_new('userres',$hashid);
                   5085: }
                   5086: 
1.624     albertel 5087: sub get_userresdata {
                   5088:     my ($uname,$udom)=@_;
                   5089:     #most student don\'t have any data set, check if there is some data
                   5090:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5091: 
                   5092:     my $hashid="$udom:$uname";
                   5093:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5094:     if (!defined($cached)) {
                   5095: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5096: 	$result=\%resourcedata;
                   5097: 	&do_cache_new('userres',$hashid,$result,600);
                   5098:     }
                   5099:     my ($tmp)=keys(%$result);
                   5100:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5101: 	return $result;
                   5102:     }
                   5103:     #error 2 occurs when the .db doesn't exist
                   5104:     if ($tmp!~/error: 2 /) {
1.672     albertel 5105: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5106: 		 " Trying to get resource data for ".
                   5107: 		 $uname." at ".$udom.": ".
                   5108: 		 $tmp."</font>");
                   5109:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5110: 	#&EXT_cache_set($udom,$uname);
                   5111: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5112: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5113:     }
                   5114:     return $tmp;
                   5115: }
                   5116: 
                   5117: sub resdata {
                   5118:     my ($name,$domain,$type,@which)=@_;
                   5119:     my $result;
                   5120:     if ($type eq 'course') {
                   5121: 	$result=&get_courseresdata($name,$domain);
                   5122:     } elsif ($type eq 'user') {
                   5123: 	$result=&get_userresdata($name,$domain);
                   5124:     }
                   5125:     if (!ref($result)) { return $result; }    
1.251     albertel 5126:     foreach my $item (@which) {
1.417     albertel 5127: 	if (defined($result->{$item})) {
                   5128: 	    return $result->{$item};
1.251     albertel 5129: 	}
1.250     albertel 5130:     }
1.291     albertel 5131:     return undef;
1.200     www      5132: }
                   5133: 
1.379     matthew  5134: #
                   5135: # EXT resource caching routines
                   5136: #
                   5137: 
                   5138: sub clear_EXT_cache_status {
1.383     albertel 5139:     &delenv('cache.EXT.');
1.379     matthew  5140: }
                   5141: 
                   5142: sub EXT_cache_status {
                   5143:     my ($target_domain,$target_user) = @_;
1.383     albertel 5144:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5145:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5146:         # We know already the user has no data
                   5147:         return 1;
                   5148:     } else {
                   5149:         return 0;
                   5150:     }
                   5151: }
                   5152: 
                   5153: sub EXT_cache_set {
                   5154:     my ($target_domain,$target_user) = @_;
1.383     albertel 5155:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5156:     #&appenv($cachename => time);
1.379     matthew  5157: }
                   5158: 
1.28      www      5159: # --------------------------------------------------------- Value of a Variable
1.58      www      5160: sub EXT {
1.715     albertel 5161: 
1.395     albertel 5162:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5163:     unless ($varname) { return ''; }
1.218     albertel 5164:     #get real user name/domain, courseid and symb
                   5165:     my $courseid;
1.359     albertel 5166:     my $publicuser;
1.427     www      5167:     if ($symbparm) {
                   5168: 	$symbparm=&get_symb_from_alias($symbparm);
                   5169:     }
1.218     albertel 5170:     if (!($uname && $udom)) {
1.360     albertel 5171:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5172: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5173:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5174:     } else {
1.620     albertel 5175: 	$courseid=$env{'request.course.id'};
1.218     albertel 5176:     }
1.48      www      5177:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5178:     my $rest;
1.320     albertel 5179:     if (defined($therest[0])) {
1.48      www      5180:        $rest=join('.',@therest);
                   5181:     } else {
                   5182:        $rest='';
                   5183:     }
1.320     albertel 5184: 
1.57      www      5185:     my $qualifierrest=$qualifier;
                   5186:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5187:     my $spacequalifierrest=$space;
                   5188:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5189:     if ($realm eq 'user') {
1.48      www      5190: # --------------------------------------------------------------- user.resource
                   5191: 	if ($space eq 'resource') {
1.651     albertel 5192: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5193: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5194: 		 &&
1.744     albertel 5195: 		 ($symbparm eq &symbread()) ) {	
                   5196: 		# if we are in the middle of processing the resource the
                   5197: 		# get the value we are planning on committing
                   5198:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5199:                     return $Apache::lonhomework::results{$qualifierrest};
                   5200:                 } else {
                   5201:                     return $Apache::lonhomework::history{$qualifierrest};
                   5202:                 }
1.335     albertel 5203: 	    } else {
1.359     albertel 5204: 		my %restored;
1.620     albertel 5205: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5206: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5207: 		} else {
                   5208: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5209: 		}
1.335     albertel 5210: 		return $restored{$qualifierrest};
                   5211: 	    }
1.48      www      5212: # ----------------------------------------------------------------- user.access
                   5213:         } elsif ($space eq 'access') {
1.218     albertel 5214: 	    # FIXME - not supporting calls for a specific user
1.48      www      5215:             return &allowed($qualifier,$rest);
                   5216: # ------------------------------------------ user.preferences, user.environment
                   5217:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5218: 	    if (($uname eq $env{'user.name'}) &&
                   5219: 		($udom eq $env{'user.domain'})) {
                   5220: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5221: 	    } else {
1.359     albertel 5222: 		my %returnhash;
                   5223: 		if (!$publicuser) {
                   5224: 		    %returnhash=&userenvironment($udom,$uname,
                   5225: 						 $qualifierrest);
                   5226: 		}
1.218     albertel 5227: 		return $returnhash{$qualifierrest};
                   5228: 	    }
1.48      www      5229: # ----------------------------------------------------------------- user.course
                   5230:         } elsif ($space eq 'course') {
1.218     albertel 5231: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5232:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5233: # ------------------------------------------------------------------- user.role
                   5234:         } elsif ($space eq 'role') {
1.218     albertel 5235: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5236:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5237:             if ($qualifier eq 'value') {
                   5238: 		return $role;
                   5239:             } elsif ($qualifier eq 'extent') {
                   5240:                 return $where;
                   5241:             }
                   5242: # ----------------------------------------------------------------- user.domain
                   5243:         } elsif ($space eq 'domain') {
1.218     albertel 5244:             return $udom;
1.48      www      5245: # ------------------------------------------------------------------- user.name
                   5246:         } elsif ($space eq 'name') {
1.218     albertel 5247:             return $uname;
1.48      www      5248: # ---------------------------------------------------- Any other user namespace
1.29      www      5249:         } else {
1.359     albertel 5250: 	    my %reply;
                   5251: 	    if (!$publicuser) {
                   5252: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5253: 	    }
                   5254: 	    return $reply{$qualifierrest};
1.48      www      5255:         }
1.236     www      5256:     } elsif ($realm eq 'query') {
                   5257: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5258:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5259: 						[$spacequalifierrest]);
1.620     albertel 5260: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5261:    } elsif ($realm eq 'request') {
1.48      www      5262: # ------------------------------------------------------------- request.browser
                   5263:         if ($space eq 'browser') {
1.430     www      5264: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5265: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5266: 		    return 1;
                   5267: 		} else {
                   5268: 		    return 0;
                   5269: 		}
                   5270: 	    } else {
1.620     albertel 5271: 		return $env{'browser.'.$qualifier};
1.430     www      5272: 	    }
1.57      www      5273: # ------------------------------------------------------------ request.filename
                   5274:         } else {
1.620     albertel 5275:             return $env{'request.'.$spacequalifierrest};
1.29      www      5276:         }
1.28      www      5277:     } elsif ($realm eq 'course') {
1.48      www      5278: # ---------------------------------------------------------- course.description
1.620     albertel 5279:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5280:     } elsif ($realm eq 'resource') {
1.165     www      5281: 
1.620     albertel 5282: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5283: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5284: 	}
1.693     albertel 5285: 
                   5286: 	if ($space eq 'title') {
                   5287: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5288: 	    return &gettitle($symbparm);
                   5289: 	}
                   5290: 	
                   5291: 	if ($space eq 'map') {
                   5292: 	    my ($map) = &decode_symb($symbparm);
                   5293: 	    return &symbread($map);
                   5294: 	}
                   5295: 
                   5296: 	my ($section, $group, @groups);
1.593     albertel 5297: 	my ($courselevelm,$courselevel);
1.539     albertel 5298: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5299: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5300: 
1.218     albertel 5301: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5302: 
1.60      www      5303: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5304: 	    my $symbp=$symbparm;
1.735     albertel 5305: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5306: 
                   5307: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5308: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5309: 
1.620     albertel 5310: 	    if (($env{'user.name'} eq $uname) &&
                   5311: 		($env{'user.domain'} eq $udom)) {
                   5312: 		$section=$env{'request.course.sec'};
1.733     raeburn  5313:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5314:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5315: 	    } else {
1.539     albertel 5316: 		if (! defined($usection)) {
1.551     albertel 5317: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5318: 		} else {
                   5319: 		    $section = $usection;
                   5320: 		}
1.733     raeburn  5321:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5322: 	    }
                   5323: 
                   5324: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5325: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5326: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5327: 
1.593     albertel 5328: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5329: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5330: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5331: 
1.60      www      5332: # ----------------------------------------------------------- first, check user
1.624     albertel 5333: 
                   5334: 	    my $userreply=&resdata($uname,$udom,'user',
                   5335: 				       ($courselevelr,$courselevelm,
                   5336: 					$courselevel));
                   5337: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5338: 
1.594     albertel 5339: # ------------------------------------------------ second, check some of course
1.684     raeburn  5340:             my $coursereply;
1.691     raeburn  5341:             if (@groups > 0) {
                   5342:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5343:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5344:                 if (defined($coursereply)) { return $coursereply; }
                   5345:             }
1.96      www      5346: 
1.684     raeburn  5347: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5348: 				     $env{'course.'.$courseid.'.domain'},
                   5349: 				     'course',
                   5350: 				     ($seclevelr,$seclevelm,$seclevel,
                   5351: 				      $courselevelr));
1.287     albertel 5352: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5353: 
1.60      www      5354: # ------------------------------------------------------ third, check map parms
1.218     albertel 5355: 	    my %parmhash=();
                   5356: 	    my $thisparm='';
                   5357: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5358: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5359: 		    &GDBM_READER(),0640)) {
1.218     albertel 5360: 		$thisparm=$parmhash{$symbparm};
                   5361: 		untie(%parmhash);
                   5362: 	    }
                   5363: 	    if ($thisparm) { return $thisparm; }
                   5364: 	}
1.594     albertel 5365: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5366: 
1.218     albertel 5367: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5368: 	my $filename;
                   5369: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5370: 	if ($symbparm) {
1.409     www      5371: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5372: 	} else {
1.620     albertel 5373: 	    $filename=$env{'request.filename'};
1.282     albertel 5374: 	}
                   5375: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5376: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5377: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5378: 	if (defined($metadata)) { return $metadata; }
1.142     www      5379: 
1.594     albertel 5380: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5381: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5382: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5383: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5384: 				     $env{'course.'.$courseid.'.domain'},
                   5385: 				     'course',
                   5386: 				     ($courselevelm,$courselevel));
1.593     albertel 5387: 	    if (defined($coursereply)) { return $coursereply; }
                   5388: 	}
1.145     www      5389: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5390: 	unless ($space eq '0') {
1.336     albertel 5391: 	    my @parts=split(/_/,$space);
                   5392: 	    my $id=pop(@parts);
                   5393: 	    my $part=join('_',@parts);
                   5394: 	    if ($part eq '') { $part='0'; }
                   5395: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5396: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5397: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5398: 	}
1.395     albertel 5399: 	if ($recurse) { return undef; }
                   5400: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5401: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5402: 
1.48      www      5403: # ---------------------------------------------------- Any other user namespace
                   5404:     } elsif ($realm eq 'environment') {
                   5405: # ----------------------------------------------------------------- environment
1.620     albertel 5406: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5407: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5408: 	} else {
                   5409: 	    my %returnhash=&userenvironment($udom,$uname,
                   5410: 					    $spacequalifierrest);
                   5411: 	    return $returnhash{$spacequalifierrest};
                   5412: 	}
1.28      www      5413:     } elsif ($realm eq 'system') {
1.48      www      5414: # ----------------------------------------------------------------- system.time
                   5415: 	if ($space eq 'time') {
                   5416: 	    return time;
                   5417:         }
1.696     albertel 5418:     } elsif ($realm eq 'server') {
                   5419: # ----------------------------------------------------------------- system.time
                   5420: 	if ($space eq 'name') {
                   5421: 	    return $ENV{'SERVER_NAME'};
                   5422:         }
1.28      www      5423:     }
1.48      www      5424:     return '';
1.61      www      5425: }
                   5426: 
1.691     raeburn  5427: sub check_group_parms {
                   5428:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5429:     my @groupitems = ();
                   5430:     my $resultitem;
                   5431:     my @levels = ($symbparm,$mapparm,$what);
                   5432:     foreach my $group (@{$groups}) {
                   5433:         foreach my $level (@levels) {
                   5434:              my $item = $courseid.'.['.$group.'].'.$level;
                   5435:              push(@groupitems,$item);
                   5436:         }
                   5437:     }
                   5438:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5439:                             $env{'course.'.$courseid.'.domain'},
                   5440:                                      'course',@groupitems);
                   5441:     return $coursereply;
                   5442: }
                   5443: 
                   5444: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5445:     my ($courseid,@groups) = @_;
                   5446:     @groups = sort(@groups);
1.691     raeburn  5447:     return @groups;
                   5448: }
                   5449: 
1.395     albertel 5450: sub packages_tab_default {
                   5451:     my ($uri,$varname)=@_;
                   5452:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5453: 
                   5454:     my (@extension,@specifics,$do_default);
                   5455:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5456: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5457: 	if ($pack_type eq 'default') {
                   5458: 	    $do_default=1;
                   5459: 	} elsif ($pack_type eq 'extension') {
                   5460: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5461: 	} else {
                   5462: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5463: 	}
                   5464:     }
                   5465:     # first look for a package that matches the requested part id
                   5466:     foreach my $package (@specifics) {
                   5467: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5468: 	next if ($pack_part ne $part);
                   5469: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5470: 	    return $packagetab{"$pack_type&$name&default"};
                   5471: 	}
                   5472:     }
                   5473:     # look for any possible matching non extension_ package
                   5474:     foreach my $package (@specifics) {
                   5475: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5476: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5477: 	    return $packagetab{"$pack_type&$name&default"};
                   5478: 	}
1.585     albertel 5479: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5480: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5481: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5482: 	}
                   5483:     }
1.738     albertel 5484:     # look for any posible extension_ match
                   5485:     foreach my $package (@extension) {
                   5486: 	my ($package,$pack_type)=@{$package};
                   5487: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5488: 	    return $packagetab{"$pack_type&$name&default"};
                   5489: 	}
                   5490: 	if (defined($packagetab{$package."&$name&default"})) {
                   5491: 	    return $packagetab{$package."&$name&default"};
                   5492: 	}
                   5493:     }
                   5494:     # look for a global default setting
                   5495:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5496: 	return $packagetab{"default&$name&default"};
                   5497:     }
1.395     albertel 5498:     return undef;
                   5499: }
                   5500: 
1.334     albertel 5501: sub add_prefix_and_part {
                   5502:     my ($prefix,$part)=@_;
                   5503:     my $keyroot;
                   5504:     if (defined($prefix) && $prefix !~ /^__/) {
                   5505: 	# prefix that has a part already
                   5506: 	$keyroot=$prefix;
                   5507:     } elsif (defined($prefix)) {
                   5508: 	# prefix that is missing a part
                   5509: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5510:     } else {
                   5511: 	# no prefix at all
                   5512: 	if (defined($part)) { $keyroot='_'.$part; }
                   5513:     }
                   5514:     return $keyroot;
                   5515: }
                   5516: 
1.71      www      5517: # ---------------------------------------------------------------- Get metadata
                   5518: 
1.599     albertel 5519: my %metaentry;
1.71      www      5520: sub metadata {
1.176     www      5521:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5522:     $uri=&declutter($uri);
1.288     albertel 5523:     # if it is a non metadata possible uri return quickly
1.529     albertel 5524:     if (($uri eq '') || 
                   5525: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5526: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5527:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5528: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5529: 	return undef;
1.288     albertel 5530:     }
1.73      www      5531:     my $filename=$uri;
                   5532:     $uri=~s/\.meta$//;
1.172     www      5533: #
                   5534: # Is the metadata already cached?
1.177     www      5535: # Look at timestamp of caching
1.172     www      5536: # Everything is cached by the main uri, libraries are never directly cached
                   5537: #
1.428     albertel 5538:     if (!defined($liburi)) {
1.599     albertel 5539: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5540: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5541:     }
                   5542:     {
1.172     www      5543: #
                   5544: # Is this a recursive call for a library?
                   5545: #
1.599     albertel 5546: #	if (! exists($metacache{$uri})) {
                   5547: #	    $metacache{$uri}={};
                   5548: #	}
1.171     www      5549:         if ($liburi) {
                   5550: 	    $liburi=&declutter($liburi);
                   5551:             $filename=$liburi;
1.401     bowersj2 5552:         } else {
1.599     albertel 5553: 	    &devalidate_cache_new('meta',$uri);
                   5554: 	    undef(%metaentry);
1.401     bowersj2 5555: 	}
1.140     www      5556:         my %metathesekeys=();
1.73      www      5557:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5558: 	my $metastring;
1.609     banghart 5559: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 5560: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5561: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5562: 	    $metastring=&getfile($file);
1.489     albertel 5563: 	}
1.208     albertel 5564:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5565:         my $token;
1.140     www      5566:         undef %metathesekeys;
1.71      www      5567:         while ($token=$parser->get_token) {
1.339     albertel 5568: 	    if ($token->[0] eq 'S') {
                   5569: 		if (defined($token->[2]->{'package'})) {
1.172     www      5570: #
                   5571: # This is a package - get package info
                   5572: #
1.339     albertel 5573: 		    my $package=$token->[2]->{'package'};
                   5574: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5575: 		    if (defined($token->[2]->{'id'})) { 
                   5576: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5577: 		    }
1.599     albertel 5578: 		    if ($metaentry{':packages'}) {
                   5579: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5580: 		    } else {
1.599     albertel 5581: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5582: 		    }
1.736     albertel 5583: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5584: 			my $part=$keyroot;
                   5585: 			$part=~s/^\_//;
1.736     albertel 5586: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5587: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5588: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5589: 			    # ignore package.tab specified default values
                   5590:                             # here &package_tab_default() will fetch those
                   5591: 			    if ($subp eq 'default') { next; }
1.736     albertel 5592: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5593: 			    my $unikey;
                   5594: 			    if ($pack =~ /_0$/) {
                   5595: 				$unikey='parameter_0_'.$name;
                   5596: 				$part=0;
                   5597: 			    } else {
                   5598: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5599: 			    }
1.339     albertel 5600: 			    if ($subp eq 'display') {
                   5601: 				$value.=' [Part: '.$part.']';
                   5602: 			    }
1.599     albertel 5603: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5604: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5605: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5606: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5607: 			    }
1.599     albertel 5608: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5609: 				$metaentry{':'.$unikey}=
                   5610: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5611: 			    }
1.339     albertel 5612: 			}
                   5613: 		    }
                   5614: 		} else {
1.172     www      5615: #
                   5616: # This is not a package - some other kind of start tag
1.339     albertel 5617: #
                   5618: 		    my $entry=$token->[1];
                   5619: 		    my $unikey;
                   5620: 		    if ($entry eq 'import') {
                   5621: 			$unikey='';
                   5622: 		    } else {
                   5623: 			$unikey=$entry;
                   5624: 		    }
                   5625: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5626: 
                   5627: 		    if (defined($token->[2]->{'id'})) { 
                   5628: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5629: 		    }
1.175     www      5630: 
1.339     albertel 5631: 		    if ($entry eq 'import') {
1.175     www      5632: #
                   5633: # Importing a library here
1.339     albertel 5634: #
                   5635: 			if ($depthcount<20) {
                   5636: 			    my $location=$parser->get_text('/import');
                   5637: 			    my $dir=$filename;
                   5638: 			    $dir=~s|[^/]*$||;
                   5639: 			    $location=&filelocation($dir,$location);
1.736     albertel 5640: 			    my $metadata = 
                   5641: 				&metadata($uri,'keys', $location,$unikey,
                   5642: 					  $depthcount+1);
                   5643: 			    foreach my $meta (split(',',$metadata)) {
                   5644: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   5645: 				$metathesekeys{$meta}=1;
1.339     albertel 5646: 			    }
                   5647: 			}
                   5648: 		    } else { 
                   5649: 			
                   5650: 			if (defined($token->[2]->{'name'})) { 
                   5651: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5652: 			}
                   5653: 			$metathesekeys{$unikey}=1;
1.736     albertel 5654: 			foreach my $param (@{$token->[3]}) {
                   5655: 			    $metaentry{':'.$unikey.'.'.$param} =
                   5656: 				$token->[2]->{$param};
1.339     albertel 5657: 			}
                   5658: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5659: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5660: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5661: 		 # only ws inside the tag, and not in default, so use default
                   5662: 		 # as value
1.599     albertel 5663: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5664: 			} else {
1.321     albertel 5665: 		  # either something interesting inside the tag or default
                   5666:                   # uninteresting
1.599     albertel 5667: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5668: 			}
1.172     www      5669: # end of not-a-package not-a-library import
1.339     albertel 5670: 		    }
1.172     www      5671: # end of not-a-package start tag
1.339     albertel 5672: 		}
1.172     www      5673: # the next is the end of "start tag"
1.339     albertel 5674: 	    }
                   5675: 	}
1.483     albertel 5676: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 5677: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 5678: 	    #no specific packages #how's our extension
                   5679: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5680: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5681: 					 \%metathesekeys);
                   5682: 	}
1.599     albertel 5683: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 5684: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 5685: 		#no specific packages well let's get default then
                   5686: 		if ($key!~/^default&/) { next; }
1.488     albertel 5687: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5688: 					     \%metathesekeys);
                   5689: 	    }
                   5690: 	}
1.338     www      5691: # are there custom rights to evaluate
1.599     albertel 5692: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5693: 
1.338     www      5694:     #
                   5695:     # Importing a rights file here
1.339     albertel 5696:     #
                   5697: 	    unless ($depthcount) {
1.599     albertel 5698: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5699: 		my $dir=$filename;
                   5700: 		$dir=~s|[^/]*$||;
                   5701: 		$location=&filelocation($dir,$location);
1.736     albertel 5702: 		my $rights_metadata =
                   5703: 		    &metadata($uri,'keys',$location,'_rights',
                   5704: 			      $depthcount+1);
                   5705: 		foreach my $rights (split(',',$rights_metadata)) {
                   5706: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   5707: 		    $metathesekeys{$rights}=1;
1.339     albertel 5708: 		}
                   5709: 	    }
                   5710: 	}
1.737     albertel 5711: 	# uniqifiy package listing
                   5712: 	my %seen;
                   5713: 	my @uniq_packages =
                   5714: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   5715: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   5716: 
                   5717: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 5718: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5719: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 5720: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      5721: # this is the end of "was not already recently cached
1.71      www      5722:     }
1.599     albertel 5723:     return $metaentry{':'.$what};
1.261     albertel 5724: }
                   5725: 
1.488     albertel 5726: sub metadata_create_package_def {
1.483     albertel 5727:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5728:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5729:     if ($subp eq 'default') { next; }
                   5730:     
1.599     albertel 5731:     if (defined($metaentry{':packages'})) {
                   5732: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5733:     } else {
1.599     albertel 5734: 	$metaentry{':packages'}=$package;
1.483     albertel 5735:     }
                   5736:     my $value=$packagetab{$key};
                   5737:     my $unikey;
                   5738:     $unikey='parameter_0_'.$name;
1.599     albertel 5739:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5740:     $$metathesekeys{$unikey}=1;
1.599     albertel 5741:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5742: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5743:     }
1.599     albertel 5744:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5745: 	$metaentry{':'.$unikey}=
                   5746: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5747:     }
                   5748: }
                   5749: 
1.261     albertel 5750: sub metadata_generate_part0 {
                   5751:     my ($metadata,$metacache,$uri) = @_;
                   5752:     my %allnames;
1.737     albertel 5753:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 5754: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5755: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5756: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5757: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5758: 	    $allnames{$name}=$part;
                   5759: 	  }
                   5760: 	}
                   5761:     }
                   5762:     foreach my $name (keys(%allnames)) {
                   5763:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5764:       my $key=":parameter_0_$name";
1.261     albertel 5765:       $$metacache{"$key.part"}='0';
                   5766:       $$metacache{"$key.name"}=$name;
1.428     albertel 5767:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5768: 					   $allnames{$name}.'_'.$name.
                   5769: 					   '.type'};
1.428     albertel 5770:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5771: 			     '.display'};
1.644     www      5772:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5773:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5774:       $$metacache{"$key.display"}=$olddis;
                   5775:     }
1.71      www      5776: }
                   5777: 
1.301     www      5778: # ------------------------------------------------- Get the title of a resource
                   5779: 
                   5780: sub gettitle {
                   5781:     my $urlsymb=shift;
                   5782:     my $symb=&symbread($urlsymb);
1.534     albertel 5783:     if ($symb) {
1.620     albertel 5784: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5785: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5786: 	if (defined($cached)) { 
                   5787: 	    return $result;
                   5788: 	}
1.534     albertel 5789: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5790: 	my $title='';
                   5791: 	my %bighash;
1.620     albertel 5792: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5793: 		&GDBM_READER(),0640)) {
                   5794: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5795: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5796: 	    untie %bighash;
                   5797: 	}
                   5798: 	$title=~s/\&colon\;/\:/gs;
                   5799: 	if ($title) {
1.599     albertel 5800: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5801: 	}
                   5802: 	$urlsymb=$url;
                   5803:     }
                   5804:     my $title=&metadata($urlsymb,'title');
                   5805:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5806:     return $title;
1.301     www      5807: }
1.613     albertel 5808: 
1.614     albertel 5809: sub get_slot {
                   5810:     my ($which,$cnum,$cdom)=@_;
                   5811:     if (!$cnum || !$cdom) {
                   5812: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5813: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5814: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5815:     }
1.703     albertel 5816:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   5817:     my %slotinfo;
                   5818:     if (exists($remembered{$key})) {
                   5819: 	$slotinfo{$which} = $remembered{$key};
                   5820:     } else {
                   5821: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5822: 	&Apache::lonhomework::showhash(%slotinfo);
                   5823: 	my ($tmp)=keys(%slotinfo);
                   5824: 	if ($tmp=~/^error:/) { return (); }
                   5825: 	$remembered{$key} = $slotinfo{$which};
                   5826:     }
1.616     albertel 5827:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5828: 	return %{$slotinfo{$which}};
                   5829:     }
                   5830:     return $slotinfo{$which};
1.614     albertel 5831: }
1.31      www      5832: # ------------------------------------------------- Update symbolic store links
                   5833: 
                   5834: sub symblist {
                   5835:     my ($mapname,%newhash)=@_;
1.438     www      5836:     $mapname=&deversion(&declutter($mapname));
1.31      www      5837:     my %hash;
1.620     albertel 5838:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5839:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5840:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 5841: 	    foreach my $url (keys %newhash) {
                   5842: 		next if ($url eq 'last_known'
                   5843: 			 && $env{'form.no_update_last_known'});
                   5844: 		$hash{declutter($url)}=&encode_symb($mapname,
                   5845: 						    $newhash{$url}->[1],
                   5846: 						    $newhash{$url}->[0]);
1.191     harris41 5847:             }
1.31      www      5848:             if (untie(%hash)) {
                   5849: 		return 'ok';
                   5850:             }
                   5851:         }
                   5852:     }
                   5853:     return 'error';
1.212     www      5854: }
                   5855: 
                   5856: # --------------------------------------------------------------- Verify a symb
                   5857: 
                   5858: sub symbverify {
1.510     www      5859:     my ($symb,$thisurl)=@_;
                   5860:     my $thisfn=$thisurl;
                   5861: # wrapper not part of symbs
                   5862:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 5863:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      5864:     $thisfn=&declutter($thisfn);
1.215     www      5865: # direct jump to resource in page or to a sequence - will construct own symbs
                   5866:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5867: # check URL part
1.409     www      5868:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5869: 
1.431     www      5870:     unless ($url eq $thisfn) { return 0; }
1.213     www      5871: 
1.216     www      5872:     $symb=&symbclean($symb);
1.510     www      5873:     $thisurl=&deversion($thisurl);
1.439     www      5874:     $thisfn=&deversion($thisfn);
1.213     www      5875: 
                   5876:     my %bighash;
                   5877:     my $okay=0;
1.431     www      5878: 
1.620     albertel 5879:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5880:                             &GDBM_READER(),0640)) {
1.510     www      5881:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5882:         unless ($ids) { 
1.510     www      5883:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5884:         }
                   5885:         if ($ids) {
                   5886: # ------------------------------------------------------------------- Has ID(s)
                   5887: 	    foreach (split(/\,/,$ids)) {
1.644     www      5888: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5889:                if (
                   5890:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5891:    eq $symb) { 
1.620     albertel 5892: 		   if (($env{'request.role.adv'}) ||
                   5893: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5894: 		       $okay=1; 
                   5895: 		   }
                   5896: 	       }
1.216     www      5897: 	   }
                   5898:         }
1.213     www      5899: 	untie(%bighash);
                   5900:     }
                   5901:     return $okay;
1.31      www      5902: }
                   5903: 
1.210     www      5904: # --------------------------------------------------------------- Clean-up symb
                   5905: 
                   5906: sub symbclean {
                   5907:     my $symb=shift;
1.568     albertel 5908:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5909: # remove version from map
                   5910:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      5911: 
1.210     www      5912: # remove version from URL
                   5913:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      5914: 
1.507     www      5915: # remove wrapper
                   5916: 
1.510     www      5917:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 5918:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      5919:     return $symb;
1.409     www      5920: }
                   5921: 
                   5922: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 5923: 
                   5924: sub encode_symb {
                   5925:     my ($map,$resid,$url)=@_;
                   5926:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   5927: }
1.409     www      5928: 
                   5929: sub decode_symb {
1.568     albertel 5930:     my $symb=shift;
                   5931:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   5932:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      5933:     return (&fixversion($map),$resid,&fixversion($url));
                   5934: }
                   5935: 
                   5936: sub fixversion {
                   5937:     my $fn=shift;
1.609     banghart 5938:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      5939:     my %bighash;
                   5940:     my $uri=&clutter($fn);
1.620     albertel 5941:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      5942: # is this cached?
1.599     albertel 5943:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      5944:     if (defined($cached)) { return $result; }
                   5945: # unfortunately not cached, or expired
1.620     albertel 5946:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      5947: 	    &GDBM_READER(),0640)) {
                   5948:  	if ($bighash{'version_'.$uri}) {
                   5949:  	    my $version=$bighash{'version_'.$uri};
1.444     www      5950:  	    unless (($version eq 'mostrecent') || 
                   5951: 		    ($version==&getversion($uri))) {
1.440     www      5952:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   5953:  	    }
                   5954:  	}
                   5955:  	untie %bighash;
1.413     www      5956:     }
1.599     albertel 5957:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      5958: }
                   5959: 
                   5960: sub deversion {
                   5961:     my $url=shift;
                   5962:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   5963:     return $url;
1.210     www      5964: }
                   5965: 
1.31      www      5966: # ------------------------------------------------------ Return symb list entry
                   5967: 
                   5968: sub symbread {
1.249     www      5969:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 5970:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 5971:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      5972: # no filename provided? try from environment
1.44      www      5973:     unless ($thisfn) {
1.620     albertel 5974:         if ($env{'request.symb'}) {
                   5975: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 5976: 	}
1.620     albertel 5977: 	$thisfn=$env{'request.filename'};
1.44      www      5978:     }
1.569     albertel 5979:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      5980: # is that filename actually a symb? Verify, clean, and return
                   5981:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 5982: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 5983: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 5984: 	}
1.242     www      5985:     }
1.44      www      5986:     $thisfn=declutter($thisfn);
1.31      www      5987:     my %hash;
1.37      www      5988:     my %bighash;
                   5989:     my $syval='';
1.620     albertel 5990:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  5991:         my $targetfn = $thisfn;
1.609     banghart 5992:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  5993:             $targetfn = 'adm/wrapper/'.$thisfn;
                   5994:         }
1.687     albertel 5995: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   5996: 	    $targetfn=$1;
                   5997: 	}
1.620     albertel 5998:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5999:                       &GDBM_READER(),0640)) {
1.481     raeburn  6000: 	    $syval=$hash{$targetfn};
1.37      www      6001:             untie(%hash);
                   6002:         }
                   6003: # ---------------------------------------------------------- There was an entry
                   6004:         if ($syval) {
1.601     albertel 6005: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6006: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6007: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6008: 		    #return $env{$cache_str}='';
1.601     albertel 6009: 		#}    
                   6010: 		#$syval.=$1;
                   6011: 	    #}
1.37      www      6012:         } else {
                   6013: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6014:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6015:                             &GDBM_READER(),0640)) {
1.37      www      6016: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6017:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6018:               unless ($ids) { 
                   6019:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6020:               }
                   6021:               unless ($ids) {
                   6022: # alias?
                   6023: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6024:               }
1.37      www      6025:               if ($ids) {
                   6026: # ------------------------------------------------------------------- Has ID(s)
                   6027:                  my @possibilities=split(/\,/,$ids);
1.39      www      6028:                  if ($#possibilities==0) {
                   6029: # ----------------------------------------------- There is only one possibility
1.37      www      6030: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6031: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6032: 						    $resid,$thisfn);
1.249     www      6033:                  } elsif (!$donotrecurse) {
1.39      www      6034: # ------------------------------------------ There is more than one possibility
                   6035:                      my $realpossible=0;
1.191     harris41 6036:                      foreach (@possibilities) {
1.39      www      6037: 			 my $file=$bighash{'src_'.$_};
                   6038:                          if (&allowed('bre',$file)) {
                   6039:          		    my ($mapid,$resid)=split(/\./,$_);
                   6040:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6041: 				$realpossible++;
1.626     albertel 6042:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6043: 						    $resid,$thisfn);
1.39      www      6044:                             }
                   6045: 			 }
1.191     harris41 6046:                      }
1.39      www      6047: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6048:                  } else {
                   6049:                      $syval='';
1.37      www      6050:                  }
                   6051: 	      }
                   6052:               untie(%bighash)
1.481     raeburn  6053:            }
1.31      www      6054:         }
1.62      www      6055:         if ($syval) {
1.620     albertel 6056: 	    return $env{$cache_str}=$syval;
1.62      www      6057:         }
1.31      www      6058:     }
1.44      www      6059:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6060:     return $env{$cache_str}='';
1.31      www      6061: }
                   6062: 
                   6063: # ---------------------------------------------------------- Return random seed
                   6064: 
1.32      www      6065: sub numval {
                   6066:     my $txt=shift;
                   6067:     $txt=~tr/A-J/0-9/;
                   6068:     $txt=~tr/a-j/0-9/;
                   6069:     $txt=~tr/K-T/0-9/;
                   6070:     $txt=~tr/k-t/0-9/;
                   6071:     $txt=~tr/U-Z/0-5/;
                   6072:     $txt=~tr/u-z/0-5/;
                   6073:     $txt=~s/\D//g;
1.564     albertel 6074:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6075:     return int($txt);
1.368     albertel 6076: }
                   6077: 
1.484     albertel 6078: sub numval2 {
                   6079:     my $txt=shift;
                   6080:     $txt=~tr/A-J/0-9/;
                   6081:     $txt=~tr/a-j/0-9/;
                   6082:     $txt=~tr/K-T/0-9/;
                   6083:     $txt=~tr/k-t/0-9/;
                   6084:     $txt=~tr/U-Z/0-5/;
                   6085:     $txt=~tr/u-z/0-5/;
                   6086:     $txt=~s/\D//g;
                   6087:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6088:     my $total;
                   6089:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6090:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6091:     return int($total);
                   6092: }
                   6093: 
1.575     albertel 6094: sub numval3 {
                   6095:     use integer;
                   6096:     my $txt=shift;
                   6097:     $txt=~tr/A-J/0-9/;
                   6098:     $txt=~tr/a-j/0-9/;
                   6099:     $txt=~tr/K-T/0-9/;
                   6100:     $txt=~tr/k-t/0-9/;
                   6101:     $txt=~tr/U-Z/0-5/;
                   6102:     $txt=~tr/u-z/0-5/;
                   6103:     $txt=~s/\D//g;
                   6104:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6105:     my $total;
                   6106:     foreach my $val (@txts) { $total+=$val; }
                   6107:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6108:     return $total;
                   6109: }
                   6110: 
1.675     albertel 6111: sub digest {
                   6112:     my ($data)=@_;
                   6113:     my $digest=&Digest::MD5::md5($data);
                   6114:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6115:     my ($e,$f);
                   6116:     {
                   6117:         use integer;
                   6118:         $e=($a+$b);
                   6119:         $f=($c+$d);
                   6120:         if ($_64bit) {
                   6121:             $e=(($e<<32)>>32);
                   6122:             $f=(($f<<32)>>32);
                   6123:         }
                   6124:     }
                   6125:     if (wantarray) {
                   6126: 	return ($e,$f);
                   6127:     } else {
                   6128: 	my $g;
                   6129: 	{
                   6130: 	    use integer;
                   6131: 	    $g=($e+$f);
                   6132: 	    if ($_64bit) {
                   6133: 		$g=(($g<<32)>>32);
                   6134: 	    }
                   6135: 	}
                   6136: 	return $g;
                   6137:     }
                   6138: }
                   6139: 
1.368     albertel 6140: sub latest_rnd_algorithm_id {
1.675     albertel 6141:     return '64bit5';
1.366     albertel 6142: }
1.32      www      6143: 
1.503     albertel 6144: sub get_rand_alg {
                   6145:     my ($courseid)=@_;
                   6146:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6147:     if ($courseid) {
1.620     albertel 6148: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6149:     }
                   6150:     return &latest_rnd_algorithm_id();
                   6151: }
                   6152: 
1.562     albertel 6153: sub validCODE {
                   6154:     my ($CODE)=@_;
                   6155:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6156:     return 0;
                   6157: }
                   6158: 
1.491     albertel 6159: sub getCODE {
1.620     albertel 6160:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6161:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6162: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6163: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6164: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6165:     }
                   6166:     return undef;
                   6167: }
                   6168: 
1.31      www      6169: sub rndseed {
1.155     albertel 6170:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6171: 
                   6172:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6173:     if (!$symb) {
1.366     albertel 6174: 	unless ($symb=$wsymb) { return time; }
                   6175:     }
                   6176:     if (!$courseid) { $courseid=$wcourseid; }
                   6177:     if (!$domain) { $domain=$wdomain; }
                   6178:     if (!$username) { $username=$wusername }
1.503     albertel 6179:     my $which=&get_rand_alg();
1.491     albertel 6180:     if (defined(&getCODE())) {
1.675     albertel 6181: 	if ($which eq '64bit5') {
                   6182: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6183: 	} elsif ($which eq '64bit4') {
1.575     albertel 6184: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6185: 	} else {
                   6186: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6187: 	}
1.675     albertel 6188:     } elsif ($which eq '64bit5') {
                   6189: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6190:     } elsif ($which eq '64bit4') {
                   6191: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6192:     } elsif ($which eq '64bit3') {
                   6193: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6194:     } elsif ($which eq '64bit2') {
                   6195: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6196:     } elsif ($which eq '64bit') {
                   6197: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6198:     }
                   6199:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6200: }
                   6201: 
                   6202: sub rndseed_32bit {
                   6203:     my ($symb,$courseid,$domain,$username)=@_;
                   6204:     {
                   6205: 	use integer;
                   6206: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6207: 	my $symbseed=numval($symb) << 22;
                   6208: 	my $namechck=unpack("%32C*",$username) << 17;
                   6209: 	my $nameseed=numval($username) << 12;
                   6210: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6211: 	my $courseseed=unpack("%32C*",$courseid);
                   6212: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6213: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6214: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6215: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6216: 	return $num;
                   6217:     }
                   6218: }
                   6219: 
                   6220: sub rndseed_64bit {
                   6221:     my ($symb,$courseid,$domain,$username)=@_;
                   6222:     {
                   6223: 	use integer;
                   6224: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6225: 	my $symbseed=numval($symb) << 10;
                   6226: 	my $namechck=unpack("%32S*",$username);
                   6227: 	
                   6228: 	my $nameseed=numval($username) << 21;
                   6229: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6230: 	my $courseseed=unpack("%32S*",$courseid);
                   6231: 	
                   6232: 	my $num1=$symbchck+$symbseed+$namechck;
                   6233: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6234: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6235: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6236: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6237: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6238: 	return "$num1,$num2";
1.155     albertel 6239:     }
1.366     albertel 6240: }
                   6241: 
1.443     albertel 6242: sub rndseed_64bit2 {
                   6243:     my ($symb,$courseid,$domain,$username)=@_;
                   6244:     {
                   6245: 	use integer;
                   6246: 	# strings need to be an even # of cahracters long, it it is odd the
                   6247:         # last characters gets thrown away
                   6248: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6249: 	my $symbseed=numval($symb) << 10;
                   6250: 	my $namechck=unpack("%32S*",$username.' ');
                   6251: 	
                   6252: 	my $nameseed=numval($username) << 21;
1.501     albertel 6253: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6254: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6255: 	
                   6256: 	my $num1=$symbchck+$symbseed+$namechck;
                   6257: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6258: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6259: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6260: 	return "$num1,$num2";
                   6261:     }
                   6262: }
                   6263: 
                   6264: sub rndseed_64bit3 {
                   6265:     my ($symb,$courseid,$domain,$username)=@_;
                   6266:     {
                   6267: 	use integer;
                   6268: 	# strings need to be an even # of cahracters long, it it is odd the
                   6269:         # last characters gets thrown away
                   6270: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6271: 	my $symbseed=numval2($symb) << 10;
                   6272: 	my $namechck=unpack("%32S*",$username.' ');
                   6273: 	
                   6274: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6275: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6276: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6277: 	
                   6278: 	my $num1=$symbchck+$symbseed+$namechck;
                   6279: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6280: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6281: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6282: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6283: 	
1.503     albertel 6284: 	return "$num1:$num2";
1.443     albertel 6285:     }
                   6286: }
                   6287: 
1.575     albertel 6288: sub rndseed_64bit4 {
                   6289:     my ($symb,$courseid,$domain,$username)=@_;
                   6290:     {
                   6291: 	use integer;
                   6292: 	# strings need to be an even # of cahracters long, it it is odd the
                   6293:         # last characters gets thrown away
                   6294: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6295: 	my $symbseed=numval3($symb) << 10;
                   6296: 	my $namechck=unpack("%32S*",$username.' ');
                   6297: 	
                   6298: 	my $nameseed=numval3($username) << 21;
                   6299: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6300: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6301: 	
                   6302: 	my $num1=$symbchck+$symbseed+$namechck;
                   6303: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6304: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6305: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6306: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6307: 	
                   6308: 	return "$num1:$num2";
                   6309:     }
                   6310: }
                   6311: 
1.675     albertel 6312: sub rndseed_64bit5 {
                   6313:     my ($symb,$courseid,$domain,$username)=@_;
                   6314:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6315:     return "$num1:$num2";
                   6316: }
                   6317: 
1.366     albertel 6318: sub rndseed_CODE_64bit {
                   6319:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6320:     {
1.366     albertel 6321: 	use integer;
1.443     albertel 6322: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6323: 	my $symbseed=numval2($symb);
1.491     albertel 6324: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6325: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6326: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6327: 	my $num1=$symbseed+$CODEchck;
                   6328: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6329: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6330: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6331: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6332: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6333: 	return "$num1:$num2";
1.366     albertel 6334:     }
                   6335: }
                   6336: 
1.575     albertel 6337: sub rndseed_CODE_64bit4 {
                   6338:     my ($symb,$courseid,$domain,$username)=@_;
                   6339:     {
                   6340: 	use integer;
                   6341: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6342: 	my $symbseed=numval3($symb);
                   6343: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6344: 	my $CODEseed=numval3(&getCODE());
                   6345: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6346: 	my $num1=$symbseed+$CODEchck;
                   6347: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6348: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6349: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6350: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6351: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6352: 	return "$num1:$num2";
                   6353:     }
                   6354: }
                   6355: 
1.675     albertel 6356: sub rndseed_CODE_64bit5 {
                   6357:     my ($symb,$courseid,$domain,$username)=@_;
                   6358:     my $code = &getCODE();
                   6359:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6360:     return "$num1:$num2";
                   6361: }
                   6362: 
1.366     albertel 6363: sub setup_random_from_rndseed {
                   6364:     my ($rndseed)=@_;
1.503     albertel 6365:     if ($rndseed =~/([,:])/) {
                   6366: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6367: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6368:     } else {
                   6369: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6370:     }
1.36      albertel 6371: }
                   6372: 
1.474     albertel 6373: sub latest_receipt_algorithm_id {
                   6374:     return 'receipt2';
                   6375: }
                   6376: 
1.480     www      6377: sub recunique {
                   6378:     my $fucourseid=shift;
                   6379:     my $unique;
1.620     albertel 6380:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6381: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6382:     } else {
                   6383: 	$unique=$perlvar{'lonReceipt'};
                   6384:     }
                   6385:     return unpack("%32C*",$unique);
                   6386: }
                   6387: 
                   6388: sub recprefix {
                   6389:     my $fucourseid=shift;
                   6390:     my $prefix;
1.620     albertel 6391:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6392: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6393:     } else {
                   6394: 	$prefix=$perlvar{'lonHostID'};
                   6395:     }
                   6396:     return unpack("%32C*",$prefix);
                   6397: }
                   6398: 
1.76      www      6399: sub ireceipt {
1.474     albertel 6400:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6401:     my $cuname=unpack("%32C*",$funame);
                   6402:     my $cudom=unpack("%32C*",$fudom);
                   6403:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6404:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6405:     my $cunique=&recunique($fucourseid);
1.474     albertel 6406:     my $cpart=unpack("%32S*",$part);
1.480     www      6407:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6408:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6409: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6410: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6411: 			       " and ".($cpart%$cudom));
                   6412: 			       
                   6413: 	$return.= ($cunique%$cuname+
                   6414: 		   $cunique%$cudom+
                   6415: 		   $cusymb%$cuname+
                   6416: 		   $cusymb%$cudom+
                   6417: 		   $cucourseid%$cuname+
                   6418: 		   $cucourseid%$cudom+
                   6419: 		   $cpart%$cuname+
                   6420: 		   $cpart%$cudom);
                   6421:     } else {
                   6422: 	$return.= ($cunique%$cuname+
                   6423: 		   $cunique%$cudom+
                   6424: 		   $cusymb%$cuname+
                   6425: 		   $cusymb%$cudom+
                   6426: 		   $cucourseid%$cuname+
                   6427: 		   $cucourseid%$cudom);
                   6428:     }
                   6429:     return $return;
1.76      www      6430: }
                   6431: 
                   6432: sub receipt {
1.474     albertel 6433:     my ($part)=@_;
                   6434:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6435:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6436: }
1.260     ng       6437: 
1.36      albertel 6438: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6439: # returns either the contents of the file or 
                   6440: # -1 if the file doesn't exist
1.481     raeburn  6441: #
                   6442: # if the target is a file that was uploaded via DOCS, 
                   6443: # a check will be made to see if a current copy exists on the local server,
                   6444: # if it does this will be served, otherwise a copy will be retrieved from
                   6445: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6446: # the local server.   
1.472     albertel 6447: 
1.36      albertel 6448: sub getfile {
1.538     albertel 6449:     my ($file) = @_;
1.609     banghart 6450:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6451:     &repcopy($file);
                   6452:     return &readfile($file);
                   6453: }
                   6454: 
                   6455: sub repcopy_userfile {
                   6456:     my ($file)=@_;
1.609     banghart 6457:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6458:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6459:     my ($cdom,$cnum,$filename) = 
                   6460: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6461:     my ($info,$rtncode);
                   6462:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6463:     if (-e "$file") {
                   6464: 	my @fileinfo = stat($file);
                   6465: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6466: 	if ($lwpresp ne 'ok') {
                   6467: 	    if ($rtncode eq '404') {
1.538     albertel 6468: 		unlink($file);
1.482     albertel 6469: 	    }
1.517     albertel 6470: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6471: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6472: 	    #my $response=$ua->request($request);
                   6473: 	    #if ($response->is_success()) {
                   6474: 	#	return $response->content;
                   6475: 	#    } else {
                   6476: 	#	return -1;
                   6477: 	#    }
1.482     albertel 6478: 	    return -1;
                   6479: 	}
                   6480: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6481: 	    return 'ok';
1.482     albertel 6482: 	}
                   6483: 	$info = '';
1.538     albertel 6484: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6485: 	if ($lwpresp ne 'ok') {
                   6486: 	    return -1;
                   6487: 	}
                   6488:     } else {
1.538     albertel 6489: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6490: 	if ($lwpresp ne 'ok') {
1.517     albertel 6491: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6492: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6493: 	    my $response=$ua->request($request);
                   6494: 	    if ($response->is_success()) {
1.538     albertel 6495: 		$info=$response->content;
1.517     albertel 6496: 	    } else {
                   6497: 		return -1;
                   6498: 	    }
1.482     albertel 6499: 	}
                   6500: 	my @parts = ($cdom,$cnum); 
                   6501: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6502: 	    push @parts, split(/\//,$1);
1.518     albertel 6503: 	}
1.538     albertel 6504: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6505: 	foreach my $part (@parts) {
                   6506: 	    $path .= '/'.$part;
                   6507: 	    if (!-e $path) {
                   6508: 		mkdir($path,0770);
                   6509: 	    }
                   6510: 	}
                   6511:     }
1.538     albertel 6512:     open(FILE,">$file");
1.482     albertel 6513:     print FILE $info;
                   6514:     close(FILE);
1.607     raeburn  6515:     return 'ok';
1.481     raeburn  6516: }
                   6517: 
1.517     albertel 6518: sub tokenwrapper {
                   6519:     my $uri=shift;
1.552     albertel 6520:     $uri=~s|^http\://([^/]+)||;
                   6521:     $uri=~s|^/||;
1.620     albertel 6522:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6523:     my $token=$1;
1.552     albertel 6524:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6525:     if ($udom && $uname && $file) {
                   6526: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6527:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6528:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6529:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6530:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6531:     } else {
                   6532:         return '/adm/notfound.html';
                   6533:     }
                   6534: }
                   6535: 
1.481     raeburn  6536: sub getuploaded {
                   6537:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6538:     $uri=~s/^\///;
                   6539:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6540:     my $ua=new LWP::UserAgent;
                   6541:     my $request=new HTTP::Request($reqtype,$uri);
                   6542:     my $response=$ua->request($request);
                   6543:     $$rtncode = $response->code;
1.482     albertel 6544:     if (! $response->is_success()) {
                   6545: 	return 'failed';
                   6546:     }      
                   6547:     if ($reqtype eq 'HEAD') {
1.486     www      6548: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6549:     } elsif ($reqtype eq 'GET') {
                   6550: 	$$info = $response->content;
1.472     albertel 6551:     }
1.482     albertel 6552:     return 'ok';
1.36      albertel 6553: }
                   6554: 
1.481     raeburn  6555: sub readfile {
                   6556:     my $file = shift;
                   6557:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6558:     my $fh;
                   6559:     open($fh,"<$file");
                   6560:     my $a='';
                   6561:     while (<$fh>) { $a .=$_; }
                   6562:     return $a;
                   6563: }
                   6564: 
1.36      albertel 6565: sub filelocation {
1.590     banghart 6566:     my ($dir,$file) = @_;
                   6567:     my $location;
                   6568:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6569: 
                   6570:     if ($file =~ m-^/adm/-) {
                   6571: 	$file=~s-^/adm/wrapper/-/-;
                   6572: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6573:     }
1.590     banghart 6574:     if ($file=~m:^/~:) { # is a contruction space reference
                   6575:         $location = $file;
                   6576:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6577:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6578: 	# is a correct contruction space reference
                   6579:         $location = $file;
1.609     banghart 6580:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6581:         my ($udom,$uname,$filename)=
1.609     banghart 6582:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6583:         my $home=&homeserver($uname,$udom);
                   6584:         my $is_me=0;
                   6585:         my @ids=&current_machine_ids();
                   6586:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6587:         if ($is_me) {
1.740     www      6588:   	    $location=&propath($udom,$uname).
1.590     banghart 6589:   	      '/userfiles/'.$filename;
                   6590:         } else {
                   6591:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6592:   	      $udom.'/'.$uname.'/'.$filename;
                   6593:         }
                   6594:     } else {
                   6595:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6596:         $file=~s:^/res/:/:;
                   6597:         if ( !( $file =~ m:^/:) ) {
                   6598:             $location = $dir. '/'.$file;
                   6599:         } else {
                   6600:             $location = '/home/httpd/html/res'.$file;
                   6601:         }
1.59      albertel 6602:     }
1.590     banghart 6603:     $location=~s://+:/:g; # remove duplicate /
                   6604:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6605:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6606:     return $location;
1.46      www      6607: }
1.36      albertel 6608: 
1.46      www      6609: sub hreflocation {
                   6610:     my ($dir,$file)=@_;
1.460     albertel 6611:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6612: 	$file=filelocation($dir,$file);
1.700     albertel 6613:     } elsif ($file=~m-^/adm/-) {
                   6614: 	$file=~s-^/adm/wrapper/-/-;
                   6615: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6616:     }
                   6617:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6618: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6619:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6620: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6621:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6622: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6623: 	    -/uploaded/$1/$2/-x;
1.46      www      6624:     }
1.462     albertel 6625:     return $file;
1.465     albertel 6626: }
                   6627: 
                   6628: sub current_machine_domains {
                   6629:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6630:     my @domains;
                   6631:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6632: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6633: 	if ($hostname eq $name) {
                   6634: 	    push(@domains,$hostdom{$id});
                   6635: 	}
                   6636:     }
                   6637:     return @domains;
                   6638: }
                   6639: 
                   6640: sub current_machine_ids {
                   6641:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6642:     my @ids;
                   6643:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6644: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6645: 	if ($hostname eq $name) {
                   6646: 	    push(@ids,$id);
                   6647: 	}
                   6648:     }
                   6649:     return @ids;
1.31      www      6650: }
                   6651: 
                   6652: # ------------------------------------------------------------- Declutters URLs
                   6653: 
                   6654: sub declutter {
                   6655:     my $thisfn=shift;
1.569     albertel 6656:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6657:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6658:     $thisfn=~s/^\///;
1.697     albertel 6659:     $thisfn=~s|^adm/wrapper/||;
                   6660:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      6661:     $thisfn=~s/^res\///;
1.235     www      6662:     $thisfn=~s/\?.+$//;
1.268     www      6663:     return $thisfn;
                   6664: }
                   6665: 
                   6666: # ------------------------------------------------------------- Clutter up URLs
                   6667: 
                   6668: sub clutter {
                   6669:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6670:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6671:        $thisfn='/res'.$thisfn; 
                   6672:     }
1.694     albertel 6673:     if ($thisfn !~m|/adm|) {
1.695     albertel 6674: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 6675: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 6676: 	} else {
                   6677: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   6678: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 6679: 	    if ($embstyle eq 'ssi'
                   6680: 		|| ($embstyle eq 'hdn')
                   6681: 		|| ($embstyle eq 'rat')
                   6682: 		|| ($embstyle eq 'prv')
                   6683: 		|| ($embstyle eq 'ign')) {
                   6684: 		#do nothing with these
                   6685: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 6686: 		|| ($embstyle eq 'emb')
                   6687: 		|| ($embstyle eq 'wrp')) {
                   6688: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 6689: 	    } elsif ($embstyle eq 'unk'
                   6690: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 6691: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 6692: 	    } else {
1.718     www      6693: #		&logthis("Got a blank emb style");
1.695     albertel 6694: 	    }
1.694     albertel 6695: 	}
                   6696:     }
1.31      www      6697:     return $thisfn;
1.12      www      6698: }
                   6699: 
1.557     albertel 6700: sub freeze_escape {
                   6701:     my ($value)=@_;
                   6702:     if (ref($value)) {
                   6703: 	$value=&nfreeze($value);
                   6704: 	return '__FROZEN__'.&escape($value);
                   6705:     }
                   6706:     return &escape($value);
                   6707: }
                   6708: 
1.11      www      6709: 
1.557     albertel 6710: sub thaw_unescape {
                   6711:     my ($value)=@_;
                   6712:     if ($value =~ /^__FROZEN__/) {
                   6713: 	substr($value,0,10,undef);
                   6714: 	$value=&unescape($value);
                   6715: 	return &thaw($value);
                   6716:     }
                   6717:     return &unescape($value);
                   6718: }
                   6719: 
1.436     albertel 6720: sub correct_line_ends {
                   6721:     my ($result)=@_;
                   6722:     $$result =~s/\r\n/\n/mg;
                   6723:     $$result =~s/\r/\n/mg;
1.415     albertel 6724: }
1.1       albertel 6725: # ================================================================ Main Program
                   6726: 
1.184     www      6727: sub goodbye {
1.204     albertel 6728:    &logthis("Starting Shut down");
1.443     albertel 6729: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6730:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6731: #converted
1.599     albertel 6732: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6733:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6734: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6735: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6736: #1.1 only
1.599     albertel 6737: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6738: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6739: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6740: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6741:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6742:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6743:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6744:    &flushcourselogs();
                   6745:    &logthis("Shutting down");
                   6746: }
                   6747: 
1.179     www      6748: BEGIN {
1.228     harris41 6749: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6750:     unless ($readit) {
1.217     harris41 6751: {
1.581     matthew  6752:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6753:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6754: 
                   6755:     while (my $configline=<$config>) {
1.484     albertel 6756:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6757: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6758:            chomp($varvalue);
1.1       albertel 6759:            $perlvar{$varname}=$varvalue;
                   6760:         }
                   6761:     }
1.448     albertel 6762:     close($config);
1.1       albertel 6763: }
1.227     harris41 6764: {
1.448     albertel 6765:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6766: 
                   6767:     while (my $configline=<$config>) {
                   6768:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6769: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6770:            chomp($varvalue);
                   6771:            $perlvar{$varname}=$varvalue;
                   6772:         }
                   6773:     }
1.448     albertel 6774:     close($config);
1.227     harris41 6775: }
1.1       albertel 6776: 
1.327     albertel 6777: # ------------------------------------------------------------ Read domain file
                   6778: {
                   6779:     %domaindescription = ();
                   6780:     %domain_auth_def = ();
                   6781:     %domain_auth_arg_def = ();
1.448     albertel 6782:     my $fh;
                   6783:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6784:        while (<$fh>) {
1.390     matthew  6785:            next if (/^(\#|\s*$)/);
                   6786: #           next if /^\#/;
1.327     albertel 6787:            chomp;
1.403     www      6788:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  6789: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      6790: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6791:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6792: 	   $domaindescription{$domain}=$domain_description;
                   6793: 	   $domain_lang_def{$domain}=$def_lang;
                   6794: 	   $domain_city{$domain}=$city;
                   6795: 	   $domain_longi{$domain}=$longi;
                   6796: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  6797:            $domain_primary{$domain}=$primary;
1.403     www      6798: 
1.448     albertel 6799:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6800: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6801: 	}
1.327     albertel 6802:     }
1.448     albertel 6803:     close ($fh);
1.327     albertel 6804: }
                   6805: 
                   6806: 
1.1       albertel 6807: # ------------------------------------------------------------- Read hosts file
                   6808: {
1.448     albertel 6809:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6810: 
                   6811:     while (my $configline=<$config>) {
1.303     matthew  6812:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6813:        chomp($configline);
1.595     albertel 6814:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6815:        $name=~s/\s//g;
1.595     albertel 6816:        if ($id && $domain && $role && $name) {
1.252     albertel 6817: 	 $hostname{$id}=$name;
                   6818: 	 $hostdom{$id}=$domain;
                   6819: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6820:        }
1.1       albertel 6821:     }
1.448     albertel 6822:     close($config);
1.619     albertel 6823:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 6824:     #&get_iphost();
1.1       albertel 6825: }
                   6826: 
1.598     albertel 6827: sub get_iphost {
                   6828:     if (%iphost) { return %iphost; }
1.653     albertel 6829:     my %name_to_ip;
1.598     albertel 6830:     foreach my $id (keys(%hostname)) {
                   6831: 	my $name=$hostname{$id};
1.653     albertel 6832: 	my $ip;
                   6833: 	if (!exists($name_to_ip{$name})) {
                   6834: 	    $ip = gethostbyname($name);
                   6835: 	    if (!$ip || length($ip) ne 4) {
                   6836: 		&logthis("Skipping host $id name $name no IP found\n");
                   6837: 		next;
                   6838: 	    }
                   6839: 	    $ip=inet_ntoa($ip);
                   6840: 	    $name_to_ip{$name} = $ip;
                   6841: 	} else {
                   6842: 	    $ip = $name_to_ip{$name};
1.598     albertel 6843: 	}
                   6844: 	push(@{$iphost{$ip}},$id);
                   6845:     }
                   6846:     return %iphost;
                   6847: }
                   6848: 
1.1       albertel 6849: # ------------------------------------------------------ Read spare server file
                   6850: {
1.448     albertel 6851:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 6852: 
                   6853:     while (my $configline=<$config>) {
                   6854:        chomp($configline);
1.284     matthew  6855:        if ($configline) {
1.1       albertel 6856:           $spareid{$configline}=1;
                   6857:        }
                   6858:     }
1.448     albertel 6859:     close($config);
1.1       albertel 6860: }
1.11      www      6861: # ------------------------------------------------------------ Read permissions
                   6862: {
1.448     albertel 6863:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      6864: 
                   6865:     while (my $configline=<$config>) {
1.448     albertel 6866: 	chomp($configline);
                   6867: 	if ($configline) {
                   6868: 	    my ($role,$perm)=split(/ /,$configline);
                   6869: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   6870: 	}
1.11      www      6871:     }
1.448     albertel 6872:     close($config);
1.11      www      6873: }
                   6874: 
                   6875: # -------------------------------------------- Read plain texts for permissions
                   6876: {
1.448     albertel 6877:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      6878: 
                   6879:     while (my $configline=<$config>) {
1.448     albertel 6880: 	chomp($configline);
                   6881: 	if ($configline) {
1.742     raeburn  6882: 	    my ($short,@plain)=split(/:/,$configline);
                   6883:             %{$prp{$short}} = ();
                   6884: 	    if (@plain > 0) {
                   6885:                 $prp{$short}{'std'} = $plain[0];
                   6886:                 for (my $i=1; $i<@plain; $i++) {
                   6887:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   6888:                 }
                   6889:             }
1.448     albertel 6890: 	}
1.135     www      6891:     }
1.448     albertel 6892:     close($config);
1.135     www      6893: }
                   6894: 
                   6895: # ---------------------------------------------------------- Read package table
                   6896: {
1.448     albertel 6897:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      6898: 
                   6899:     while (my $configline=<$config>) {
1.483     albertel 6900: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 6901: 	chomp($configline);
                   6902: 	my ($short,$plain)=split(/:/,$configline);
                   6903: 	my ($pack,$name)=split(/\&/,$short);
                   6904: 	if ($plain ne '') {
                   6905: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   6906: 	    $packagetab{$short}=$plain; 
                   6907: 	}
1.11      www      6908:     }
1.448     albertel 6909:     close($config);
1.329     matthew  6910: }
                   6911: 
                   6912: # ------------- set up temporary directory
                   6913: {
                   6914:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   6915: 
1.11      www      6916: }
                   6917: 
1.599     albertel 6918: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      6919: 
1.281     www      6920: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      6921: $dumpcount=0;
1.22      www      6922: 
1.163     harris41 6923: &logtouch();
1.672     albertel 6924: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      6925: $readit=1;
1.564     albertel 6926:     {
                   6927: 	use integer;
                   6928: 	my $test=(2**32)+1;
1.568     albertel 6929: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 6930: 	&logthis(" Detected 64bit platform ($_64bit)");
                   6931:     }
1.195     www      6932: }
1.1       albertel 6933: }
1.179     www      6934: 
1.1       albertel 6935: 1;
1.191     harris41 6936: __END__
                   6937: 
1.243     albertel 6938: =pod
                   6939: 
1.191     harris41 6940: =head1 NAME
                   6941: 
1.243     albertel 6942: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 6943: 
                   6944: =head1 SYNOPSIS
                   6945: 
1.243     albertel 6946: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 6947: 
                   6948:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   6949: 
1.243     albertel 6950: Common parameters:
                   6951: 
                   6952: =over 4
                   6953: 
                   6954: =item *
                   6955: 
                   6956: $uname : an internal username (if $cname expecting a course Id specifically)
                   6957: 
                   6958: =item *
                   6959: 
                   6960: $udom : a domain (if $cdom expecting a course's domain specifically)
                   6961: 
                   6962: =item *
                   6963: 
                   6964: $symb : a resource instance identifier
                   6965: 
                   6966: =item *
                   6967: 
                   6968: $namespace : the name of a .db file that contains the data needed or
                   6969: being set.
                   6970: 
                   6971: =back
                   6972: 
1.394     bowersj2 6973: =head1 OVERVIEW
1.191     harris41 6974: 
1.394     bowersj2 6975: lonnet provides subroutines which interact with the
                   6976: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   6977: about classes, users, and resources.
1.243     albertel 6978: 
                   6979: For many of these objects you can also use this to store data about
                   6980: them or modify them in various ways.
1.191     harris41 6981: 
1.394     bowersj2 6982: =head2 Symbs
1.191     harris41 6983: 
1.394     bowersj2 6984: To identify a specific instance of a resource, LON-CAPA uses symbols
                   6985: or "symbs"X<symb>. These identifiers are built from the URL of the
                   6986: map, the resource number of the resource in the map, and the URL of
                   6987: the resource itself. The latter is somewhat redundant, but might help
                   6988: if maps change.
                   6989: 
                   6990: An example is
                   6991: 
                   6992:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   6993: 
                   6994: The respective map entry is
                   6995: 
                   6996:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   6997:   title="Problem 2">
                   6998:  </resource>
                   6999: 
                   7000: Symbs are used by the random number generator, as well as to store and
                   7001: restore data specific to a certain instance of for example a problem.
                   7002: 
                   7003: =head2 Storing And Retrieving Data
                   7004: 
                   7005: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7006: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7007: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7008: is is the non-critical message twin of cstore. These functions are for
                   7009: handlers to store a perl hash to a user's permanent data space in an
                   7010: easy manner, and to retrieve it again on another call. It is expected
                   7011: that a handler would use this once at the beginning to retrieve data,
                   7012: and then again once at the end to send only the new data back.
                   7013: 
                   7014: The data is stored in the user's data directory on the user's
                   7015: homeserver under the ID of the course.
                   7016: 
                   7017: The hash that is returned by restore will have all of the previous
                   7018: value for all of the elements of the hash.
                   7019: 
                   7020: Example:
                   7021: 
                   7022:  #creating a hash
                   7023:  my %hash;
                   7024:  $hash{'foo'}='bar';
                   7025: 
                   7026:  #storing it
                   7027:  &Apache::lonnet::cstore(\%hash);
                   7028: 
                   7029:  #changing a value
                   7030:  $hash{'foo'}='notbar';
                   7031: 
                   7032:  #adding a new value
                   7033:  $hash{'bar'}='foo';
                   7034:  &Apache::lonnet::cstore(\%hash);
                   7035: 
                   7036:  #retrieving the hash
                   7037:  my %history=&Apache::lonnet::restore();
                   7038: 
                   7039:  #print the hash
                   7040:  foreach my $key (sort(keys(%history))) {
                   7041:    print("\%history{$key} = $history{$key}");
                   7042:  }
                   7043: 
                   7044: Will print out:
1.191     harris41 7045: 
1.394     bowersj2 7046:  %history{1:foo} = bar
                   7047:  %history{1:keys} = foo:timestamp
                   7048:  %history{1:timestamp} = 990455579
                   7049:  %history{2:bar} = foo
                   7050:  %history{2:foo} = notbar
                   7051:  %history{2:keys} = foo:bar:timestamp
                   7052:  %history{2:timestamp} = 990455580
                   7053:  %history{bar} = foo
                   7054:  %history{foo} = notbar
                   7055:  %history{timestamp} = 990455580
                   7056:  %history{version} = 2
                   7057: 
                   7058: Note that the special hash entries C<keys>, C<version> and
                   7059: C<timestamp> were added to the hash. C<version> will be equal to the
                   7060: total number of versions of the data that have been stored. The
                   7061: C<timestamp> attribute will be the UNIX time the hash was
                   7062: stored. C<keys> is available in every historical section to list which
                   7063: keys were added or changed at a specific historical revision of a
                   7064: hash.
                   7065: 
                   7066: B<Warning>: do not store the hash that restore returns directly. This
                   7067: will cause a mess since it will restore the historical keys as if the
                   7068: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7069: 
1.394     bowersj2 7070: Calling convention:
1.191     harris41 7071: 
1.394     bowersj2 7072:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7073:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7074: 
1.394     bowersj2 7075: For more detailed information, see lonnet specific documentation.
1.191     harris41 7076: 
1.394     bowersj2 7077: =head1 RETURN MESSAGES
1.191     harris41 7078: 
1.394     bowersj2 7079: =over 4
1.191     harris41 7080: 
1.394     bowersj2 7081: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7082: 
1.394     bowersj2 7083: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7084: when the connection is brought back up
1.191     harris41 7085: 
1.394     bowersj2 7086: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7087: for later delivery
1.191     harris41 7088: 
1.394     bowersj2 7089: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7090: 
1.394     bowersj2 7091: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7092: that was requested
1.191     harris41 7093: 
1.243     albertel 7094: =back
1.191     harris41 7095: 
1.243     albertel 7096: =head1 PUBLIC SUBROUTINES
1.191     harris41 7097: 
1.243     albertel 7098: =head2 Session Environment Functions
1.191     harris41 7099: 
1.243     albertel 7100: =over 4
1.191     harris41 7101: 
1.394     bowersj2 7102: =item * 
                   7103: X<appenv()>
                   7104: B<appenv(%hash)>: the value of %hash is written to
                   7105: the user envirnoment file, and will be restored for each access this
1.620     albertel 7106: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7107: process
1.191     harris41 7108: 
                   7109: =item *
1.394     bowersj2 7110: X<delenv()>
                   7111: B<delenv($regexp)>: removes all items from the session
                   7112: environment file that matches the regular expression in $regexp. The
1.620     albertel 7113: values are also delted from the current processes %env.
1.191     harris41 7114: 
1.243     albertel 7115: =back
                   7116: 
                   7117: =head2 User Information
1.191     harris41 7118: 
1.243     albertel 7119: =over 4
1.191     harris41 7120: 
                   7121: =item *
1.394     bowersj2 7122: X<queryauthenticate()>
                   7123: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7124: authentication scheme
                   7125: 
                   7126: =item *
1.394     bowersj2 7127: X<authenticate()>
                   7128: B<authenticate($uname,$upass,$udom)>: try to
                   7129: authenticate user from domain's lib servers (first use the current
                   7130: one). C<$upass> should be the users password.
1.191     harris41 7131: 
                   7132: =item *
1.394     bowersj2 7133: X<homeserver()>
                   7134: B<homeserver($uname,$udom)>: find the server which has
                   7135: the user's directory and files (there must be only one), this caches
                   7136: the answer, and also caches if there is a borken connection.
1.191     harris41 7137: 
                   7138: =item *
1.394     bowersj2 7139: X<idget()>
                   7140: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7141: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7142: username, and only 1 username per ID in a specific domain) (returns
                   7143: hash: id=>name,id=>name)
1.191     harris41 7144: 
                   7145: =item *
1.394     bowersj2 7146: X<idrget()>
                   7147: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7148: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7149: 
                   7150: =item *
1.394     bowersj2 7151: X<idput()>
                   7152: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7153: 
                   7154: =item *
1.394     bowersj2 7155: X<rolesinit()>
                   7156: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7157: 
                   7158: =item *
1.551     albertel 7159: X<getsection()>
                   7160: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7161: course $cname, return section name/number or '' for "not in course"
                   7162: and '-1' for "no section"
                   7163: 
                   7164: =item *
1.394     bowersj2 7165: X<userenvironment()>
                   7166: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7167: passed in @what from the requested user's environment, returns a hash
                   7168: 
                   7169: =back
                   7170: 
                   7171: =head2 User Roles
                   7172: 
                   7173: =over 4
                   7174: 
                   7175: =item *
                   7176: 
                   7177: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7178: actions
                   7179:  F: full access
                   7180:  U,I,K: authentication modes (cxx only)
                   7181:  '': forbidden
                   7182:  1: user needs to choose course
                   7183:  2: browse allowed
                   7184: 
                   7185: =item *
                   7186: 
                   7187: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7188: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7189: and course level
                   7190: 
                   7191: =item *
                   7192: 
                   7193: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7194: explanation of a user role term
                   7195: 
                   7196: =back
                   7197: 
                   7198: =head2 User Modification
                   7199: 
                   7200: =over 4
                   7201: 
                   7202: =item *
                   7203: 
                   7204: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7205: user for the level given by URL.  Optional start and end dates (leave empty
                   7206: string or zero for "no date")
1.191     harris41 7207: 
                   7208: =item *
                   7209: 
1.243     albertel 7210: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7211: change a users, password, possible return values are: ok,
                   7212: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7213: refused
1.191     harris41 7214: 
                   7215: =item *
                   7216: 
1.243     albertel 7217: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7218: 
                   7219: =item *
                   7220: 
1.243     albertel 7221: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7222: modify user
1.191     harris41 7223: 
                   7224: =item *
                   7225: 
1.286     matthew  7226: modifystudent
                   7227: 
                   7228: modify a students enrollment and identification information.
                   7229: The course id is resolved based on the current users environment.  
                   7230: This means the envoking user must be a course coordinator or otherwise
                   7231: associated with a course.
                   7232: 
1.297     matthew  7233: This call is essentially a wrapper for lonnet::modifyuser and
                   7234: lonnet::modify_student_enrollment
1.286     matthew  7235: 
                   7236: Inputs: 
                   7237: 
                   7238: =over 4
                   7239: 
                   7240: =item B<$udom> Students loncapa domain
                   7241: 
                   7242: =item B<$uname> Students loncapa login name
                   7243: 
                   7244: =item B<$uid> Students id/student number
                   7245: 
                   7246: =item B<$umode> Students authentication mode
                   7247: 
                   7248: =item B<$upass> Students password
                   7249: 
                   7250: =item B<$first> Students first name
                   7251: 
                   7252: =item B<$middle> Students middle name
                   7253: 
                   7254: =item B<$last> Students last name
                   7255: 
                   7256: =item B<$gene> Students generation
                   7257: 
                   7258: =item B<$usec> Students section in course
                   7259: 
                   7260: =item B<$end> Unix time of the roles expiration
                   7261: 
                   7262: =item B<$start> Unix time of the roles start date
                   7263: 
                   7264: =item B<$forceid> If defined, allow $uid to be changed
                   7265: 
                   7266: =item B<$desiredhome> server to use as home server for student
                   7267: 
                   7268: =back
1.297     matthew  7269: 
                   7270: =item *
                   7271: 
                   7272: modify_student_enrollment
                   7273: 
                   7274: Change a students enrollment status in a class.  The environment variable
                   7275: 'role.request.course' must be defined for this function to proceed.
                   7276: 
                   7277: Inputs:
                   7278: 
                   7279: =over 4
                   7280: 
                   7281: =item $udom, students domain
                   7282: 
                   7283: =item $uname, students name
                   7284: 
                   7285: =item $uid, students user id
                   7286: 
                   7287: =item $first, students first name
                   7288: 
                   7289: =item $middle
                   7290: 
                   7291: =item $last
                   7292: 
                   7293: =item $gene
                   7294: 
                   7295: =item $usec
                   7296: 
                   7297: =item $end
                   7298: 
                   7299: =item $start
                   7300: 
                   7301: =back
                   7302: 
1.191     harris41 7303: 
                   7304: =item *
                   7305: 
1.243     albertel 7306: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7307: custom role; give a custom role to a user for the level given by URL.  Specify
                   7308: name and domain of role author, and role name
1.191     harris41 7309: 
                   7310: =item *
                   7311: 
1.243     albertel 7312: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7313: 
                   7314: =item *
                   7315: 
1.243     albertel 7316: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7317: 
                   7318: =back
                   7319: 
                   7320: =head2 Course Infomation
                   7321: 
                   7322: =over 4
1.191     harris41 7323: 
                   7324: =item *
                   7325: 
1.631     albertel 7326: coursedescription($courseid) : returns a hash of information about the
                   7327: specified course id, including all environment settings for the
                   7328: course, the description of the course will be in the hash under the
                   7329: key 'description'
1.191     harris41 7330: 
                   7331: =item *
                   7332: 
1.624     albertel 7333: resdata($name,$domain,$type,@which) : request for current parameter
                   7334: setting for a specific $type, where $type is either 'course' or 'user',
                   7335: @what should be a list of parameters to ask about. This routine caches
                   7336: answers for 5 minutes.
1.243     albertel 7337: 
                   7338: =back
                   7339: 
                   7340: =head2 Course Modification
                   7341: 
                   7342: =over 4
1.191     harris41 7343: 
                   7344: =item *
                   7345: 
1.243     albertel 7346: writecoursepref($courseid,%prefs) : write preferences (environment
                   7347: database) for a course
1.191     harris41 7348: 
                   7349: =item *
                   7350: 
1.243     albertel 7351: createcourse($udom,$description,$url) : make/modify course
                   7352: 
                   7353: =back
                   7354: 
                   7355: =head2 Resource Subroutines
                   7356: 
                   7357: =over 4
1.191     harris41 7358: 
                   7359: =item *
                   7360: 
1.243     albertel 7361: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7362: 
                   7363: =item *
                   7364: 
1.243     albertel 7365: repcopy($filename) : subscribes to the requested file, and attempts to
                   7366: replicate from the owning library server, Might return
1.607     raeburn  7367: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7368: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7369: resource. Expects the local filesystem pathname
                   7370: (/home/httpd/html/res/....)
                   7371: 
                   7372: =back
                   7373: 
                   7374: =head2 Resource Information
                   7375: 
                   7376: =over 4
1.191     harris41 7377: 
                   7378: =item *
                   7379: 
1.243     albertel 7380: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7381: a vairety of different possible values, $varname should be a request
                   7382: string, and the other parameters can be used to specify who and what
                   7383: one is asking about.
                   7384: 
                   7385: Possible values for $varname are environment.lastname (or other item
                   7386: from the envirnment hash), user.name (or someother aspect about the
                   7387: user), resource.0.maxtries (or some other part and parameter of a
                   7388: resource)
1.204     albertel 7389: 
                   7390: =item *
                   7391: 
1.243     albertel 7392: directcondval($number) : get current value of a condition; reads from a state
                   7393: string
1.204     albertel 7394: 
                   7395: =item *
                   7396: 
1.243     albertel 7397: condval($condidx) : value of condition index based on state
1.204     albertel 7398: 
                   7399: =item *
                   7400: 
1.243     albertel 7401: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7402: resource's metadata, $what should be either a specific key, or either
                   7403: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7404: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7405: 
                   7406: this function automatically caches all requests
1.191     harris41 7407: 
                   7408: =item *
                   7409: 
1.243     albertel 7410: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7411: network of library servers; returns file handle of where SQL and regex results
                   7412: will be stored for query
1.191     harris41 7413: 
                   7414: =item *
                   7415: 
1.243     albertel 7416: symbread($filename) : return symbolic list entry (filename argument optional);
                   7417: returns the data handle
1.191     harris41 7418: 
                   7419: =item *
                   7420: 
1.243     albertel 7421: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7422: a possible symb for the URL in $thisfn, and if is an encryypted
                   7423: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7424: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7425: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7426: 
1.191     harris41 7427: 
                   7428: =item *
                   7429: 
1.243     albertel 7430: symbclean($symb) : removes versions numbers from a symb, returns the
                   7431: cleaned symb
1.191     harris41 7432: 
                   7433: =item *
                   7434: 
1.243     albertel 7435: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7436: course map, user must be in a course for it to work.
1.191     harris41 7437: 
                   7438: =item *
                   7439: 
1.243     albertel 7440: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7441: 
                   7442: =item *
                   7443: 
1.243     albertel 7444: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7445: a random seed, all arguments are optional, if they aren't sent it uses the
                   7446: environment to derive them. Note: if symb isn't sent and it can't get one
                   7447: from &symbread it will use the current time as its return value
1.191     harris41 7448: 
                   7449: =item *
                   7450: 
1.243     albertel 7451: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7452: unfakeable, receipt
1.191     harris41 7453: 
                   7454: =item *
                   7455: 
1.620     albertel 7456: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7457: 
                   7458: =item *
                   7459: 
1.243     albertel 7460: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7461: 
                   7462: =item *
                   7463: 
1.243     albertel 7464: 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 7465: 
                   7466: =item *
                   7467: 
1.243     albertel 7468: 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 7469: 
                   7470: =item *
                   7471: 
1.243     albertel 7472: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7473: 
                   7474: =item *
                   7475: 
1.243     albertel 7476: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7477: forcing spreadsheet to reevaluate the resource scores next time.
                   7478: 
                   7479: =back
                   7480: 
                   7481: =head2 Storing/Retreiving Data
                   7482: 
                   7483: =over 4
1.191     harris41 7484: 
                   7485: =item *
                   7486: 
1.243     albertel 7487: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7488: for this url; hashref needs to be given and should be a \%hashname; the
                   7489: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7490: be derived from the env
1.191     harris41 7491: 
                   7492: =item *
                   7493: 
1.243     albertel 7494: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7495: uses critical subroutine
1.191     harris41 7496: 
                   7497: =item *
                   7498: 
1.243     albertel 7499: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7500: all args are optional
1.191     harris41 7501: 
                   7502: =item *
                   7503: 
1.717     albertel 7504: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7505: dumps the complete (or key matching regexp) namespace into a hash
                   7506: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7507: normally &store()ed into
                   7508: 
                   7509: $range should be either an integer '100' (give me the first 100
                   7510:                                            matching records)
                   7511:               or be  two integers sperated by a - with no spaces
                   7512:                  '30-50' (give me the 30th through the 50th matching
                   7513:                           records)
                   7514: 
                   7515: 
                   7516: =item *
                   7517: 
                   7518: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7519: replaces a &store() version of data with a replacement set of data
                   7520: for a particular resource in a namespace passed in the $storehash hash 
                   7521: reference
                   7522: 
                   7523: =item *
                   7524: 
1.243     albertel 7525: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7526: works very similar to store/cstore, but all data is stored in a
                   7527: temporary location and can be reset using tmpreset, $storehash should
                   7528: be a hash reference, returns nothing on success
1.191     harris41 7529: 
                   7530: =item *
                   7531: 
1.243     albertel 7532: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7533: similar to restore, but all data is stored in a temporary location and
                   7534: can be reset using tmpreset. Returns a hash of values on success,
                   7535: error string otherwise.
1.191     harris41 7536: 
                   7537: =item *
                   7538: 
1.243     albertel 7539: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7540: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7541: 
                   7542: =item *
                   7543: 
1.243     albertel 7544: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7545: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7546: 
                   7547: =item *
                   7548: 
1.243     albertel 7549: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7550: namesp ($udom and $uname are optional)
1.191     harris41 7551: 
                   7552: =item *
                   7553: 
1.702     albertel 7554: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7555: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7556: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7557: 
1.702     albertel 7558: $range should be either an integer '100' (give me the first 100
                   7559:                                            matching records)
                   7560:               or be  two integers sperated by a - with no spaces
                   7561:                  '30-50' (give me the 30th through the 50th matching
                   7562:                           records)
1.449     matthew  7563: =item *
                   7564: 
                   7565: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7566: $store can be a scalar, an array reference, or if the amount to be 
                   7567: incremented is > 1, a hash reference.
                   7568: 
                   7569: ($udom and $uname are optional)
1.191     harris41 7570: 
                   7571: =item *
                   7572: 
1.243     albertel 7573: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7574: ($udom and $uname are optional)
1.191     harris41 7575: 
                   7576: =item *
                   7577: 
1.243     albertel 7578: cput($namespace,$storehash,$udom,$uname) : critical put
                   7579: ($udom and $uname are optional)
1.191     harris41 7580: 
                   7581: =item *
                   7582: 
1.243     albertel 7583: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7584: reference filled in from namesp (encrypts the return communication)
                   7585: ($udom and $uname are optional)
1.191     harris41 7586: 
                   7587: =item *
                   7588: 
1.243     albertel 7589: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7590: critical subroutine
                   7591: 
                   7592: =back
                   7593: 
                   7594: =head2 Network Status Functions
                   7595: 
                   7596: =over 4
1.191     harris41 7597: 
                   7598: =item *
                   7599: 
                   7600: dirlist($uri) : return directory list based on URI
                   7601: 
                   7602: =item *
                   7603: 
1.243     albertel 7604: spareserver() : find server with least workload from spare.tab
                   7605: 
                   7606: =back
                   7607: 
                   7608: =head2 Apache Request
                   7609: 
                   7610: =over 4
1.191     harris41 7611: 
                   7612: =item *
                   7613: 
1.243     albertel 7614: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7615: localhost, posts hash
                   7616: 
                   7617: =back
                   7618: 
                   7619: =head2 Data to String to Data
                   7620: 
                   7621: =over 4
1.191     harris41 7622: 
                   7623: =item *
                   7624: 
1.243     albertel 7625: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7626: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7627: 
                   7628: =item *
                   7629: 
1.243     albertel 7630: hashref2str($hashref) : convert a hashref into a string complete with
                   7631: escaping and '=' and '&' separators, supports elements that are
                   7632: arrayrefs and hashrefs
1.191     harris41 7633: 
                   7634: =item *
                   7635: 
1.243     albertel 7636: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7637: with escaping and '&' separators, supports elements that are arrayrefs
                   7638: and hashrefs
1.191     harris41 7639: 
                   7640: =item *
                   7641: 
1.243     albertel 7642: str2hash($string) : convert string to hash using unescaping and
                   7643: splitting on '=' and '&', supports elements that are arrayrefs and
                   7644: hashrefs
1.191     harris41 7645: 
                   7646: =item *
                   7647: 
1.243     albertel 7648: str2array($string) : convert string to hash using unescaping and
                   7649: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7650: 
                   7651: =back
                   7652: 
                   7653: =head2 Logging Routines
                   7654: 
                   7655: =over 4
                   7656: 
                   7657: These routines allow one to make log messages in the lonnet.log and
                   7658: lonnet.perm logfiles.
1.191     harris41 7659: 
                   7660: =item *
                   7661: 
1.243     albertel 7662: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 7663: 
                   7664: =item *
                   7665: 
1.243     albertel 7666: logthis() : append message to the normal lonnet.log file, it gets
                   7667: preiodically rolled over and deleted.
1.191     harris41 7668: 
                   7669: =item *
                   7670: 
1.243     albertel 7671: logperm() : append a permanent message to lonnet.perm.log, this log
                   7672: file never gets deleted by any automated portion of the system, only
                   7673: messages of critical importance should go in here.
                   7674: 
                   7675: =back
                   7676: 
                   7677: =head2 General File Helper Routines
                   7678: 
                   7679: =over 4
1.191     harris41 7680: 
                   7681: =item *
                   7682: 
1.481     raeburn  7683: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7684: (a) files in /uploaded
                   7685:   (i) If a local copy of the file exists - 
                   7686:       compares modification date of local copy with last-modified date for 
                   7687:       definitive version stored on home server for course. If local copy is 
                   7688:       stale, requests a new version from the home server and stores it. 
                   7689:       If the original has been removed from the home server, then local copy 
                   7690:       is unlinked.
                   7691:   (ii) If local copy does not exist -
                   7692:       requests the file from the home server and stores it. 
                   7693:   
                   7694:   If $caller is 'uploadrep':  
                   7695:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7696:     for request for files originally uploaded via DOCS. 
                   7697:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7698:   
                   7699:   Otherwise:
                   7700:      This indicates a call from the content generation phase of the request.
                   7701:      -  returns the entire contents of the file or -1.
                   7702:      
                   7703: (b) files in /res
                   7704:    - returns the entire contents of a file or -1; 
                   7705:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7706: 
1.712     albertel 7707: 
                   7708: =item *
                   7709: 
                   7710: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   7711:                   reference
                   7712: 
                   7713: returns either a stat() list of data about the file or an empty list
                   7714: if the file doesn't exist or couldn't find out about it (connection
                   7715: problems or user unknown)
                   7716: 
1.191     harris41 7717: =item *
                   7718: 
1.243     albertel 7719: filelocation($dir,$file) : returns file system location of a file
                   7720: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7721: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7722: and a file of ../bob will become /a/bob)
1.191     harris41 7723: 
                   7724: =item *
                   7725: 
                   7726: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7727: filelocation except for hrefs
                   7728: 
                   7729: =item *
                   7730: 
                   7731: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7732: 
1.243     albertel 7733: =back
                   7734: 
1.608     albertel 7735: =head2 Usererfile file routines (/uploaded*)
                   7736: 
                   7737: =over 4
                   7738: 
                   7739: =item *
                   7740: 
                   7741: userfileupload(): main rotine for putting a file in a user or course's
                   7742:                   filespace, arguments are,
                   7743: 
1.620     albertel 7744:  formname - required - this is the name of the element in $env where the
1.608     albertel 7745:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7746:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7747:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7748:  coursedoc - if true, store the file in the course of the active role
                   7749:              of the current user
                   7750:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7751:          if undefined, it will be placed in "unknown"
                   7752: 
                   7753:  (This routine calls clean_filename() to remove any dangerous
                   7754:  characters from the filename, and then calls finuserfileupload() to
                   7755:  complete the transaction)
                   7756: 
                   7757:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7758:  and /adm/notfound.html if unsuccessful
                   7759: 
                   7760: =item *
                   7761: 
                   7762: clean_filename(): routine for cleaing a filename up for storage in
                   7763:                  userfile space, argument is:
                   7764: 
                   7765:  filename - proposed filename
                   7766: 
                   7767: returns: the new clean filename
                   7768: 
                   7769: =item *
                   7770: 
                   7771: finishuserfileupload(): routine that creaes and sends the file to
                   7772: userspace, probably shouldn't be called directly
                   7773: 
                   7774:   docuname: username or courseid of destination for the file
                   7775:   docudom: domain of user/course of destination for the file
                   7776:   formname: same as for userfileupload()
                   7777:   fname: filename (inculding subdirectories) for the file
                   7778: 
                   7779:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7780:  and /adm/notfound.html if unsuccessful
                   7781: 
                   7782: =item *
                   7783: 
                   7784: renameuserfile(): renames an existing userfile to a new name
                   7785: 
                   7786:   Args:
                   7787:    docuname: username or courseid of destination for the file
                   7788:    docudom: domain of user/course of destination for the file
                   7789:    old: current file name (including any subdirs under userfiles)
                   7790:    new: desired file name (including any subdirs under userfiles)
                   7791: 
                   7792: =item *
                   7793: 
                   7794: mkdiruserfile(): creates a directory is a userfiles dir
                   7795: 
                   7796:   Args:
                   7797:    docuname: username or courseid of destination for the file
                   7798:    docudom: domain of user/course of destination for the file
                   7799:    dir: dir to create (including any subdirs under userfiles)
                   7800: 
                   7801: =item *
                   7802: 
                   7803: removeuserfile(): removes a file that exists in userfiles
                   7804: 
                   7805:   Args:
                   7806:    docuname: username or courseid of destination for the file
                   7807:    docudom: domain of user/course of destination for the file
                   7808:    fname: filname to delete (including any subdirs under userfiles)
                   7809: 
                   7810: =item *
                   7811: 
                   7812: removeuploadedurl(): convience function for removeuserfile()
                   7813: 
                   7814:   Args:
                   7815:    url:  a full /uploaded/... url to delete
                   7816: 
                   7817: =back
                   7818: 
1.243     albertel 7819: =head2 HTTP Helper Routines
                   7820: 
                   7821: =over 4
                   7822: 
1.191     harris41 7823: =item *
                   7824: 
                   7825: escape() : unpack non-word characters into CGI-compatible hex codes
                   7826: 
                   7827: =item *
                   7828: 
                   7829: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   7830: 
1.243     albertel 7831: =back
                   7832: 
                   7833: =head1 PRIVATE SUBROUTINES
                   7834: 
                   7835: =head2 Underlying communication routines (Shouldn't call)
                   7836: 
                   7837: =over 4
                   7838: 
                   7839: =item *
                   7840: 
                   7841: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   7842: 
                   7843: =item *
                   7844: 
                   7845: reply() : uses subreply to send a message to remote machine, logs all failures
                   7846: 
                   7847: =item *
                   7848: 
                   7849: critical() : passes a critical message to another server; if cannot
                   7850: get through then place message in connection buffer directory and
                   7851: returns con_delayed, if incapable of saving message, returns
                   7852: con_failed
                   7853: 
                   7854: =item *
                   7855: 
                   7856: reconlonc() : tries to reconnect lonc client processes.
                   7857: 
                   7858: =back
                   7859: 
                   7860: =head2 Resource Access Logging
                   7861: 
                   7862: =over 4
                   7863: 
                   7864: =item *
                   7865: 
                   7866: flushcourselogs() : flush (save) buffer logs and access logs
                   7867: 
                   7868: =item *
                   7869: 
                   7870: courselog($what) : save message for course in hash
                   7871: 
                   7872: =item *
                   7873: 
                   7874: courseacclog($what) : save message for course using &courselog().  Perform
                   7875: special processing for specific resource types (problems, exams, quizzes, etc).
                   7876: 
1.191     harris41 7877: =item *
                   7878: 
                   7879: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   7880: as a PerlChildExitHandler
1.243     albertel 7881: 
                   7882: =back
                   7883: 
                   7884: =head2 Other
                   7885: 
                   7886: =over 4
                   7887: 
                   7888: =item *
                   7889: 
                   7890: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 7891: 
                   7892: =back
                   7893: 
                   7894: =cut

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