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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.732   ! albertel    4: # $Id: lonnet.pm,v 1.731 2006/04/26 14:50:56 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.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.599     albertel   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
                     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;
                     55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
                    146: # -------------------------------------------------- Non-critical communication
                    147: sub subreply {
                    148:     my ($cmd,$server)=@_;
1.704     albertel  149:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      150:     #
                    151:     #  With loncnew process trimming, there's a timing hole between lonc server
                    152:     #  process exit and the master server picking up the listen on the AF_UNIX
                    153:     #  socket.  In that time interval, a lock file will exist:
                    154: 
                    155:     my $lockfile=$peerfile.".lock";
                    156:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    157: 	sleep(1);
                    158:     }
                    159:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      160:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      161:     #
1.550     foxr      162:     #   We'll give the connection a few tries before abandoning it.  If
                    163:     #   connection is not possible, we'll con_lost back to the client.
                    164:     #   
                    165:     my $client;
                    166:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    167: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    168: 				      Type    => SOCK_STREAM,
                    169: 				      Timeout => 10);
                    170: 	if($client) {
                    171: 	    last;		# Connected!
                    172: 	}
                    173: 	sleep(1);		# Try again later if failed connection.
                    174:     }
                    175:     my $answer;
                    176:     if ($client) {
1.704     albertel  177: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      178: 	$answer=<$client>;
                    179: 	if (!$answer) { $answer="con_lost"; }
                    180: 	chomp($answer);
                    181:     } else {
                    182: 	$answer = 'con_lost';	# Failed connection.
                    183:     }
1.1       albertel  184:     return $answer;
                    185: }
                    186: 
                    187: sub reply {
                    188:     my ($cmd,$server)=@_;
1.205     www       189:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  190:     my $answer=subreply($cmd,$server);
1.65      www       191:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  192:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       193:                 " $cmd to $server returned $answer</font>");
                    194:     }
1.1       albertel  195:     return $answer;
                    196: }
                    197: 
                    198: # ----------------------------------------------------------- Send USR1 to lonc
                    199: 
                    200: sub reconlonc {
                    201:     my $peerfile=shift;
                    202:     &logthis("Trying to reconnect for $peerfile");
                    203:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  204:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  205: 	my $loncpid=<$fh>;
                    206:         chomp($loncpid);
                    207:         if (kill 0 => $loncpid) {
                    208: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    209:             kill USR1 => $loncpid;
                    210:             sleep 1;
                    211:             if (-e "$peerfile") { return; }
                    212:             &logthis("$peerfile still not there, give it another try");
                    213:             sleep 5;
                    214:             if (-e "$peerfile") { return; }
1.12      www       215:             &logthis(
1.672     albertel  216:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  217:         } else {
1.12      www       218: 	    &logthis(
1.672     albertel  219:                "<font color=\"blue\">WARNING:".
1.12      www       220:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  221:         }
                    222:     } else {
1.672     albertel  223:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  224:     }
                    225: }
                    226: 
                    227: # ------------------------------------------------------ Critical communication
1.12      www       228: 
1.1       albertel  229: sub critical {
                    230:     my ($cmd,$server)=@_;
1.89      www       231:     unless ($hostname{$server}) {
1.672     albertel  232:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       233:                " Critical message to unknown server ($server)</font>");
                    234:         return 'no_such_host';
                    235:     }
1.1       albertel  236:     my $answer=reply($cmd,$server);
                    237:     if ($answer eq 'con_lost') {
                    238: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  239: 	my $answer=reply($cmd,$server);
1.1       albertel  240:         if ($answer eq 'con_lost') {
                    241:             my $now=time;
                    242:             my $middlename=$cmd;
1.5       www       243:             $middlename=substr($middlename,0,16);
1.1       albertel  244:             $middlename=~s/\W//g;
                    245:             my $dfilename=
1.305     www       246:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    247:             $dumpcount++;
1.1       albertel  248:             {
1.448     albertel  249: 		my $dfh;
                    250: 		if (open($dfh,">$dfilename")) {
                    251: 		    print $dfh "$cmd\n"; 
                    252: 		    close($dfh);
                    253: 		}
1.1       albertel  254:             }
                    255:             sleep 2;
                    256:             my $wcmd='';
                    257:             {
1.448     albertel  258: 		my $dfh;
                    259: 		if (open($dfh,"<$dfilename")) {
                    260: 		    $wcmd=<$dfh>; 
                    261: 		    close($dfh);
                    262: 		}
1.1       albertel  263:             }
                    264:             chomp($wcmd);
1.7       www       265:             if ($wcmd eq $cmd) {
1.672     albertel  266: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       267:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  268:                 &logperm("D:$server:$cmd");
                    269: 	        return 'con_delayed';
                    270:             } else {
1.672     albertel  271:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       272:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  273:                 &logperm("F:$server:$cmd");
                    274:                 return 'con_failed';
                    275:             }
                    276:         }
                    277:     }
                    278:     return $answer;
1.405     albertel  279: }
                    280: 
1.374     www       281: # ------------------------------------------- Transfer profile into environment
                    282: 
                    283: sub transfer_profile_to_env {
                    284:     my ($lonidsdir,$handle)=@_;
1.720     albertel  285:     if (!defined($lonidsdir)) {
                    286: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    287:     }
                    288:     if (!defined($handle)) {
                    289:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    290:     }
                    291: 
1.374     www       292:     my @profile;
                    293:     {
1.448     albertel  294: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       295: 	flock($idf,LOCK_SH);
                    296: 	@profile=<$idf>;
1.448     albertel  297: 	close($idf);
1.374     www       298:     }
                    299:     my $envi;
1.433     matthew   300:     my %Remove;
1.374     www       301:     for ($envi=0;$envi<=$#profile;$envi++) {
                    302: 	chomp($profile[$envi]);
1.690     albertel  303: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  304: 	$envname=&unescape($envname);
                    305: 	$envvalue=&unescape($envvalue);
1.619     albertel  306: 	$env{$envname} = $envvalue;
1.433     matthew   307:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    308:             if ($time < time-300) {
                    309:                 $Remove{$key}++;
                    310:             }
                    311:         }
                    312:     }
1.619     albertel  313:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   314:     foreach my $expired_key (keys(%Remove)) {
                    315:         &delenv($expired_key);
1.374     www       316:     }
1.1       albertel  317: }
                    318: 
1.5       www       319: # ---------------------------------------------------------- Append Environment
                    320: 
                    321: sub appenv {
1.6       www       322:     my %newenv=@_;
1.692     albertel  323:     foreach my $key (keys(%newenv)) {
                    324: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  325:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  326:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       327:                 .'</font>');
1.692     albertel  328: 	    delete($newenv{$key});
1.35      www       329:         } else {
1.692     albertel  330:             $env{$key}=$newenv{$key};
1.35      www       331:         }
1.191     harris41  332:     }
1.95      www       333: 
                    334:     my $lockfh;
1.620     albertel  335:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  336: 	return 'error: '.$!;
1.95      www       337:     }
                    338:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  339:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       340:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  341:          close($lockfh);
1.95      www       342:          return 'error: '.$!;
                    343:     }
                    344: 
1.6       www       345:     my @oldenv;
                    346:     {
1.448     albertel  347: 	my $fh;
1.620     albertel  348: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  349: 	    return 'error: '.$!;
                    350: 	}
                    351: 	@oldenv=<$fh>;
                    352: 	close($fh);
1.6       www       353:     }
                    354:     for (my $i=0; $i<=$#oldenv; $i++) {
                    355:         chomp($oldenv[$i]);
1.9       www       356:         if ($oldenv[$i] ne '') {
1.690     albertel  357: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.726     albertel  358: 	    $name=&unescape($name);
                    359: 	    $value=&unescape($value);
1.448     albertel  360: 	    unless (defined($newenv{$name})) {
                    361: 		$newenv{$name}=$value;
                    362: 	    }
1.9       www       363:         }
1.6       www       364:     }
                    365:     {
1.448     albertel  366: 	my $fh;
1.620     albertel  367: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  368: 	    return 'error';
                    369: 	}
                    370: 	my $newname;
                    371: 	foreach $newname (keys %newenv) {
1.726     albertel  372: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
1.448     albertel  373: 	}
                    374: 	close($fh);
1.56      www       375:     }
1.448     albertel  376: 	
                    377:     close($lockfh);
1.56      www       378:     return 'ok';
                    379: }
                    380: # ----------------------------------------------------- Delete from Environment
                    381: 
                    382: sub delenv {
                    383:     my $delthis=shift;
                    384:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  385:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       386:                 "Attempt to delete from environment ".$delthis);
                    387:         return 'error';
                    388:     }
                    389:     my @oldenv;
                    390:     {
1.448     albertel  391: 	my $fh;
1.620     albertel  392: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  393: 	    return 'error';
                    394: 	}
                    395: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  396: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  397: 		     'Could not obtain shared lock in delenv: '.$!);
                    398: 	    close($fh);
                    399: 	    return 'error: '.$!;
                    400: 	}
                    401: 	@oldenv=<$fh>;
                    402: 	close($fh);
1.56      www       403:     }
                    404:     {
1.448     albertel  405: 	my $fh;
1.620     albertel  406: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  407: 	    return 'error';
                    408: 	}
                    409: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  410: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  411: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    412: 	    close($fh);
                    413: 	    return 'error: '.$!;
                    414: 	}
1.692     albertel  415: 	foreach my $cur_key (@oldenv) {
1.726     albertel  416: 	    my $unescaped_cur_key = &unescape($cur_key);
                    417: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    418:                 my ($key) = split('=',$cur_key,2);
                    419: 		$key = &unescape($key);
1.619     albertel  420:                 delete($env{$key});
1.473     matthew   421:             } else {
1.692     albertel  422:                 print $fh $cur_key; 
1.473     matthew   423:             }
1.448     albertel  424: 	}
                    425: 	close($fh);
1.5       www       426:     }
                    427:     return 'ok';
1.369     albertel  428: }
                    429: 
                    430: # ------------------------------------------ Find out current server userload
                    431: # there is a copy in lond
                    432: sub userload {
                    433:     my $numusers=0;
                    434:     {
                    435: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    436: 	my $filename;
                    437: 	my $curtime=time;
                    438: 	while ($filename=readdir(LONIDS)) {
                    439: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  440: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  441: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  442: 	}
                    443: 	closedir(LONIDS);
                    444:     }
                    445:     my $userloadpercent=0;
                    446:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    447:     if ($maxuserload) {
1.371     albertel  448: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  449:     }
1.372     albertel  450:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  451:     return $userloadpercent;
1.283     www       452: }
                    453: 
                    454: # ------------------------------------------ Fight off request when overloaded
                    455: 
                    456: sub overloaderror {
                    457:     my ($r,$checkserver)=@_;
                    458:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    459:     my $loadavg;
                    460:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  461:        open(my $loadfile,'/proc/loadavg');
1.283     www       462:        $loadavg=<$loadfile>;
                    463:        $loadavg =~ s/\s.*//g;
1.285     matthew   464:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  465:        close($loadfile);
1.283     www       466:     } else {
                    467:        $loadavg=&reply('load',$checkserver);
                    468:     }
1.285     matthew   469:     my $overload=$loadavg-100;
1.283     www       470:     if ($overload>0) {
1.285     matthew   471: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       472:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       473:         return 413;
1.283     www       474:     }    
                    475:     return '';
1.5       www       476: }
1.1       albertel  477: 
                    478: # ------------------------------ Find server with least workload from spare.tab
1.11      www       479: 
1.1       albertel  480: sub spareserver {
1.670     albertel  481:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  482:     my $tryserver;
                    483:     my $spareserver='';
1.370     albertel  484:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    485:     my $lowestserver=$loadpercent > $userloadpercent?
                    486: 	             $loadpercent :  $userloadpercent;
1.670     albertel  487:     foreach $tryserver (keys(%spareid)) {
                    488: 	my $loadans=&reply('load',$tryserver);
                    489: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  490: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    491: 	    next; #didn't get a number from the server
                    492: 	}
                    493: 	my $answer;
                    494: 	if ($loadans =~ /\d/) {
                    495: 	    if ($userloadans =~ /\d/) {
                    496: 		#both are numbers, pick the bigger one
                    497: 		$answer=$loadans > $userloadans?
                    498: 		    $loadans :  $userloadans;
                    499: 	    } else {
                    500: 		$answer = $loadans;
                    501: 	    }
                    502: 	} else {
                    503: 	    $answer = $userloadans;
                    504: 	}
                    505: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  506: 	    if ($want_server_name) {
                    507: 		$spareserver=$tryserver;
                    508: 	    } else {
                    509: 		$spareserver="http://$hostname{$tryserver}";
                    510: 	    }
1.411     albertel  511: 	    $lowestserver=$answer;
                    512: 	}
1.370     albertel  513:     }
1.1       albertel  514:     return $spareserver;
1.202     matthew   515: }
                    516: 
                    517: # --------------------------------------------- Try to change a user's password
                    518: 
                    519: sub changepass {
                    520:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    521:     $currentpass = &escape($currentpass);
                    522:     $newpass     = &escape($newpass);
                    523:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    524: 		       $server);
                    525:     if (! $answer) {
                    526: 	&logthis("No reply on password change request to $server ".
                    527: 		 "by $uname in domain $udom.");
                    528:     } elsif ($answer =~ "^ok") {
                    529:         &logthis("$uname in $udom successfully changed their password ".
                    530: 		 "on $server.");
                    531:     } elsif ($answer =~ "^pwchange_failure") {
                    532: 	&logthis("$uname in $udom was unable to change their password ".
                    533: 		 "on $server.  The action was blocked by either lcpasswd ".
                    534: 		 "or pwchange");
                    535:     } elsif ($answer =~ "^non_authorized") {
                    536:         &logthis("$uname in $udom did not get their password correct when ".
                    537: 		 "attempting to change it on $server.");
                    538:     } elsif ($answer =~ "^auth_mode_error") {
                    539:         &logthis("$uname in $udom attempted to change their password despite ".
                    540: 		 "not being locally or internally authenticated on $server.");
                    541:     } elsif ($answer =~ "^unknown_user") {
                    542:         &logthis("$uname in $udom attempted to change their password ".
                    543: 		 "on $server but were unable to because $server is not ".
                    544: 		 "their home server.");
                    545:     } elsif ($answer =~ "^refused") {
                    546: 	&logthis("$server refused to change $uname in $udom password because ".
                    547: 		 "it was sent an unencrypted request to change the password.");
                    548:     }
                    549:     return $answer;
1.1       albertel  550: }
                    551: 
1.169     harris41  552: # ----------------------- Try to determine user's current authentication scheme
                    553: 
                    554: sub queryauthenticate {
                    555:     my ($uname,$udom)=@_;
1.456     albertel  556:     my $uhome=&homeserver($uname,$udom);
                    557:     if (!$uhome) {
                    558: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    559: 	return 'no_host';
                    560:     }
                    561:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    562:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    563: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  564:     }
1.456     albertel  565:     return $answer;
1.169     harris41  566: }
                    567: 
1.1       albertel  568: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       569: 
1.1       albertel  570: sub authenticate {
                    571:     my ($uname,$upass,$udom)=@_;
1.12      www       572:     $upass=escape($upass);
1.199     www       573:     $uname=~s/\W//g;
1.471     albertel  574:     my $uhome=&homeserver($uname,$udom);
                    575:     if (!$uhome) {
                    576: 	&logthis("User $uname at $udom is unknown in authenticate");
                    577: 	return 'no_host';
1.1       albertel  578:     }
1.471     albertel  579:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    580:     if ($answer eq 'authorized') {
                    581: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    582: 	return $uhome; 
                    583:     }
                    584:     if ($answer eq 'non_authorized') {
                    585: 	&logthis("User $uname at $udom rejected by $uhome");
                    586: 	return 'no_host'; 
1.9       www       587:     }
1.471     albertel  588:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  589:     return 'no_host';
                    590: }
                    591: 
                    592: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       593: 
1.599     albertel  594: my %homecache;
1.1       albertel  595: sub homeserver {
1.230     stredwic  596:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  597:     my $index="$uname:$udom";
1.426     albertel  598: 
1.599     albertel  599:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  600:     my $tryserver;
                    601:     foreach $tryserver (keys %libserv) {
1.230     stredwic  602:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  603: 		 exists($badServerCache{$tryserver}));
1.1       albertel  604: 	if ($hostdom{$tryserver} eq $udom) {
                    605:            my $answer=reply("home:$udom:$uname",$tryserver);
                    606:            if ($answer eq 'found') { 
1.599     albertel  607: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  608:            } elsif ($answer eq 'no_host') {
                    609: 	       $badServerCache{$tryserver}=1;
1.221     matthew   610:            }
1.1       albertel  611:        }
                    612:     }    
                    613:     return 'no_host';
1.70      www       614: }
                    615: 
                    616: # ------------------------------------- Find the usernames behind a list of IDs
                    617: 
                    618: sub idget {
                    619:     my ($udom,@ids)=@_;
                    620:     my %returnhash=();
                    621:     
                    622:     my $tryserver;
                    623:     foreach $tryserver (keys %libserv) {
                    624:        if ($hostdom{$tryserver} eq $udom) {
                    625: 	  my $idlist=join('&',@ids);
                    626:           $idlist=~tr/A-Z/a-z/; 
                    627: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    628:           my @answer=();
1.76      www       629:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       630: 	      @answer=split(/\&/,$reply);
                    631:           }                    ;
                    632:           my $i;
                    633:           for ($i=0;$i<=$#ids;$i++) {
                    634:               if ($answer[$i]) {
                    635: 		  $returnhash{$ids[$i]}=$answer[$i];
                    636:               } 
                    637:           }
                    638:        }
                    639:     }    
                    640:     return %returnhash;
                    641: }
                    642: 
                    643: # ------------------------------------- Find the IDs behind a list of usernames
                    644: 
                    645: sub idrget {
                    646:     my ($udom,@unames)=@_;
                    647:     my %returnhash=();
1.191     harris41  648:     foreach (@unames) {
1.70      www       649:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  650:     }
1.70      www       651:     return %returnhash;
                    652: }
                    653: 
                    654: # ------------------------------- Store away a list of names and associated IDs
                    655: 
                    656: sub idput {
                    657:     my ($udom,%ids)=@_;
                    658:     my %servers=();
1.191     harris41  659:     foreach (keys %ids) {
1.487     albertel  660: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       661:         my $uhom=&homeserver($_,$udom);
                    662:         if ($uhom ne 'no_host') {
                    663:             my $id=&escape($ids{$_});
                    664:             $id=~tr/A-Z/a-z/;
                    665:             my $unam=&escape($_);
                    666: 	    if ($servers{$uhom}) {
                    667: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    668:             } else {
                    669:                 $servers{$uhom}=$id.'='.$unam;
                    670:             }
                    671:         }
1.191     harris41  672:     }
                    673:     foreach (keys %servers) {
1.70      www       674:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  675:     }
1.344     www       676: }
                    677: 
                    678: # --------------------------------------------------- Assign a key to a student
                    679: 
                    680: sub assign_access_key {
1.364     www       681: #
                    682: # a valid key looks like uname:udom#comments
                    683: # comments are being appended
                    684: #
1.498     www       685:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    686:     $kdom=
1.620     albertel  687:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       688:     $knum=
1.620     albertel  689:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       690:     $cdom=
1.620     albertel  691:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       692:     $cnum=
1.620     albertel  693:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    694:     $udom=$env{'user.name'} unless (defined($udom));
                    695:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       696:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       697:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  698:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       699:                                                   # assigned to this person
                    700:                                                   # - this should not happen,
1.345     www       701:                                                   # unless something went wrong
                    702:                                                   # the first time around
                    703: # ready to assign
1.364     www       704:         $logentry=$1.'; '.$logentry;
1.496     www       705:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       706:                                                  $kdom,$knum) eq 'ok') {
1.345     www       707: # key now belongs to user
1.346     www       708: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       709:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    710:                 &appenv('environment.'.$envkey => $ckey);
                    711:                 return 'ok';
                    712:             } else {
                    713:                 return 
                    714:   'error: Count not permanently assign key, will need to be re-entered later.';
                    715: 	    }
                    716:         } else {
                    717:             return 'error: Could not assign key, try again later.';
                    718:         }
1.364     www       719:     } elsif (!$existing{$ckey}) {
1.345     www       720: # the key does not exist
                    721: 	return 'error: The key does not exist';
                    722:     } else {
                    723: # the key is somebody else's
                    724: 	return 'error: The key is already in use';
                    725:     }
1.344     www       726: }
                    727: 
1.364     www       728: # ------------------------------------------ put an additional comment on a key
                    729: 
                    730: sub comment_access_key {
                    731: #
                    732: # a valid key looks like uname:udom#comments
                    733: # comments are being appended
                    734: #
                    735:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    736:     $cdom=
1.620     albertel  737:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       738:     $cnum=
1.620     albertel  739:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       740:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    741:     if ($existing{$ckey}) {
                    742:         $existing{$ckey}.='; '.$logentry;
                    743: # ready to assign
1.367     www       744:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       745:                                                  $cdom,$cnum) eq 'ok') {
                    746: 	    return 'ok';
                    747:         } else {
                    748: 	    return 'error: Count not store comment.';
                    749:         }
                    750:     } else {
                    751: # the key does not exist
                    752: 	return 'error: The key does not exist';
                    753:     }
                    754: }
                    755: 
1.344     www       756: # ------------------------------------------------------ Generate a set of keys
                    757: 
                    758: sub generate_access_keys {
1.364     www       759:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       760:     $cdom=
1.620     albertel  761:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       762:     $cnum=
1.620     albertel  763:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       764:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       765:     unless (($cdom) && ($cnum)) { return 0; }
                    766:     if ($number>10000) { return 0; }
                    767:     sleep(2); # make sure don't get same seed twice
                    768:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    769:     my $total=0;
                    770:     for (my $i=1;$i<=$number;$i++) {
                    771:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    772:                   sprintf("%lx",int(100000*rand)).'-'.
                    773:                   sprintf("%lx",int(100000*rand));
                    774:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    775:        $newkey=~s/0/h/g; # and also 0 and O
                    776:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    777:        if ($existing{$newkey}) {
                    778:            $i--;
                    779:        } else {
1.364     www       780: 	  if (&put('accesskeys',
                    781:               { $newkey => '# generated '.localtime().
1.620     albertel  782:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       783:                            '; '.$logentry },
                    784: 		   $cdom,$cnum) eq 'ok') {
1.344     www       785:               $total++;
                    786: 	  }
                    787:        }
                    788:     }
1.620     albertel  789:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       790:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    791:     return $total;
                    792: }
                    793: 
                    794: # ------------------------------------------------------- Validate an accesskey
                    795: 
                    796: sub validate_access_key {
                    797:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    798:     $cdom=
1.620     albertel  799:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       800:     $cnum=
1.620     albertel  801:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    802:     $udom=$env{'user.domain'} unless (defined($udom));
                    803:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       804:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  805:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       806: }
                    807: 
                    808: # ------------------------------------- Find the section of student in a course
1.652     albertel  809: sub devalidate_getsection_cache {
                    810:     my ($udom,$unam,$courseid)=@_;
                    811:     $courseid=~s/\_/\//g;
                    812:     $courseid=~s/^(\w)/\/$1/;
                    813:     my $hashid="$udom:$unam:$courseid";
                    814:     &devalidate_cache_new('getsection',$hashid);
                    815: }
1.298     matthew   816: 
                    817: sub getsection {
                    818:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  819:     my $cachetime=1800;
1.298     matthew   820:     $courseid=~s/\_/\//g;
                    821:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  822: 
                    823:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  824:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  825:     if (defined($cached)) { return $result; }
                    826: 
1.298     matthew   827:     my %Pending; 
                    828:     my %Expired;
                    829:     #
                    830:     # Each role can either have not started yet (pending), be active, 
                    831:     #    or have expired.
                    832:     #
                    833:     # If there is an active role, we are done.
                    834:     #
                    835:     # If there is more than one role which has not started yet, 
                    836:     #     choose the one which will start sooner
                    837:     # If there is one role which has not started yet, return it.
                    838:     #
                    839:     # If there is more than one expired role, choose the one which ended last.
                    840:     # If there is a role which has expired, return it.
                    841:     #
                    842:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    843:                         &homeserver($unam,$udom)))) {
                    844:         my ($key,$value)=split(/\=/,$_);
                    845:         $key=&unescape($key);
1.479     albertel  846:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   847:         my $section=$1;
                    848:         if ($key eq $courseid.'_st') { $section=''; }
                    849:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    850:         my $now=time;
1.548     albertel  851:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   852:             $Expired{$end}=$section;
                    853:             next;
                    854:         }
1.548     albertel  855:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   856:             $Pending{$start}=$section;
                    857:             next;
                    858:         }
1.599     albertel  859:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   860:     }
                    861:     #
                    862:     # Presumedly there will be few matching roles from the above
                    863:     # loop and the sorting time will be negligible.
                    864:     if (scalar(keys(%Pending))) {
                    865:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  866:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   867:     } 
                    868:     if (scalar(keys(%Expired))) {
                    869:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    870:         my $time = pop(@sorted);
1.599     albertel  871:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   872:     }
1.599     albertel  873:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   874: }
1.70      www       875: 
1.599     albertel  876: sub save_cache {
                    877:     &purge_remembered();
1.722     albertel  878:     #&Apache::loncommon::validate_page();
1.620     albertel  879:     undef(%env);
1.599     albertel  880: }
1.452     albertel  881: 
1.599     albertel  882: my $to_remember=-1;
                    883: my %remembered;
                    884: my %accessed;
                    885: my $kicks=0;
                    886: my $hits=0;
                    887: sub devalidate_cache_new {
                    888:     my ($name,$id,$debug) = @_;
                    889:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    890:     $id=&escape($name.':'.$id);
                    891:     $memcache->delete($id);
                    892:     delete($remembered{$id});
                    893:     delete($accessed{$id});
                    894: }
                    895: 
                    896: sub is_cached_new {
                    897:     my ($name,$id,$debug) = @_;
                    898:     $id=&escape($name.':'.$id);
                    899:     if (exists($remembered{$id})) {
                    900: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    901: 	$accessed{$id}=[&gettimeofday()];
                    902: 	$hits++;
                    903: 	return ($remembered{$id},1);
                    904:     }
                    905:     my $value = $memcache->get($id);
                    906:     if (!(defined($value))) {
                    907: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  908: 	return (undef,undef);
1.416     albertel  909:     }
1.599     albertel  910:     if ($value eq '__undef__') {
                    911: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    912: 	$value=undef;
                    913:     }
                    914:     &make_room($id,$value,$debug);
                    915:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    916:     return ($value,1);
                    917: }
                    918: 
                    919: sub do_cache_new {
                    920:     my ($name,$id,$value,$time,$debug) = @_;
                    921:     $id=&escape($name.':'.$id);
                    922:     my $setvalue=$value;
                    923:     if (!defined($setvalue)) {
                    924: 	$setvalue='__undef__';
                    925:     }
1.623     albertel  926:     if (!defined($time) ) {
                    927: 	$time=600;
                    928:     }
1.599     albertel  929:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  930:     $memcache->set($id,$setvalue,$time);
                    931:     # need to make a copy of $value
                    932:     #&make_room($id,$value,$debug);
1.599     albertel  933:     return $value;
                    934: }
                    935: 
                    936: sub make_room {
                    937:     my ($id,$value,$debug)=@_;
                    938:     $remembered{$id}=$value;
                    939:     if ($to_remember<0) { return; }
                    940:     $accessed{$id}=[&gettimeofday()];
                    941:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    942:     my $to_kick;
                    943:     my $max_time=0;
                    944:     foreach my $other (keys(%accessed)) {
                    945: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    946: 	    $to_kick=$other;
                    947: 	    $max_time=&tv_interval($accessed{$other});
                    948: 	}
                    949:     }
                    950:     delete($remembered{$to_kick});
                    951:     delete($accessed{$to_kick});
                    952:     $kicks++;
                    953:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  954:     return;
                    955: }
                    956: 
1.599     albertel  957: sub purge_remembered {
1.604     albertel  958:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    959:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  960:     undef(%remembered);
                    961:     undef(%accessed);
1.428     albertel  962: }
1.70      www       963: # ------------------------------------- Read an entry from a user's environment
                    964: 
                    965: sub userenvironment {
                    966:     my ($udom,$unam,@what)=@_;
                    967:     my %returnhash=();
                    968:     my @answer=split(/\&/,
                    969:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    970:                       &homeserver($unam,$udom)));
                    971:     my $i;
                    972:     for ($i=0;$i<=$#what;$i++) {
                    973: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    974:     }
                    975:     return %returnhash;
1.1       albertel  976: }
                    977: 
1.617     albertel  978: # ---------------------------------------------------------- Get a studentphoto
                    979: sub studentphoto {
                    980:     my ($udom,$unam,$ext) = @_;
                    981:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   982:     if (defined($env{'request.course.id'})) {
1.708     raeburn   983:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   984:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    985:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    986:             } else {
                    987:                 my ($result,$perm_reqd)=
1.707     albertel  988: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   989:                 if ($result eq 'ok') {
                    990:                     if (!($perm_reqd eq 'yes')) {
                    991:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    992:                     }
                    993:                 }
                    994:             }
                    995:         }
                    996:     } else {
                    997:         my ($result,$perm_reqd) = 
1.707     albertel  998: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   999:         if ($result eq 'ok') {
                   1000:             if (!($perm_reqd eq 'yes')) {
                   1001:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1002:             }
                   1003:         }
                   1004:     }
                   1005:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1006: }
                   1007: 
                   1008: sub retrievestudentphoto {
                   1009:     my ($udom,$unam,$ext,$type) = @_;
                   1010:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1011:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1012:     if ($ret eq 'ok') {
                   1013:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1014:         if ($type eq 'thumbnail') {
                   1015:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1016:         }
                   1017:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1018:         return $tokenurl;
                   1019:     } else {
                   1020:         if ($type eq 'thumbnail') {
                   1021:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1022:         } else { 
                   1023:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1024:         }
1.617     albertel 1025:     }
                   1026: }
                   1027: 
1.263     www      1028: # -------------------------------------------------------------------- New chat
                   1029: 
                   1030: sub chatsend {
1.724     raeburn  1031:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1032:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1033:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1034:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1035:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1036: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1037: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1038: }
                   1039: 
                   1040: # ------------------------------------------ Find current version of a resource
                   1041: 
                   1042: sub getversion {
                   1043:     my $fname=&clutter(shift);
                   1044:     unless ($fname=~/^\/res\//) { return -1; }
                   1045:     return &currentversion(&filelocation('',$fname));
                   1046: }
                   1047: 
                   1048: sub currentversion {
                   1049:     my $fname=shift;
1.599     albertel 1050:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1051:     if (defined($cached)) { return $result; }
1.292     www      1052:     my $author=$fname;
                   1053:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1054:     my ($udom,$uname)=split(/\//,$author);
                   1055:     my $home=homeserver($uname,$udom);
                   1056:     if ($home eq 'no_host') { 
                   1057:         return -1; 
                   1058:     }
                   1059:     my $answer=reply("currentversion:$fname",$home);
                   1060:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1061: 	return -1;
                   1062:     }
1.599     albertel 1063:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1064: }
                   1065: 
1.1       albertel 1066: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1067: 
1.1       albertel 1068: sub subscribe {
                   1069:     my $fname=shift;
1.312     www      1070:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1071:     $fname=~s/[\n\r]//g;
1.1       albertel 1072:     my $author=$fname;
                   1073:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1074:     my ($udom,$uname)=split(/\//,$author);
                   1075:     my $home=homeserver($uname,$udom);
1.335     albertel 1076:     if ($home eq 'no_host') {
                   1077:         return 'not_found';
1.1       albertel 1078:     }
                   1079:     my $answer=reply("sub:$fname",$home);
1.64      www      1080:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1081: 	$answer.=' by '.$home;
                   1082:     }
1.1       albertel 1083:     return $answer;
                   1084: }
                   1085:     
1.8       www      1086: # -------------------------------------------------------------- Replicate file
                   1087: 
                   1088: sub repcopy {
                   1089:     my $filename=shift;
1.23      www      1090:     $filename=~s/\/+/\//g;
1.607     raeburn  1091:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1092:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1093:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1094: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1095: 	return &repcopy_userfile($filename);
                   1096:     }
1.532     albertel 1097:     $filename=~s/[\n\r]//g;
1.8       www      1098:     my $transname="$filename.in.transfer";
1.607     raeburn  1099:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1100:     my $remoteurl=subscribe($filename);
1.64      www      1101:     if ($remoteurl =~ /^con_lost by/) {
                   1102: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1103:            return 'unavailable';
1.8       www      1104:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1105: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1106: 	   return 'not_found';
1.64      www      1107:     } elsif ($remoteurl =~ /^rejected by/) {
                   1108: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1109:            return 'forbidden';
1.20      www      1110:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1111:            return 'ok';
1.8       www      1112:     } else {
1.290     www      1113:         my $author=$filename;
                   1114:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1115:         my ($udom,$uname)=split(/\//,$author);
                   1116:         my $home=homeserver($uname,$udom);
                   1117:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1118:            my @parts=split(/\//,$filename);
                   1119:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1120:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1121:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1122: 	       return 'bad_request';
1.8       www      1123:            }
                   1124:            my $count;
                   1125:            for ($count=5;$count<$#parts;$count++) {
                   1126:                $path.="/$parts[$count]";
                   1127:                if ((-e $path)!=1) {
                   1128: 		   mkdir($path,0777);
                   1129:                }
                   1130:            }
                   1131:            my $ua=new LWP::UserAgent;
                   1132:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1133:            my $response=$ua->request($request,$transname);
                   1134:            if ($response->is_error()) {
                   1135: 	       unlink($transname);
                   1136:                my $message=$response->status_line;
1.672     albertel 1137:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1138:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1139:                return 'unavailable';
1.8       www      1140:            } else {
1.16      www      1141: 	       if ($remoteurl!~/\.meta$/) {
                   1142:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1143:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1144:                   if ($mresponse->is_error()) {
                   1145: 		      unlink($filename.'.meta');
                   1146:                       &logthis(
1.672     albertel 1147:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1148:                   }
                   1149: 	       }
1.8       www      1150:                rename($transname,$filename);
1.607     raeburn  1151:                return 'ok';
1.8       www      1152:            }
1.290     www      1153:        }
1.8       www      1154:     }
1.330     www      1155: }
                   1156: 
                   1157: # ------------------------------------------------ Get server side include body
                   1158: sub ssi_body {
1.381     albertel 1159:     my ($filelink,%form)=@_;
1.606     matthew  1160:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1161:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1162:     }
1.330     www      1163:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1164:                                      &ssi($filelink,%form));
1.565     albertel 1165:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1166:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1167:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1168:     return $output;
1.8       www      1169: }
                   1170: 
1.15      www      1171: # --------------------------------------------------------- Server Side Include
                   1172: 
                   1173: sub ssi {
                   1174: 
1.23      www      1175:     my ($fn,%form)=@_;
1.15      www      1176: 
                   1177:     my $ua=new LWP::UserAgent;
1.23      www      1178:     
                   1179:     my $request;
1.711     albertel 1180: 
                   1181:     $form{'no_update_last_known'}=1;
                   1182: 
1.23      www      1183:     if (%form) {
                   1184:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1185:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1186:     } else {
                   1187:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1188:     }
                   1189: 
1.15      www      1190:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1191:     my $response=$ua->request($request);
                   1192: 
1.324     www      1193:     return $response->content;
                   1194: }
                   1195: 
                   1196: sub externalssi {
                   1197:     my ($url)=@_;
                   1198:     my $ua=new LWP::UserAgent;
                   1199:     my $request=new HTTP::Request('GET',$url);
                   1200:     my $response=$ua->request($request);
1.15      www      1201:     return $response->content;
                   1202: }
1.254     www      1203: 
1.492     albertel 1204: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1205: 
                   1206: sub allowuploaded {
                   1207:     my ($srcurl,$url)=@_;
                   1208:     $url=&clutter(&declutter($url));
                   1209:     my $dir=$url;
                   1210:     $dir=~s/\/[^\/]+$//;
                   1211:     my %httpref=();
                   1212:     my $httpurl=&hreflocation('',$url);
                   1213:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1214:     &Apache::lonnet::appenv(%httpref);
1.254     www      1215: }
1.477     raeburn  1216: 
1.478     albertel 1217: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1218: # input: action, courseID, current domain, intended
1.637     raeburn  1219: #        path to file, source of file, instruction to parse file for objects,
                   1220: #        ref to hash for embedded objects,
                   1221: #        ref to hash for codebase of java objects.
                   1222: #
1.485     raeburn  1223: # output: url to file (if action was uploaddoc), 
                   1224: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1225: #
1.478     albertel 1226: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1227: # course.
1.477     raeburn  1228: #
1.478     albertel 1229: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1230: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1231: #          course's home server.
1.477     raeburn  1232: #
1.478     albertel 1233: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1234: #          be copied from $source (current location) to 
                   1235: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1236: #         and will then be copied to
                   1237: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1238: #         course's home server.
1.485     raeburn  1239: #
1.481     raeburn  1240: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1241: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1242: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1243: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1244: #         in course's home server.
1.637     raeburn  1245: #
1.477     raeburn  1246: 
                   1247: sub process_coursefile {
1.638     albertel 1248:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1249:     my $fetchresult;
1.638     albertel 1250:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1251:     if ($action eq 'propagate') {
1.638     albertel 1252:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1253: 			     $home);
1.481     raeburn  1254:     } else {
1.477     raeburn  1255:         my $fpath = '';
                   1256:         my $fname = $file;
1.478     albertel 1257:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1258:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1259:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1260:         if ($action eq 'copy') {
                   1261:             if ($source eq '') {
                   1262:                 $fetchresult = 'no source file';
                   1263:                 return $fetchresult;
                   1264:             } else {
                   1265:                 my $destination = $filepath.'/'.$fname;
                   1266:                 rename($source,$destination);
                   1267:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1268:                                  $home);
1.481     raeburn  1269:             }
                   1270:         } elsif ($action eq 'uploaddoc') {
                   1271:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1272:             print $fh $env{'form.'.$source};
1.481     raeburn  1273:             close($fh);
1.637     raeburn  1274:             if ($parser eq 'parse') {
                   1275:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1276:                 unless ($parse_result eq 'ok') {
                   1277:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1278:                 }
                   1279:             }
1.477     raeburn  1280:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1281:                                  $home);
1.481     raeburn  1282:             if ($fetchresult eq 'ok') {
                   1283:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1284:             } else {
                   1285:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1286:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1287:                 return '/adm/notfound.html';
                   1288:             }
1.477     raeburn  1289:         }
                   1290:     }
1.485     raeburn  1291:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1292:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1293:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1294:     }
                   1295:     return $fetchresult;
                   1296: }
                   1297: 
1.637     raeburn  1298: sub build_filepath {
                   1299:     my ($fpath) = @_;
                   1300:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1301:     unless ($fpath eq '') {
                   1302:         my @parts=split('/',$fpath);
                   1303:         foreach my $part (@parts) {
                   1304:             $filepath.= '/'.$part;
                   1305:             if ((-e $filepath)!=1) {
                   1306:                 mkdir($filepath,0777);
                   1307:             }
                   1308:         }
                   1309:     }
                   1310:     return $filepath;
                   1311: }
                   1312: 
                   1313: sub store_edited_file {
1.638     albertel 1314:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1315:     my $file = $primary_url;
                   1316:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1317:     my $fpath = '';
                   1318:     my $fname = $file;
                   1319:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1320:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1321:     my $filepath = &build_filepath($fpath);
                   1322:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1323:     print $fh $content;
                   1324:     close($fh);
1.638     albertel 1325:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1326:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1327: 			  $home);
1.637     raeburn  1328:     if ($$fetchresult eq 'ok') {
                   1329:         return '/uploaded/'.$fpath.'/'.$fname;
                   1330:     } else {
1.638     albertel 1331:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1332: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1333:         return '/adm/notfound.html';
                   1334:     }
                   1335: }
                   1336: 
1.531     albertel 1337: sub clean_filename {
                   1338:     my ($fname)=@_;
1.315     www      1339: # Replace Windows backslashes by forward slashes
1.257     www      1340:     $fname=~s/\\/\//g;
1.315     www      1341: # Get rid of everything but the actual filename
1.257     www      1342:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1343: # Replace spaces by underscores
                   1344:     $fname=~s/\s+/\_/g;
                   1345: # Replace all other weird characters by nothing
1.317     www      1346:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1347: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1348: # numbers
                   1349:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1350:     return $fname;
                   1351: }
                   1352: 
1.608     albertel 1353: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1354: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1355: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1356: #        $coursedoc - if true up to the current course
                   1357: #                     if false
                   1358: #        $subdir - directory in userfile to store the file into
                   1359: #        $parser, $allfiles, $codebase - unknown
                   1360: #
                   1361: # output: url of file in userspace, or error: <message> 
                   1362: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1363: 
                   1364: 
1.531     albertel 1365: sub userfileupload {
1.719     banghart 1366:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1367:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1368:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1369:     $fname=&clean_filename($fname);
1.315     www      1370: # See if there is anything left
1.257     www      1371:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1372:     chop($env{'form.'.$formname});
1.523     raeburn  1373:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1374:         my $now = time;
                   1375:         my $filepath = 'tmp/helprequests/'.$now;
                   1376:         my @parts=split(/\//,$filepath);
                   1377:         my $fullpath = $perlvar{'lonDaemons'};
                   1378:         for (my $i=0;$i<@parts;$i++) {
                   1379:             $fullpath .= '/'.$parts[$i];
                   1380:             if ((-e $fullpath)!=1) {
                   1381:                 mkdir($fullpath,0777);
                   1382:             }
                   1383:         }
                   1384:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1385:         print $fh $env{'form.'.$formname};
1.523     raeburn  1386:         close($fh);
                   1387:         return $fullpath.'/'.$fname; 
                   1388:     }
1.719     banghart 1389:     
1.258     www      1390: # Create the directory if not present
1.493     albertel 1391:     $fname="$subdir/$fname";
1.259     www      1392:     if ($coursedoc) {
1.638     albertel 1393: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1394: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1395:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1396:             return &finishuserfileupload($docuname,$docudom,
                   1397: 					 $formname,$fname,$parser,$allfiles,
                   1398: 					 $codebase);
1.481     raeburn  1399:         } else {
1.620     albertel 1400:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1401:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1402: 				       $fname,$formname,$parser,
                   1403: 				       $allfiles,$codebase);
1.481     raeburn  1404:         }
1.719     banghart 1405:     } elsif (defined($destuname)) {
                   1406:         my $docuname=$destuname;
                   1407:         my $docudom=$destudom;
                   1408: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1409: 				     $fname,$parser,$allfiles,$codebase);
                   1410:         
1.259     www      1411:     } else {
1.638     albertel 1412:         my $docuname=$env{'user.name'};
                   1413:         my $docudom=$env{'user.domain'};
1.714     raeburn  1414:         if (exists($env{'form.group'})) {
                   1415:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1416:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1417:         }
1.638     albertel 1418: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1419: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1420:     }
1.271     www      1421: }
                   1422: 
                   1423: sub finishuserfileupload {
1.638     albertel 1424:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1425:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1426:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1427:     my ($fnamepath,$file);
                   1428:     $file=$fname;
                   1429:     if ($fname=~m|/|) {
                   1430:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1431: 	$path.=$fnamepath.'/';
                   1432:     }
1.259     www      1433:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1434:     my $count;
                   1435:     for ($count=4;$count<=$#parts;$count++) {
                   1436:         $filepath.="/$parts[$count]";
                   1437:         if ((-e $filepath)!=1) {
                   1438: 	    mkdir($filepath,0777);
                   1439:         }
                   1440:     }
                   1441: # Save the file
                   1442:     {
1.701     albertel 1443: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1444: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1445: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1446: 	    return '/adm/notfound.html';
                   1447: 	}
                   1448: 	if (!print FH ($env{'form.'.$formname})) {
                   1449: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1450: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1451: 	    return '/adm/notfound.html';
                   1452: 	}
1.570     albertel 1453: 	close(FH);
1.258     www      1454:     }
1.637     raeburn  1455:     if ($parser eq 'parse') {
1.638     albertel 1456:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1457: 						   $codebase);
1.637     raeburn  1458:         unless ($parse_result eq 'ok') {
1.638     albertel 1459:             &logthis('Failed to parse '.$filepath.$file.
                   1460: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1461:         }
                   1462:     }
1.259     www      1463: # Notify homeserver to grep it
                   1464: #
1.638     albertel 1465:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1466:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1467:     if ($fetchresult eq 'ok') {
1.259     www      1468: #
1.258     www      1469: # Return the URL to it
1.494     albertel 1470:         return '/uploaded/'.$path.$file;
1.263     www      1471:     } else {
1.494     albertel 1472:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1473: 		 ': '.$fetchresult);
1.263     www      1474:         return '/adm/notfound.html';
                   1475:     }    
1.493     albertel 1476: }
                   1477: 
1.637     raeburn  1478: sub extract_embedded_items {
1.648     raeburn  1479:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1480:     my @state = ();
                   1481:     my %javafiles = (
                   1482:                       codebase => '',
                   1483:                       code => '',
                   1484:                       archive => ''
                   1485:                     );
                   1486:     my %mediafiles = (
                   1487:                       src => '',
                   1488:                       movie => '',
                   1489:                      );
1.648     raeburn  1490:     my $p;
                   1491:     if ($content) {
                   1492:         $p = HTML::LCParser->new($content);
                   1493:     } else {
                   1494:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1495:     }
1.641     albertel 1496:     while (my $t=$p->get_token()) {
1.640     albertel 1497: 	if ($t->[0] eq 'S') {
                   1498: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1499: 	    push (@state, $tagname);
1.648     raeburn  1500:             if (lc($tagname) eq 'allow') {
                   1501:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1502:             }
1.640     albertel 1503: 	    if (lc($tagname) eq 'img') {
                   1504: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1505: 	    }
1.645     raeburn  1506:             if (lc($tagname) eq 'script') {
                   1507:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1508:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1509:                 } else {
                   1510:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1511:                 }
                   1512:             }
                   1513:             if (lc($tagname) eq 'link') {
                   1514:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1515:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1516:                 }
                   1517:             }
1.640     albertel 1518: 	    if (lc($tagname) eq 'object' ||
                   1519: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1520: 		foreach my $item (keys(%javafiles)) {
                   1521: 		    $javafiles{$item} = '';
                   1522: 		}
                   1523: 	    }
                   1524: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1525: 		my $name = lc($attr->{'name'});
                   1526: 		foreach my $item (keys(%javafiles)) {
                   1527: 		    if ($name eq $item) {
                   1528: 			$javafiles{$item} = $attr->{'value'};
                   1529: 			last;
                   1530: 		    }
                   1531: 		}
                   1532: 		foreach my $item (keys(%mediafiles)) {
                   1533: 		    if ($name eq $item) {
                   1534: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1535: 			last;
                   1536: 		    }
                   1537: 		}
                   1538: 	    }
                   1539: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1540: 		foreach my $item (keys(%javafiles)) {
                   1541: 		    if ($attr->{$item}) {
                   1542: 			$javafiles{$item} = $attr->{$item};
                   1543: 			last;
                   1544: 		    }
                   1545: 		}
                   1546: 		foreach my $item (keys(%mediafiles)) {
                   1547: 		    if ($attr->{$item}) {
                   1548: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1549: 			last;
                   1550: 		    }
                   1551: 		}
                   1552: 	    }
                   1553: 	} elsif ($t->[0] eq 'E') {
                   1554: 	    my ($tagname) = ($t->[1]);
                   1555: 	    if ($javafiles{'codebase'} ne '') {
                   1556: 		$javafiles{'codebase'} .= '/';
                   1557: 	    }  
                   1558: 	    if (lc($tagname) eq 'applet' ||
                   1559: 		lc($tagname) eq 'object' ||
                   1560: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1561: 		) {
                   1562: 		foreach my $item (keys(%javafiles)) {
                   1563: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1564: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1565: 			&add_filetype($allfiles,$file,$item);
                   1566: 		    }
                   1567: 		}
                   1568: 	    } 
                   1569: 	    pop @state;
                   1570: 	}
                   1571:     }
1.637     raeburn  1572:     return 'ok';
                   1573: }
                   1574: 
1.639     albertel 1575: sub add_filetype {
                   1576:     my ($allfiles,$file,$type)=@_;
                   1577:     if (exists($allfiles->{$file})) {
                   1578: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1579: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1580: 	}
                   1581:     } else {
                   1582: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1583:     }
                   1584: }
                   1585: 
1.493     albertel 1586: sub removeuploadedurl {
                   1587:     my ($url)=@_;
                   1588:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1589:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1590: }
                   1591: 
                   1592: sub removeuserfile {
                   1593:     my ($docuname,$docudom,$fname)=@_;
                   1594:     my $home=&homeserver($docuname,$docudom);
                   1595:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1596: }
1.15      www      1597: 
1.530     albertel 1598: sub mkdiruserfile {
                   1599:     my ($docuname,$docudom,$dir)=@_;
                   1600:     my $home=&homeserver($docuname,$docudom);
                   1601:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1602: }
                   1603: 
1.531     albertel 1604: sub renameuserfile {
                   1605:     my ($docuname,$docudom,$old,$new)=@_;
                   1606:     my $home=&homeserver($docuname,$docudom);
                   1607:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1608: 		  &escape("$new"),$home);
                   1609: }
                   1610: 
1.14      www      1611: # ------------------------------------------------------------------------- Log
                   1612: 
                   1613: sub log {
                   1614:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1615:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1616: }
                   1617: 
                   1618: # ------------------------------------------------------------------ Course Log
1.352     www      1619: #
                   1620: # This routine flushes several buffers of non-mission-critical nature
                   1621: #
1.157     www      1622: 
                   1623: sub flushcourselogs {
1.352     www      1624:     &logthis('Flushing log buffers');
                   1625: #
                   1626: # course logs
                   1627: # This is a log of all transactions in a course, which can be used
                   1628: # for data mining purposes
                   1629: #
                   1630: # It also collects the courseid database, which lists last transaction
                   1631: # times and course titles for all courseids
                   1632: #
                   1633:     my %courseidbuffer=();
1.191     harris41 1634:     foreach (keys %courselogs) {
1.157     www      1635:         my $crsid=$_;
1.352     www      1636:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1637: 		          &escape($courselogs{$crsid}),
                   1638: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1639: 	    delete $courselogs{$crsid};
                   1640:         } else {
                   1641:             &logthis('Failed to flush log buffer for '.$crsid);
                   1642:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1643:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1644:                         " exceeded maximum size, deleting.</font>");
                   1645:                delete $courselogs{$crsid};
                   1646:             }
1.352     www      1647:         }
                   1648:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1649:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1650: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1651:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352     www      1652:         } else {
                   1653:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1654: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1655:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
                   1656:         }
1.191     harris41 1657:     }
1.352     www      1658: #
                   1659: # Write course id database (reverse lookup) to homeserver of courses 
                   1660: # Is used in pickcourse
                   1661: #
                   1662:     foreach (keys %courseidbuffer) {
1.353     www      1663:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1664:     }
                   1665: #
                   1666: # File accesses
                   1667: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1668: #
1.449     matthew  1669:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1670:         if ($entry =~ /___count$/) {
                   1671:             my ($dom,$name);
                   1672:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1673:             if (! defined($dom) || $dom eq '' || 
                   1674:                 ! defined($name) || $name eq '') {
1.620     albertel 1675:                 my $cid = $env{'request.course.id'};
                   1676:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1677:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1678:             }
1.450     matthew  1679:             my $value = $accesshash{$entry};
                   1680:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1681:             my %temphash=($url => $value);
1.449     matthew  1682:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1683:             if ($result eq 'ok') {
                   1684:                 delete $accesshash{$entry};
                   1685:             } elsif ($result eq 'unknown_cmd') {
                   1686:                 # Target server has old code running on it.
1.450     matthew  1687:                 my %temphash=($entry => $value);
1.449     matthew  1688:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1689:                     delete $accesshash{$entry};
                   1690:                 }
                   1691:             }
                   1692:         } else {
1.458     matthew  1693:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1694:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1695:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1696:                 delete $accesshash{$entry};
                   1697:             }
1.185     www      1698:         }
1.191     harris41 1699:     }
1.352     www      1700: #
                   1701: # Roles
                   1702: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1703: #
1.349     www      1704:     foreach (keys %userrolehash) {
                   1705:         my $entry=$_;
1.351     www      1706:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1707: 	    split(/\:/,$entry);
                   1708:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1709:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1710:                 $rudom,$runame) eq 'ok') {
                   1711: 	    delete $userrolehash{$entry};
                   1712:         }
                   1713:     }
1.662     raeburn  1714: #
                   1715: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1716: #
                   1717:     my %domrolebuffer = ();
                   1718:     foreach my $entry (keys %domainrolehash) {
                   1719:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1720:         if ($domrolebuffer{$rudom}) {
                   1721:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1722:                       '='.&escape($domainrolehash{$entry});
                   1723:         } else {
                   1724:             $domrolebuffer{$rudom}.=&escape($entry).
                   1725:                       '='.&escape($domainrolehash{$entry});
                   1726:         }
                   1727:         delete $domainrolehash{$entry};
                   1728:     }
                   1729:     foreach my $dom (keys(%domrolebuffer)) {
                   1730:         foreach my $tryserver (keys %libserv) {
                   1731:             if ($hostdom{$tryserver} eq $dom) {
                   1732:                 unless (&reply('domroleput:'.$dom.':'.
                   1733:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1734:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1735:                 }
                   1736:             }
                   1737:         }
                   1738:     }
1.186     www      1739:     $dumpcount++;
1.157     www      1740: }
                   1741: 
                   1742: sub courselog {
                   1743:     my $what=shift;
1.158     www      1744:     $what=time.':'.$what;
1.620     albertel 1745:     unless ($env{'request.course.id'}) { return ''; }
                   1746:     $coursedombuf{$env{'request.course.id'}}=
                   1747:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1748:     $coursenumbuf{$env{'request.course.id'}}=
                   1749:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1750:     $coursehombuf{$env{'request.course.id'}}=
                   1751:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1752:     $coursedescrbuf{$env{'request.course.id'}}=
                   1753:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1754:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1755:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1756:     $courseownerbuf{$env{'request.course.id'}}=
                   1757:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   1758:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1759: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1760:     } else {
1.620     albertel 1761: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1762:     }
1.620     albertel 1763:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1764: 	&flushcourselogs();
                   1765:     }
1.158     www      1766: }
                   1767: 
                   1768: sub courseacclog {
                   1769:     my $fnsymb=shift;
1.620     albertel 1770:     unless ($env{'request.course.id'}) { return ''; }
                   1771:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1772:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1773:         $what.=':POST';
1.583     matthew  1774:         # FIXME: Probably ought to escape things....
1.620     albertel 1775: 	foreach (keys %env) {
1.158     www      1776:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1777: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1778:             }
1.191     harris41 1779:         }
1.583     matthew  1780:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1781:         # FIXME: We should not be depending on a form parameter that someone
                   1782:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1783:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1784:             $what.= ':POST';
                   1785:             # FIXME: Probably ought to escape things....
                   1786:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1787:                                  'crsdiscuss') {
1.620     albertel 1788:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1789:             }
                   1790:         }
1.158     www      1791:     }
                   1792:     &courselog($what);
1.149     www      1793: }
                   1794: 
1.185     www      1795: sub countacc {
                   1796:     my $url=&declutter(shift);
1.458     matthew  1797:     return if (! defined($url) || $url eq '');
1.620     albertel 1798:     unless ($env{'request.course.id'}) { return ''; }
                   1799:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1800:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1801:     $accesshash{$key}++;
1.185     www      1802: }
1.349     www      1803: 
1.361     www      1804: sub linklog {
                   1805:     my ($from,$to)=@_;
                   1806:     $from=&declutter($from);
                   1807:     $to=&declutter($to);
                   1808:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1809:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1810: }
                   1811:   
1.349     www      1812: sub userrolelog {
                   1813:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1814:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1815:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1816:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1817:         ($trole=~/^ta/)) {
1.350     www      1818:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1819:        $userrolehash
                   1820:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1821:                     =$tend.':'.$tstart;
1.662     raeburn  1822:     }
                   1823:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1824:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1825:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1826:         ($trole=~/^sc/)) {
                   1827:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1828:        $domainrolehash
                   1829:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1830:                     = $tend.':'.$tstart;
                   1831:     }
1.351     www      1832: }
                   1833: 
                   1834: sub get_course_adv_roles {
                   1835:     my $cid=shift;
1.620     albertel 1836:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1837:     my %coursehash=&coursedescription($cid);
1.470     www      1838:     my %nothide=();
                   1839:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1840: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1841:     }
1.351     www      1842:     my %returnhash=();
                   1843:     my %dumphash=
                   1844:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1845:     my $now=time;
                   1846:     foreach (keys %dumphash) {
                   1847: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1848:         if (($tstart) && ($tstart<0)) { next; }
                   1849:         if (($tend) && ($tend<$now)) { next; }
                   1850:         if (($tstart) && ($now<$tstart)) { next; }
                   1851:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1852: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1853: 	if ((&privileged($username,$domain)) && 
                   1854: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1855: 	if ($role eq 'cr') { next; }
1.351     www      1856:         my $key=&plaintext($role);
1.656     albertel 1857: 	if ($role =~ /^cr/) {
                   1858: 	    $key=(split('/',$role))[3];
                   1859: 	}
1.351     www      1860:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1861:         if ($returnhash{$key}) {
                   1862: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1863:         } else {
                   1864:             $returnhash{$key}=$username.':'.$domain;
                   1865:         }
1.400     www      1866:      }
                   1867:     return %returnhash;
                   1868: }
                   1869: 
                   1870: sub get_my_roles {
                   1871:     my ($uname,$udom)=@_;
1.620     albertel 1872:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1873:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1874:     my %dumphash=
                   1875:             &dump('nohist_userroles',$udom,$uname);
                   1876:     my %returnhash=();
                   1877:     my $now=time;
                   1878:     foreach (keys %dumphash) {
                   1879: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1880:         if (($tstart) && ($tstart<0)) { next; }
                   1881:         if (($tend) && ($tend<$now)) { next; }
                   1882:         if (($tstart) && ($now<$tstart)) { next; }
                   1883:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1884: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1885:      }
                   1886:     return %returnhash;
1.399     www      1887: }
                   1888: 
                   1889: # ----------------------------------------------------- Frontpage Announcements
                   1890: #
                   1891: #
                   1892: 
                   1893: sub postannounce {
                   1894:     my ($server,$text)=@_;
                   1895:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1896:     unless ($text=~/\w/) { $text=''; }
                   1897:     return &reply('setannounce:'.&escape($text),$server);
                   1898: }
                   1899: 
                   1900: sub getannounce {
1.448     albertel 1901: 
                   1902:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1903: 	my $announcement='';
                   1904: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1905: 	close($fh);
1.399     www      1906: 	if ($announcement=~/\w/) { 
                   1907: 	    return 
                   1908:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1909:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1910: 	} else {
                   1911: 	    return '';
                   1912: 	}
                   1913:     } else {
                   1914: 	return '';
                   1915:     }
1.351     www      1916: }
1.353     www      1917: 
                   1918: # ---------------------------------------------------------- Course ID routines
                   1919: # Deal with domain's nohist_courseid.db files
                   1920: #
                   1921: 
                   1922: sub courseidput {
                   1923:     my ($domain,$what,$coursehome)=@_;
                   1924:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1925: }
                   1926: 
                   1927: sub courseiddump {
1.622     raeburn  1928:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353     www      1929:     my %returnhash=();
1.355     www      1930:     unless ($domfilter) { $domfilter=''; }
1.353     www      1931:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1932:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1933: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1934: 	        foreach (
                   1935:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1936: 			       $sincefilter.':'.&escape($descfilter).':'.
1.622     raeburn  1937:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354     www      1938:                                $tryserver))) {
1.506     raeburn  1939: 		    my ($key,$value)=split(/\=/,$_);
                   1940:                     if (($key) && ($value)) {
1.516     raeburn  1941: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1942:                     }
1.353     www      1943:                 }
                   1944:             }
                   1945:         }
                   1946:     }
                   1947:     return %returnhash;
                   1948: }
                   1949: 
1.658     raeburn  1950: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1951: 
                   1952: sub dcmailput {
1.685     raeburn  1953:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1954:     my $status = &Apache::lonnet::critical(
                   1955:        'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='.
1.685     raeburn  1956:        &Apache::lonnet::escape($message),$server);
1.662     raeburn  1957:     return $status;
                   1958: }
                   1959: 
1.658     raeburn  1960: sub dcmaildump {
                   1961:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1962:     my %returnhash=();
                   1963:     if (exists($domain_primary{$dom})) {
                   1964:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1965:                                                          &escape($enddate).':';
                   1966: 	my @esc_senders=map { &escape($_)} @$senders;
                   1967: 	$cmd.=&escape(join('&',@esc_senders));
                   1968: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1969:             my ($key,$value) = split(/\=/,$_);
                   1970:             if (($key) && ($value)) {
                   1971:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  1972:             }
                   1973:         }
                   1974:     }
                   1975:     return %returnhash;
                   1976: }
1.662     raeburn  1977: # ---------------------------------------------------------- Domain roles
                   1978: 
                   1979: sub get_domain_roles {
                   1980:     my ($dom,$roles,$startdate,$enddate)=@_;
                   1981:     if (undef($startdate) || $startdate eq '') {
                   1982:         $startdate = '.';
                   1983:     }
                   1984:     if (undef($enddate) || $enddate eq '') {
                   1985:         $enddate = '.';
                   1986:     }
                   1987:     my $rolelist = join(':',@{$roles});
                   1988:     my %personnel = ();
                   1989:     foreach my $tryserver (keys(%libserv)) {
                   1990:         if ($hostdom{$tryserver} eq $dom) {
                   1991:             %{$personnel{$tryserver}}=();
                   1992:             foreach (
                   1993:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   1994:                    &escape($startdate).':'.&escape($enddate).':'.
                   1995:                    &escape($rolelist), $tryserver))) {
                   1996:                 my($key,$value) = split(/\=/,$_);
                   1997:                 if (($key) && ($value)) {
                   1998:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   1999:                 }
                   2000:             }
                   2001:         }
                   2002:     }
                   2003:     return %personnel;
                   2004: }
1.658     raeburn  2005: 
1.149     www      2006: # ----------------------------------------------------------- Check out an item
                   2007: 
1.504     albertel 2008: sub get_first_access {
                   2009:     my ($type,$argsymb)=@_;
                   2010:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2011:     if ($argsymb) { $symb=$argsymb; }
                   2012:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2013:     if ($type eq 'map') {
                   2014: 	$res=&symbread($map);
                   2015:     } else {
                   2016: 	$res=$symb;
                   2017:     }
                   2018:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2019:     return $times{"$courseid\0$res"};
1.504     albertel 2020: }
                   2021: 
                   2022: sub set_first_access {
                   2023:     my ($type)=@_;
                   2024:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2025:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2026:     if ($type eq 'map') {
                   2027: 	$res=&symbread($map);
                   2028:     } else {
                   2029: 	$res=$symb;
                   2030:     }
                   2031:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2032:     if (!$firstaccess) {
1.588     albertel 2033: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2034:     }
                   2035:     return 'already_set';
1.504     albertel 2036: }
                   2037: 
1.149     www      2038: sub checkout {
                   2039:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2040:     my $now=time;
                   2041:     my $lonhost=$perlvar{'lonHostID'};
                   2042:     my $infostr=&escape(
1.234     www      2043:                  'CHECKOUTTOKEN&'.
1.149     www      2044:                  $tuname.'&'.
                   2045:                  $tudom.'&'.
                   2046:                  $tcrsid.'&'.
                   2047:                  $symb.'&'.
                   2048: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2049:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2050:     if ($token=~/^error\:/) { 
1.672     albertel 2051:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2052:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2053:                  "</font>");
                   2054:         return ''; 
                   2055:     }
                   2056: 
1.149     www      2057:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2058:     $token=~tr/a-z/A-Z/;
                   2059: 
1.153     www      2060:     my %infohash=('resource.0.outtoken' => $token,
                   2061:                   'resource.0.checkouttime' => $now,
                   2062:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2063: 
                   2064:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2065:        return '';
1.151     www      2066:     } else {
1.672     albertel 2067:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2068:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2069:                  "</font>");
1.149     www      2070:     }    
                   2071: 
                   2072:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2073:                          &escape('Checkout '.$infostr.' - '.
                   2074:                                                  $token)) ne 'ok') {
                   2075: 	return '';
1.151     www      2076:     } else {
1.672     albertel 2077:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2078:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2079:                  "</font>");
1.149     www      2080:     }
1.151     www      2081:     return $token;
1.149     www      2082: }
                   2083: 
                   2084: # ------------------------------------------------------------ Check in an item
                   2085: 
                   2086: sub checkin {
                   2087:     my $token=shift;
1.150     www      2088:     my $now=time;
                   2089:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2090:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2091:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2092:     $dtoken=~s/\W/\_/g;
1.234     www      2093:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2094:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2095: 
1.154     www      2096:     unless (($tuname) && ($tudom)) {
                   2097:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2098:         return '';
                   2099:     }
                   2100:     
                   2101:     unless (&allowed('mgr',$tcrsid)) {
                   2102:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2103:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2104:         return '';
                   2105:     }
                   2106: 
1.153     www      2107:     my %infohash=('resource.0.intoken' => $token,
                   2108:                   'resource.0.checkintime' => $now,
                   2109:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2110: 
                   2111:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2112:        return '';
                   2113:     }    
                   2114: 
                   2115:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2116:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2117: 	return '';
                   2118:     }
                   2119: 
                   2120:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2121: }
                   2122: 
                   2123: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2124: 
                   2125: sub expirespread {
                   2126:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2127:     my $cid=$env{'request.course.id'}; 
1.110     www      2128:     if ($cid) {
                   2129:        my $now=time;
                   2130:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2131:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2132:                             $env{'course.'.$cid.'.num'}.
1.110     www      2133: 	        	    ':nohist_expirationdates:'.
                   2134:                             &escape($key).'='.$now,
1.620     albertel 2135:                             $env{'course.'.$cid.'.home'})
1.110     www      2136:     }
                   2137:     return 'ok';
1.14      www      2138: }
                   2139: 
1.109     www      2140: # ----------------------------------------------------- Devalidate Spreadsheets
                   2141: 
                   2142: sub devalidate {
1.325     www      2143:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2144:     my $cid=$env{'request.course.id'}; 
1.109     www      2145:     if ($cid) {
1.391     matthew  2146:         # delete the stored spreadsheets for
                   2147:         # - the student level sheet of this user in course's homespace
                   2148:         # - the assessment level sheet for this resource 
                   2149:         #   for this user in user's homespace
1.553     albertel 2150: 	# - current conditional state info
1.325     www      2151: 	my $key=$uname.':'.$udom.':';
1.109     www      2152:         my $status=
1.299     matthew  2153: 	    &del('nohist_calculatedsheets',
1.391     matthew  2154: 		 [$key.'studentcalc:'],
1.620     albertel 2155: 		 $env{'course.'.$cid.'.domain'},
                   2156: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2157: 		.' '.
                   2158: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2159: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2160:         unless ($status eq 'ok ok') {
                   2161:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2162:                     $uname.' at '.$udom.' for '.
1.109     www      2163: 		    $symb.': '.$status);
1.133     albertel 2164:         }
1.553     albertel 2165: 	&delenv('user.state.'.$cid);
1.109     www      2166:     }
                   2167: }
                   2168: 
1.265     albertel 2169: sub get_scalar {
                   2170:     my ($string,$end) = @_;
                   2171:     my $value;
                   2172:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2173: 	$value = $1;
                   2174:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2175: 	$value = $1;
                   2176:     }
                   2177:     return &unescape($value);
                   2178: }
                   2179: 
                   2180: sub array2str {
                   2181:   my (@array) = @_;
                   2182:   my $result=&arrayref2str(\@array);
                   2183:   $result=~s/^__ARRAY_REF__//;
                   2184:   $result=~s/__END_ARRAY_REF__$//;
                   2185:   return $result;
                   2186: }
                   2187: 
1.204     albertel 2188: sub arrayref2str {
                   2189:   my ($arrayref) = @_;
1.265     albertel 2190:   my $result='__ARRAY_REF__';
1.204     albertel 2191:   foreach my $elem (@$arrayref) {
1.265     albertel 2192:     if(ref($elem) eq 'ARRAY') {
                   2193:       $result.=&arrayref2str($elem).'&';
                   2194:     } elsif(ref($elem) eq 'HASH') {
                   2195:       $result.=&hashref2str($elem).'&';
                   2196:     } elsif(ref($elem)) {
                   2197:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2198:     } else {
                   2199:       $result.=&escape($elem).'&';
                   2200:     }
                   2201:   }
                   2202:   $result=~s/\&$//;
1.265     albertel 2203:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2204:   return $result;
                   2205: }
                   2206: 
1.168     albertel 2207: sub hash2str {
1.204     albertel 2208:   my (%hash) = @_;
                   2209:   my $result=&hashref2str(\%hash);
1.265     albertel 2210:   $result=~s/^__HASH_REF__//;
                   2211:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2212:   return $result;
                   2213: }
                   2214: 
                   2215: sub hashref2str {
                   2216:   my ($hashref)=@_;
1.265     albertel 2217:   my $result='__HASH_REF__';
1.495     albertel 2218:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2219:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2220:       $result.=&arrayref2str($_).'=';
1.204     albertel 2221:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2222:       $result.=&hashref2str($_).'=';
1.204     albertel 2223:     } elsif (ref($_)) {
1.265     albertel 2224:       $result.='=';
                   2225:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2226:     } else {
1.265     albertel 2227: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2228:     }
                   2229: 
1.265     albertel 2230:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2231:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2232:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2233:       $result.=&hashref2str($hashref->{$_}).'&';
                   2234:     } elsif(ref($hashref->{$_})) {
                   2235:        $result.='&';
                   2236:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2237:     } else {
1.265     albertel 2238:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2239:     }
                   2240:   }
1.168     albertel 2241:   $result=~s/\&$//;
1.265     albertel 2242:   $result .= '__END_HASH_REF__';
1.168     albertel 2243:   return $result;
                   2244: }
                   2245: 
                   2246: sub str2hash {
1.265     albertel 2247:     my ($string)=@_;
                   2248:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2249:     return %$hash;
                   2250: }
                   2251: 
                   2252: sub str2hashref {
1.168     albertel 2253:   my ($string) = @_;
1.265     albertel 2254: 
                   2255:   my %hash;
                   2256: 
                   2257:   if($string !~ /^__HASH_REF__/) {
                   2258:       if (! ($string eq '' || !defined($string))) {
                   2259: 	  $hash{'error'}='Not hash reference';
                   2260:       }
                   2261:       return (\%hash, $string);
                   2262:   }
                   2263: 
                   2264:   $string =~ s/^__HASH_REF__//;
                   2265: 
                   2266:   while($string !~ /^__END_HASH_REF__/) {
                   2267:       #key
                   2268:       my $key='';
                   2269:       if($string =~ /^__HASH_REF__/) {
                   2270:           ($key, $string)=&str2hashref($string);
                   2271:           if(defined($key->{'error'})) {
                   2272:               $hash{'error'}='Bad data';
                   2273:               return (\%hash, $string);
                   2274:           }
                   2275:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2276:           ($key, $string)=&str2arrayref($string);
                   2277:           if($key->[0] eq 'Array reference error') {
                   2278:               $hash{'error'}='Bad data';
                   2279:               return (\%hash, $string);
                   2280:           }
                   2281:       } else {
                   2282:           $string =~ s/^(.*?)=//;
1.267     albertel 2283: 	  $key=&unescape($1);
1.265     albertel 2284:       }
                   2285:       $string =~ s/^=//;
                   2286: 
                   2287:       #value
                   2288:       my $value='';
                   2289:       if($string =~ /^__HASH_REF__/) {
                   2290:           ($value, $string)=&str2hashref($string);
                   2291:           if(defined($value->{'error'})) {
                   2292:               $hash{'error'}='Bad data';
                   2293:               return (\%hash, $string);
                   2294:           }
                   2295:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2296:           ($value, $string)=&str2arrayref($string);
                   2297:           if($value->[0] eq 'Array reference error') {
                   2298:               $hash{'error'}='Bad data';
                   2299:               return (\%hash, $string);
                   2300:           }
                   2301:       } else {
                   2302: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2303:       }
                   2304:       $string =~ s/^&//;
                   2305: 
                   2306:       $hash{$key}=$value;
1.204     albertel 2307:   }
1.265     albertel 2308: 
                   2309:   $string =~ s/^__END_HASH_REF__//;
                   2310: 
                   2311:   return (\%hash, $string);
1.204     albertel 2312: }
                   2313: 
                   2314: sub str2array {
1.265     albertel 2315:     my ($string)=@_;
                   2316:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2317:     return @$array;
                   2318: }
                   2319: 
                   2320: sub str2arrayref {
1.204     albertel 2321:   my ($string) = @_;
1.265     albertel 2322:   my @array;
                   2323: 
                   2324:   if($string !~ /^__ARRAY_REF__/) {
                   2325:       if (! ($string eq '' || !defined($string))) {
                   2326: 	  $array[0]='Array reference error';
                   2327:       }
                   2328:       return (\@array, $string);
                   2329:   }
                   2330: 
                   2331:   $string =~ s/^__ARRAY_REF__//;
                   2332: 
                   2333:   while($string !~ /^__END_ARRAY_REF__/) {
                   2334:       my $value='';
                   2335:       if($string =~ /^__HASH_REF__/) {
                   2336:           ($value, $string)=&str2hashref($string);
                   2337:           if(defined($value->{'error'})) {
                   2338:               $array[0] ='Array reference error';
                   2339:               return (\@array, $string);
                   2340:           }
                   2341:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2342:           ($value, $string)=&str2arrayref($string);
                   2343:           if($value->[0] eq 'Array reference error') {
                   2344:               $array[0] ='Array reference error';
                   2345:               return (\@array, $string);
                   2346:           }
                   2347:       } else {
                   2348: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2349:       }
                   2350:       $string =~ s/^&//;
                   2351: 
                   2352:       push(@array, $value);
1.191     harris41 2353:   }
1.265     albertel 2354: 
                   2355:   $string =~ s/^__END_ARRAY_REF__//;
                   2356: 
                   2357:   return (\@array, $string);
1.168     albertel 2358: }
                   2359: 
1.167     albertel 2360: # -------------------------------------------------------------------Temp Store
                   2361: 
1.168     albertel 2362: sub tmpreset {
                   2363:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2364:   if (!$symb) {
                   2365:     $symb=&symbread();
1.620     albertel 2366:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2367:   }
                   2368:   $symb=escape($symb);
                   2369: 
1.620     albertel 2370:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2371:   $namespace=~s/\//\_/g;
                   2372:   $namespace=~s/\W//g;
                   2373: 
1.620     albertel 2374:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2375:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2376:   if ($domain eq 'public' && $stuname eq 'public') {
                   2377:       $stuname=$ENV{'REMOTE_ADDR'};
                   2378:   }
1.168     albertel 2379:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2380:   my %hash;
                   2381:   if (tie(%hash,'GDBM_File',
                   2382: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2383: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2384:     foreach my $key (keys %hash) {
1.180     albertel 2385:       if ($key=~ /:$symb/) {
1.168     albertel 2386: 	delete($hash{$key});
                   2387:       }
                   2388:     }
                   2389:   }
                   2390: }
                   2391: 
1.167     albertel 2392: sub tmpstore {
1.168     albertel 2393:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2394: 
                   2395:   if (!$symb) {
                   2396:     $symb=&symbread();
1.620     albertel 2397:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2398:   }
                   2399:   $symb=escape($symb);
                   2400: 
                   2401:   if (!$namespace) {
                   2402:     # I don't think we would ever want to store this for a course.
                   2403:     # it seems this will only be used if we don't have a course.
1.620     albertel 2404:     #$namespace=$env{'request.course.id'};
1.168     albertel 2405:     #if (!$namespace) {
1.620     albertel 2406:       $namespace=$env{'request.state'};
1.168     albertel 2407:     #}
                   2408:   }
                   2409:   $namespace=~s/\//\_/g;
                   2410:   $namespace=~s/\W//g;
1.620     albertel 2411:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2412:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2413:   if ($domain eq 'public' && $stuname eq 'public') {
                   2414:       $stuname=$ENV{'REMOTE_ADDR'};
                   2415:   }
1.168     albertel 2416:   my $now=time;
                   2417:   my %hash;
                   2418:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2419:   if (tie(%hash,'GDBM_File',
                   2420: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2421: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2422:     $hash{"version:$symb"}++;
                   2423:     my $version=$hash{"version:$symb"};
                   2424:     my $allkeys=''; 
                   2425:     foreach my $key (keys(%$storehash)) {
                   2426:       $allkeys.=$key.':';
1.591     albertel 2427:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2428:     }
                   2429:     $hash{"$version:$symb:timestamp"}=$now;
                   2430:     $allkeys.='timestamp';
                   2431:     $hash{"$version:keys:$symb"}=$allkeys;
                   2432:     if (untie(%hash)) {
                   2433:       return 'ok';
                   2434:     } else {
                   2435:       return "error:$!";
                   2436:     }
                   2437:   } else {
                   2438:     return "error:$!";
                   2439:   }
                   2440: }
1.167     albertel 2441: 
1.168     albertel 2442: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2443: 
1.168     albertel 2444: sub tmprestore {
                   2445:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2446: 
1.168     albertel 2447:   if (!$symb) {
                   2448:     $symb=&symbread();
1.620     albertel 2449:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2450:   }
                   2451:   $symb=escape($symb);
                   2452: 
1.620     albertel 2453:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2454: 
1.620     albertel 2455:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2456:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2457:   if ($domain eq 'public' && $stuname eq 'public') {
                   2458:       $stuname=$ENV{'REMOTE_ADDR'};
                   2459:   }
1.168     albertel 2460:   my %returnhash;
                   2461:   $namespace=~s/\//\_/g;
                   2462:   $namespace=~s/\W//g;
                   2463:   my %hash;
                   2464:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2465:   if (tie(%hash,'GDBM_File',
                   2466: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2467: 	  &GDBM_READER(),0640)) {
1.168     albertel 2468:     my $version=$hash{"version:$symb"};
                   2469:     $returnhash{'version'}=$version;
                   2470:     my $scope;
                   2471:     for ($scope=1;$scope<=$version;$scope++) {
                   2472:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2473:       my @keys=split(/:/,$vkeys);
                   2474:       my $key;
                   2475:       $returnhash{"$scope:keys"}=$vkeys;
                   2476:       foreach $key (@keys) {
1.591     albertel 2477: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2478: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2479:       }
                   2480:     }
1.168     albertel 2481:     if (!(untie(%hash))) {
                   2482:       return "error:$!";
                   2483:     }
                   2484:   } else {
                   2485:     return "error:$!";
                   2486:   }
                   2487:   return %returnhash;
1.167     albertel 2488: }
                   2489: 
1.9       www      2490: # ----------------------------------------------------------------------- Store
                   2491: 
                   2492: sub store {
1.124     www      2493:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2494:     my $home='';
                   2495: 
1.168     albertel 2496:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2497: 
1.213     www      2498:     $symb=&symbclean($symb);
1.122     albertel 2499:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2500: 
1.620     albertel 2501:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2502:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2503: 
                   2504:     &devalidate($symb,$stuname,$domain);
1.109     www      2505: 
                   2506:     $symb=escape($symb);
1.187     www      2507:     if (!$namespace) { 
1.620     albertel 2508:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2509:           return ''; 
                   2510:        } 
                   2511:     }
1.620     albertel 2512:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2513: 
                   2514:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2515:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2516: 
1.12      www      2517:     my $namevalue='';
1.191     harris41 2518:     foreach (keys %$storehash) {
1.591     albertel 2519:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2520:     }
1.12      www      2521:     $namevalue=~s/\&$//;
1.187     www      2522:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2523:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2524: }
                   2525: 
1.47      www      2526: # -------------------------------------------------------------- Critical Store
                   2527: 
                   2528: sub cstore {
1.124     www      2529:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2530:     my $home='';
                   2531: 
1.168     albertel 2532:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2533: 
1.213     www      2534:     $symb=&symbclean($symb);
1.122     albertel 2535:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2536: 
1.620     albertel 2537:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2538:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2539: 
                   2540:     &devalidate($symb,$stuname,$domain);
1.109     www      2541: 
                   2542:     $symb=escape($symb);
1.187     www      2543:     if (!$namespace) { 
1.620     albertel 2544:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2545:           return ''; 
                   2546:        } 
                   2547:     }
1.620     albertel 2548:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2549: 
                   2550:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2551:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2552: 
1.47      www      2553:     my $namevalue='';
1.191     harris41 2554:     foreach (keys %$storehash) {
1.591     albertel 2555:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2556:     }
1.47      www      2557:     $namevalue=~s/\&$//;
1.187     www      2558:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2559:     return critical
                   2560:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2561: }
                   2562: 
1.9       www      2563: # --------------------------------------------------------------------- Restore
                   2564: 
                   2565: sub restore {
1.124     www      2566:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2567:     my $home='';
                   2568: 
1.168     albertel 2569:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2570: 
1.122     albertel 2571:     if (!$symb) {
                   2572:       unless ($symb=escape(&symbread())) { return ''; }
                   2573:     } else {
1.213     www      2574:       $symb=&escape(&symbclean($symb));
1.122     albertel 2575:     }
1.188     www      2576:     if (!$namespace) { 
1.620     albertel 2577:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2578:           return ''; 
                   2579:        } 
                   2580:     }
1.620     albertel 2581:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2582:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2583:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2584:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2585: 
1.12      www      2586:     my %returnhash=();
1.191     harris41 2587:     foreach (split(/\&/,$answer)) {
1.12      www      2588: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2589:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2590:     }
1.75      www      2591:     my $version;
                   2592:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2593:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2594:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2595:        }
1.75      www      2596:     }
1.13      www      2597:     return %returnhash;
1.34      www      2598: }
                   2599: 
                   2600: # ---------------------------------------------------------- Course Description
                   2601: 
                   2602: sub coursedescription {
1.731     albertel 2603:     my ($courseid,$args)=@_;
1.34      www      2604:     $courseid=~s/^\///;
1.49      www      2605:     $courseid=~s/\_/\//g;
1.34      www      2606:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2607:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2608:     my $normalid=$cdomain.'_'.$cnum;
                   2609:     # need to always cache even if we get errors otherwise we keep 
                   2610:     # trying and trying and trying to get the course description.
                   2611:     my %envhash=();
                   2612:     my %returnhash=();
1.731     albertel 2613:     
                   2614:     my $expiretime=600;
                   2615:     if ($env{'request.course.id'} eq $normalid) {
                   2616: 	$expiretime=120;
                   2617:     }
                   2618: 
                   2619:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2620:     if (!$args->{'freshen_cache'}
                   2621: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2622: 	foreach my $key (keys(%env)) {
                   2623: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2624: 	    my ($setting) = $1;
                   2625: 	    $returnhash{$setting} = $env{$key};
                   2626: 	}
                   2627: 	return %returnhash;
                   2628:     }
                   2629: 
                   2630:     # get the data agin
                   2631:     if (!$args->{'one_time'}) {
                   2632: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2633:     }
1.34      www      2634:     if ($chome ne 'no_host') {
1.302     albertel 2635:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2636:        if (!exists($returnhash{'con_lost'})) {
                   2637:            $returnhash{'home'}= $chome;
                   2638: 	   $returnhash{'domain'} = $cdomain;
                   2639: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2640:            while (my ($name,$value) = each %returnhash) {
1.53      www      2641:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2642:            }
1.270     www      2643:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2644:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2645: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2646:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2647:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2648:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2649:        }
                   2650:     }
1.731     albertel 2651:     if (!$args->{'one_time'}) {
                   2652: 	&appenv(%envhash);
                   2653:     }
1.302     albertel 2654:     return %returnhash;
1.461     www      2655: }
                   2656: 
                   2657: # -------------------------------------------------See if a user is privileged
                   2658: 
                   2659: sub privileged {
                   2660:     my ($username,$domain)=@_;
                   2661:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2662: 			&homeserver($username,$domain));
                   2663:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2664:     my $now=time;
                   2665:     if ($rolesdump ne '') {
                   2666:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2667: 	    if ($_!~/^rolesdef_/) {
1.461     www      2668: 		my ($area,$role)=split(/=/,$_);
                   2669: 		$area=~s/\_\w\w$//;
                   2670: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2671: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2672: 		    my $active=1;
                   2673: 		    if ($tend) {
                   2674: 			if ($tend<$now) { $active=0; }
                   2675: 		    }
                   2676: 		    if ($tstart) {
                   2677: 			if ($tstart>$now) { $active=0; }
                   2678: 		    }
                   2679: 		    if ($active) { return 1; }
                   2680: 		}
                   2681: 	    }
                   2682: 	}
                   2683:     }
                   2684:     return 0;
1.9       www      2685: }
1.1       albertel 2686: 
1.103     harris41 2687: # -------------------------------------------------------- Get user privileges
1.11      www      2688: 
                   2689: sub rolesinit {
                   2690:     my ($domain,$username,$authhost)=@_;
                   2691:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2692:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2693:     my %allroles=();
1.678     raeburn  2694:     my %allgroups=();   
1.11      www      2695:     my $now=time;
1.21      www      2696:     my $userroles="user.login.time=$now\n";
1.678     raeburn  2697:     my $group_privs;
1.11      www      2698: 
                   2699:     if ($rolesdump ne '') {
1.191     harris41 2700:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2701: 	  if ($_!~/^rolesdef_/) {
1.11      www      2702:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2703: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2704:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2705: 	    if ($role=~/^cr/) { 
1.655     albertel 2706: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2707: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2708: 		    ($tend,$tstart)=split('_',$trest);
                   2709: 		} else {
                   2710: 		    $trole=$role;
                   2711: 		}
1.678     raeburn  2712:             } elsif ($role =~ m|^gr/|) {
                   2713:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2714:                 ($trole,$group_privs) = split(/\//,$trole);
                   2715:                 $group_privs = &unescape($group_privs);
1.587     albertel 2716: 	    } else {
                   2717: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2718: 	    }
1.576     albertel 2719:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567     raeburn  2720:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2721:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2722:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2723: 		my $spec=$trole.'.'.$area;
                   2724: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2725: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2726:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2727:                 } elsif ($trole eq 'gr') {
                   2728:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2729: 		} else {
1.567     raeburn  2730:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2731: 		}
1.12      www      2732:             }
1.662     raeburn  2733:           }
1.191     harris41 2734:         }
1.678     raeburn  2735:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
1.128     www      2736:         $userroles.='user.adv='.$adv."\n".
                   2737: 	            'user.author='.$author."\n";
1.620     albertel 2738:         $env{'user.adv'}=$adv;
1.11      www      2739:     }
                   2740:     return $userroles;  
                   2741: }
                   2742: 
1.567     raeburn  2743: sub set_arearole {
                   2744:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2745: # log the associated role with the area
                   2746:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   2747:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
                   2748: }
                   2749: 
                   2750: sub custom_roleprivs {
                   2751:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2752:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2753:     my $homsvr=homeserver($rauthor,$rdomain);
                   2754:     if ($hostname{$homsvr} ne '') {
                   2755:         my ($rdummy,$roledef)=
                   2756:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2757:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2758:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2759:             if (defined($syspriv)) {
                   2760:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2761:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2762:             }
                   2763:             if ($tdomain ne '') {
                   2764:                 if (defined($dompriv)) {
                   2765:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2766:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2767:                 }
                   2768:                 if (($trest ne '') && (defined($coursepriv))) {
                   2769:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2770:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2771:                 }
                   2772:             }
                   2773:         }
                   2774:     }
                   2775: }
                   2776: 
1.678     raeburn  2777: sub group_roleprivs {
                   2778:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2779:     my $access = 1;
                   2780:     my $now = time;
                   2781:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2782:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2783:     if ($access) {
                   2784:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2785:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2786:     }
                   2787: }
1.567     raeburn  2788: 
                   2789: sub standard_roleprivs {
                   2790:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2791:     if (defined($pr{$trole.':s'})) {
                   2792:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2793:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2794:     }
                   2795:     if ($tdomain ne '') {
                   2796:         if (defined($pr{$trole.':d'})) {
                   2797:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2798:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2799:         }
                   2800:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2801:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2802:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2803:         }
                   2804:     }
                   2805: }
                   2806: 
                   2807: sub set_userprivs {
1.678     raeburn  2808:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2809:     my $author=0;
                   2810:     my $adv=0;
1.678     raeburn  2811:     my %grouproles = ();
                   2812:     if (keys(%{$allgroups}) > 0) {
                   2813:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2814:             my ($trole,$area,$sec,$extendedarea);
                   2815:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2816:                 $trole = $1;
                   2817:                 $area = $2;
1.681     raeburn  2818:                 $sec = $3;
                   2819:                 $extendedarea = $area.$sec;
                   2820:                 if (exists($$allgroups{$area})) {
                   2821:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2822:                         my $spec = $trole.'.'.$extendedarea;
                   2823:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2824:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2825:                     }
                   2826:                 }
                   2827:             }
                   2828:         }
                   2829:     }
                   2830:     foreach (keys(%grouproles)) {
                   2831:         $$allroles{$_} = $grouproles{$_};
                   2832:     }
1.567     raeburn  2833:     foreach (keys %{$allroles}) {
                   2834:         my %thesepriv=();
                   2835:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2836:         foreach (split(/:/,$$allroles{$_})) {
                   2837:             if ($_ ne '') {
                   2838:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2839:                 if ($restrictions eq '') {
                   2840:                     $thesepriv{$privilege}='F';
                   2841:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2842:                     $thesepriv{$privilege}.=$restrictions;
                   2843:                 }
                   2844:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2845:             }
                   2846:         }
                   2847:         my $thesestr='';
                   2848:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
                   2849:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
                   2850:     }
                   2851:     return ($author,$adv);
                   2852: }
                   2853: 
1.12      www      2854: # --------------------------------------------------------------- get interface
                   2855: 
                   2856: sub get {
1.131     albertel 2857:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2858:    my $items='';
1.191     harris41 2859:    foreach (@$storearr) {
1.12      www      2860:        $items.=escape($_).'&';
1.191     harris41 2861:    }
1.12      www      2862:    $items=~s/\&$//;
1.620     albertel 2863:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2864:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2865:    my $uhome=&homeserver($uname,$udomain);
                   2866: 
1.133     albertel 2867:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2868:    my @pairs=split(/\&/,$rep);
1.273     albertel 2869:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2870:      return @pairs;
                   2871:    }
1.15      www      2872:    my %returnhash=();
1.42      www      2873:    my $i=0;
1.191     harris41 2874:    foreach (@$storearr) {
1.557     albertel 2875:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2876:       $i++;
1.191     harris41 2877:    }
1.15      www      2878:    return %returnhash;
1.27      www      2879: }
                   2880: 
                   2881: # --------------------------------------------------------------- del interface
                   2882: 
                   2883: sub del {
1.133     albertel 2884:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2885:    my $items='';
1.191     harris41 2886:    foreach (@$storearr) {
1.27      www      2887:        $items.=escape($_).'&';
1.191     harris41 2888:    }
1.27      www      2889:    $items=~s/\&$//;
1.620     albertel 2890:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2891:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2892:    my $uhome=&homeserver($uname,$udomain);
                   2893: 
                   2894:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2895: }
                   2896: 
                   2897: # -------------------------------------------------------------- dump interface
                   2898: 
                   2899: sub dump {
1.702     albertel 2900:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.620     albertel 2901:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2902:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2903:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2904:    if ($regexp) {
                   2905:        $regexp=&escape($regexp);
                   2906:    } else {
                   2907:        $regexp='.';
                   2908:    }
1.702     albertel 2909:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.12      www      2910:    my @pairs=split(/\&/,$rep);
                   2911:    my %returnhash=();
1.191     harris41 2912:    foreach (@pairs) {
1.702     albertel 2913:       my ($key,$value)=split(/=/,$_,2);
1.557     albertel 2914:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2915:    }
                   2916:    return %returnhash;
1.407     www      2917: }
                   2918: 
1.717     albertel 2919: # --------------------------------------------------------- dumpstore interface
                   2920: 
                   2921: sub dumpstore {
                   2922:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2923:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2924: }
                   2925: 
1.407     www      2926: # -------------------------------------------------------------- keys interface
                   2927: 
                   2928: sub getkeys {
                   2929:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2930:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2931:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2932:    my $uhome=&homeserver($uname,$udomain);
                   2933:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2934:    my @keyarray=();
                   2935:    foreach (split(/\&/,$rep)) {
                   2936:       push (@keyarray,&unescape($_));
                   2937:    }
                   2938:    return @keyarray;
1.318     matthew  2939: }
                   2940: 
1.319     matthew  2941: # --------------------------------------------------------------- currentdump
                   2942: sub currentdump {
1.328     matthew  2943:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2944:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2945:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2946:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2947:    my $uhome = &homeserver($sname,$sdom);
                   2948:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2949:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2950:    #
1.318     matthew  2951:    my %returnhash=();
1.319     matthew  2952:    #
                   2953:    if ($rep eq "unknown_cmd") { 
                   2954:        # an old lond will not know currentdump
                   2955:        # Do a dump and make it look like a currentdump
1.326     matthew  2956:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2957:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2958:        my %hash = @tmp;
                   2959:        @tmp=();
1.424     matthew  2960:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2961:    } else {
                   2962:        my @pairs=split(/\&/,$rep);
                   2963:        foreach (@pairs) {
                   2964:            my ($key,$value)=split(/=/,$_);
                   2965:            my ($symb,$param) = split(/:/,$key);
                   2966:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2967:                                                         &thaw_unescape($value);
1.319     matthew  2968:        }
1.191     harris41 2969:    }
1.12      www      2970:    return %returnhash;
1.424     matthew  2971: }
                   2972: 
                   2973: sub convert_dump_to_currentdump{
                   2974:     my %hash = %{shift()};
                   2975:     my %returnhash;
                   2976:     # Code ripped from lond, essentially.  The only difference
                   2977:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2978:     # we might run in to problems with parameter names =~ /^v\./
                   2979:     while (my ($key,$value) = each(%hash)) {
                   2980:         my ($v,$symb,$param) = split(/:/,$key);
                   2981:         next if ($v eq 'version' || $symb eq 'keys');
                   2982:         next if (exists($returnhash{$symb}) &&
                   2983:                  exists($returnhash{$symb}->{$param}) &&
                   2984:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2985:         $returnhash{$symb}->{$param}=$value;
                   2986:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2987:     }
                   2988:     #
                   2989:     # Remove all of the keys in the hashes which keep track of
                   2990:     # the version of the parameter.
                   2991:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2992:         # use a foreach because we are going to delete from the hash.
                   2993:         foreach my $key (keys(%$param_hash)) {
                   2994:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2995:         }
                   2996:     }
                   2997:     return \%returnhash;
1.12      www      2998: }
                   2999: 
1.627     albertel 3000: # ------------------------------------------------------ critical inc interface
                   3001: 
                   3002: sub cinc {
                   3003:     return &inc(@_,'critical');
                   3004: }
                   3005: 
1.449     matthew  3006: # --------------------------------------------------------------- inc interface
                   3007: 
                   3008: sub inc {
1.627     albertel 3009:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3010:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3011:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3012:     my $uhome=&homeserver($uname,$udomain);
                   3013:     my $items='';
                   3014:     if (! ref($store)) {
                   3015:         # got a single value, so use that instead
                   3016:         $items = &escape($store).'=&';
                   3017:     } elsif (ref($store) eq 'SCALAR') {
                   3018:         $items = &escape($$store).'=&';        
                   3019:     } elsif (ref($store) eq 'ARRAY') {
                   3020:         $items = join('=&',map {&escape($_);} @{$store});
                   3021:     } elsif (ref($store) eq 'HASH') {
                   3022:         while (my($key,$value) = each(%{$store})) {
                   3023:             $items.= &escape($key).'='.&escape($value).'&';
                   3024:         }
                   3025:     }
                   3026:     $items=~s/\&$//;
1.627     albertel 3027:     if ($critical) {
                   3028: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3029:     } else {
                   3030: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3031:     }
1.449     matthew  3032: }
                   3033: 
1.12      www      3034: # --------------------------------------------------------------- put interface
                   3035: 
                   3036: sub put {
1.134     albertel 3037:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3039:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3040:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3041:    my $items='';
1.191     harris41 3042:    foreach (keys %$storehash) {
1.557     albertel 3043:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3044:    }
1.12      www      3045:    $items=~s/\&$//;
1.134     albertel 3046:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3047: }
                   3048: 
1.631     albertel 3049: # ------------------------------------------------------------ newput interface
                   3050: 
                   3051: sub newput {
                   3052:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3053:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3054:    if (!$uname) { $uname=$env{'user.name'}; }
                   3055:    my $uhome=&homeserver($uname,$udomain);
                   3056:    my $items='';
                   3057:    foreach my $key (keys(%$storehash)) {
                   3058:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3059:    }
                   3060:    $items=~s/\&$//;
                   3061:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3062: }
                   3063: 
                   3064: # ---------------------------------------------------------  putstore interface
                   3065: 
1.524     raeburn  3066: sub putstore {
1.715     albertel 3067:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3068:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3069:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3070:    my $uhome=&homeserver($uname,$udomain);
                   3071:    my $items='';
1.715     albertel 3072:    foreach my $key (keys(%$storehash)) {
                   3073:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3074:    }
1.715     albertel 3075:    $items=~s/\&$//;
1.716     albertel 3076:    my $esc_symb=&escape($symb);
                   3077:    my $esc_v=&escape($version);
1.715     albertel 3078:    my $reply =
1.716     albertel 3079:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3080: 	      $uhome);
                   3081:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3082:        # gfall back to way things use to be done
1.715     albertel 3083:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3084: 			    $uname);
1.524     raeburn  3085:    }
1.715     albertel 3086:    return $reply;
                   3087: }
                   3088: 
                   3089: sub old_putstore {
1.716     albertel 3090:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3091:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3092:     if (!$uname) { $uname=$env{'user.name'}; }
                   3093:     my $uhome=&homeserver($uname,$udomain);
                   3094:     my %newstorehash;
                   3095:     foreach (keys %$storehash) {
                   3096: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3097: 	$newstorehash{$key} = $storehash->{$_};
                   3098:     }
                   3099:     my $items='';
                   3100:     my %allitems = ();
                   3101:     foreach (keys %newstorehash) {
                   3102: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3103: 	    my $key = $1.':keys:'.$2;
                   3104: 	    $allitems{$key} .= $3.':';
                   3105: 	}
                   3106: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3107:     }
                   3108:     foreach (keys %allitems) {
                   3109: 	$allitems{$_} =~ s/\:$//;
                   3110: 	$items.= $_.'='.$allitems{$_}.'&';
                   3111:     }
                   3112:     $items=~s/\&$//;
                   3113:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3114: }
                   3115: 
1.47      www      3116: # ------------------------------------------------------ critical put interface
                   3117: 
                   3118: sub cput {
1.134     albertel 3119:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3120:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3121:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3122:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3123:    my $items='';
1.191     harris41 3124:    foreach (keys %$storehash) {
1.715     albertel 3125:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3126:    }
1.47      www      3127:    $items=~s/\&$//;
1.134     albertel 3128:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3129: }
                   3130: 
                   3131: # -------------------------------------------------------------- eget interface
                   3132: 
                   3133: sub eget {
1.133     albertel 3134:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3135:    my $items='';
1.191     harris41 3136:    foreach (@$storearr) {
1.12      www      3137:        $items.=escape($_).'&';
1.191     harris41 3138:    }
1.12      www      3139:    $items=~s/\&$//;
1.620     albertel 3140:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3141:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3142:    my $uhome=&homeserver($uname,$udomain);
                   3143:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3144:    my @pairs=split(/\&/,$rep);
                   3145:    my %returnhash=();
1.42      www      3146:    my $i=0;
1.191     harris41 3147:    foreach (@$storearr) {
1.557     albertel 3148:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3149:       $i++;
1.191     harris41 3150:    }
1.12      www      3151:    return %returnhash;
                   3152: }
                   3153: 
1.667     albertel 3154: # ------------------------------------------------------------ tmpput interface
                   3155: sub tmpput {
                   3156:     my ($storehash,$server)=@_;
                   3157:     my $items='';
                   3158:     foreach (keys(%$storehash)) {
                   3159: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3160:     }
                   3161:     $items=~s/\&$//;
                   3162:     return &reply("tmpput:$items",$server);
                   3163: }
                   3164: 
                   3165: # ------------------------------------------------------------ tmpget interface
                   3166: sub tmpget {
1.688     albertel 3167:     my ($token,$server)=@_;
                   3168:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3169:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3170:     my %returnhash;
                   3171:     foreach my $item (split(/\&/,$rep)) {
                   3172: 	my ($key,$value)=split(/=/,$item);
                   3173: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3174:     }
                   3175:     return %returnhash;
                   3176: }
                   3177: 
1.688     albertel 3178: # ------------------------------------------------------------ tmpget interface
                   3179: sub tmpdel {
                   3180:     my ($token,$server)=@_;
                   3181:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3182:     return &reply("tmpdel:$token",$server);
                   3183: }
                   3184: 
1.341     www      3185: # ---------------------------------------------- Custom access rule evaluation
                   3186: 
                   3187: sub customaccess {
                   3188:     my ($priv,$uri)=@_;
1.620     albertel 3189:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3190:     $urealm=~s/^\W//;
                   3191:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3192:     my $access=0;
                   3193:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3194: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3195:         if ($role) {
                   3196: 	   if ($role ne $urole) { next; }
                   3197:         }
                   3198:         foreach (split(/\s*\,\s*/,$realm)) {
                   3199:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3200:             if ($tdom) {
                   3201: 		if ($tdom ne $udom) { next; }
                   3202:             }
                   3203:             if ($tcrs) {
                   3204: 		if ($tcrs ne $ucrs) { next; }
                   3205:             }
                   3206:             if ($tsec) {
                   3207: 		if ($tsec ne $usec) { next; }
                   3208:             }
                   3209:             $access=($effect eq 'allow');
                   3210:             last;
1.342     www      3211:         }
1.402     bowersj2 3212: 	if ($realm eq '' && $role eq '') {
                   3213:             $access=($effect eq 'allow');
                   3214: 	}
1.341     www      3215:     }
                   3216:     return $access;
                   3217: }
                   3218: 
1.103     harris41 3219: # ------------------------------------------------- Check for a user privilege
1.12      www      3220: 
                   3221: sub allowed {
1.579     albertel 3222:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3223:     my $ver_orguri=$uri;
1.439     www      3224:     $uri=&deversion($uri);
1.152     www      3225:     my $orguri=$uri;
1.52      www      3226:     $uri=&declutter($uri);
1.545     banghart 3227:     
1.620     albertel 3228:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3229: # Free bre access to adm and meta resources
1.529     albertel 3230:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3231: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3232: 	return 'F';
1.159     www      3233:     }
                   3234: 
1.545     banghart 3235: # Free bre access to user's own portfolio contents
1.714     raeburn  3236:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3237:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3238: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3239:         return 'F';
                   3240:     }
                   3241: 
1.714     raeburn  3242: # bre access to group if user has rgf priv for this group and course.
                   3243:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3244:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3245:         if (exists($env{'request.course.id'})) {
                   3246:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3247:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3248:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3249:                 my $courseprivid=$env{'request.course.id'};
                   3250:                 $courseprivid=~s/\_/\//;
                   3251:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3252:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3253:                     return $1; 
                   3254:                 }
                   3255:             }
                   3256:         }
                   3257:     }
                   3258: 
1.159     www      3259: # Free bre to public access
                   3260: 
                   3261:     if ($priv eq 'bre') {
1.238     www      3262:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3263: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3264:            return 'F'; 
                   3265:         }
1.238     www      3266:         if ($copyright eq 'priv') {
                   3267:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3268: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3269: 		return '';
                   3270:             }
                   3271:         }
                   3272:         if ($copyright eq 'domain') {
                   3273:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3274: 	    unless (($env{'user.domain'} eq $1) ||
                   3275:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3276: 		return '';
                   3277:             }
1.262     matthew  3278:         }
1.620     albertel 3279:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3280:             # Library role, so allow browsing of resources in this domain.
                   3281:             return 'F';
1.238     www      3282:         }
1.341     www      3283:         if ($copyright eq 'custom') {
                   3284: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3285:         }
1.14      www      3286:     }
1.264     matthew  3287:     # Domain coordinator is trying to create a course
1.620     albertel 3288:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3289:         # uri is the requested domain in this case.
                   3290:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3291:         # a role of dc for the domain in question.
1.620     albertel 3292:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3293:     }
1.29      www      3294: 
1.52      www      3295:     my $thisallowed='';
                   3296:     my $statecond=0;
                   3297:     my $courseprivid='';
                   3298: 
                   3299: # Course
                   3300: 
1.620     albertel 3301:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3302:        $thisallowed.=$1;
                   3303:     }
1.29      www      3304: 
1.52      www      3305: # Domain
                   3306: 
1.620     albertel 3307:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3308:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3309:        $thisallowed.=$1;
                   3310:     }
1.52      www      3311: 
                   3312: # Course: uri itself is a course
1.66      www      3313:     my $courseuri=$uri;
                   3314:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3315:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3316: 
1.620     albertel 3317:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3318:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3319:        $thisallowed.=$1;
                   3320:     }
1.29      www      3321: 
1.678     raeburn  3322: # Group: uri itself is a group
                   3323:     my $groupuri=$uri;
                   3324:     $groupuri=~s/^([^\/])/\/$1/;
                   3325:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3326:        =~/\Q$priv\E\&([^\:]*)/) {
                   3327:        $thisallowed.=$1;
                   3328:     }
                   3329: 
1.665     albertel 3330: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3331: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3332:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3333: 	$thisallowed='';
1.671     raeburn  3334:         my ($match)=&is_on_map($uri);
                   3335:         if ($match) {
                   3336:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3337:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3338:                 $thisallowed.=$1;
                   3339:             }
                   3340:         } else {
1.705     albertel 3341:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3342:             if ($refuri) {
                   3343:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3344:                     $thisallowed='F';
1.671     raeburn  3345:                 } else {
                   3346:                     $refuri=&declutter($refuri);
                   3347:                     my ($match) = &is_on_map($refuri);
                   3348:                     if ($match) {
                   3349:                         $thisallowed='F';
                   3350:                     }
1.669     raeburn  3351:                 }
1.671     raeburn  3352:             }
                   3353:         }
1.314     www      3354:     }
1.492     albertel 3355: 
1.52      www      3356: # Full access at system, domain or course-wide level? Exit.
1.29      www      3357: 
                   3358:     if ($thisallowed=~/F/) {
                   3359: 	return 'F';
                   3360:     }
                   3361: 
1.52      www      3362: # If this is generating or modifying users, exit with special codes
1.29      www      3363: 
1.643     www      3364:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3365: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3366: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3367: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3368: 	    unless ($auname) { return $thisallowed; }
                   3369: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3370: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3371: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3372: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3373: 	}
1.52      www      3374: 	return $thisallowed;
                   3375:     }
                   3376: #
1.103     harris41 3377: # Gathered so far: system, domain and course wide privileges
1.52      www      3378: #
                   3379: # Course: See if uri or referer is an individual resource that is part of 
                   3380: # the course
                   3381: 
1.620     albertel 3382:     if ($env{'request.course.id'}) {
1.232     www      3383: 
1.620     albertel 3384:        $courseprivid=$env{'request.course.id'};
                   3385:        if ($env{'request.course.sec'}) {
                   3386:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3387:        }
                   3388:        $courseprivid=~s/\_/\//;
                   3389:        my $checkreferer=1;
1.232     www      3390:        my ($match,$cond)=&is_on_map($uri);
                   3391:        if ($match) {
                   3392:            $statecond=$cond;
1.620     albertel 3393:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3394:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3395:                $thisallowed.=$1;
                   3396:                $checkreferer=0;
                   3397:            }
1.29      www      3398:        }
1.83      www      3399:        
1.148     www      3400:        if ($checkreferer) {
1.620     albertel 3401: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3402:             unless ($refuri) {
1.620     albertel 3403:                 foreach (keys %env) {
1.148     www      3404: 		    if ($_=~/^httpref\..*\*/) {
                   3405: 			my $pattern=$_;
1.156     www      3406:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3407:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3408:                         $pattern=~s/\//\\\//g;
1.152     www      3409:                         if ($orguri=~/$pattern/) {
1.620     albertel 3410: 			    $refuri=$env{$_};
1.148     www      3411:                         }
                   3412:                     }
1.191     harris41 3413:                 }
1.148     www      3414:             }
1.232     www      3415: 
1.148     www      3416:          if ($refuri) { 
1.152     www      3417: 	  $refuri=&declutter($refuri);
1.232     www      3418:           my ($match,$cond)=&is_on_map($refuri);
                   3419:             if ($match) {
                   3420:               my $refstatecond=$cond;
1.620     albertel 3421:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3422:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3423:                   $thisallowed.=$1;
1.53      www      3424:                   $uri=$refuri;
                   3425:                   $statecond=$refstatecond;
1.52      www      3426:               }
                   3427:           }
1.148     www      3428:         }
1.29      www      3429:        }
1.52      www      3430:    }
1.29      www      3431: 
1.52      www      3432: #
1.103     harris41 3433: # Gathered now: all privileges that could apply, and condition number
1.52      www      3434: # 
                   3435: #
                   3436: # Full or no access?
                   3437: #
1.29      www      3438: 
1.52      www      3439:     if ($thisallowed=~/F/) {
                   3440: 	return 'F';
                   3441:     }
1.29      www      3442: 
1.52      www      3443:     unless ($thisallowed) {
                   3444:         return '';
                   3445:     }
1.29      www      3446: 
1.52      www      3447: # Restrictions exist, deal with them
                   3448: #
                   3449: #   C:according to course preferences
                   3450: #   R:according to resource settings
                   3451: #   L:unless locked
                   3452: #   X:according to user session state
                   3453: #
                   3454: 
                   3455: # Possibly locked functionality, check all courses
1.54      www      3456: # Locks might take effect only after 10 minutes cache expiration for other
                   3457: # courses, and 2 minutes for current course
1.52      www      3458: 
                   3459:     my $envkey;
                   3460:     if ($thisallowed=~/L/) {
1.620     albertel 3461:         foreach $envkey (keys %env) {
1.54      www      3462:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3463:                my $courseid=$2;
                   3464:                my $roleid=$1.'.'.$2;
1.92      www      3465:                $courseid=~s/^\///;
1.54      www      3466:                my $expiretime=600;
1.620     albertel 3467:                if ($env{'request.role'} eq $roleid) {
1.54      www      3468: 		  $expiretime=120;
                   3469:                }
                   3470: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3471:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3472:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3473: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3474:                }
1.620     albertel 3475:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3476:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3477: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3478:                        &log($env{'user.domain'},$env{'user.name'},
                   3479:                             $env{'user.home'},
1.57      www      3480:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3481:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3482:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3483: 		       return '';
                   3484:                    }
                   3485:                }
1.620     albertel 3486:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3487:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3488: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3489:                        &log($env{'user.domain'},$env{'user.name'},
                   3490:                             $env{'user.home'},
1.57      www      3491:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3492:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3493:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3494: 		       return '';
                   3495:                    }
                   3496:                }
                   3497: 	   }
1.29      www      3498:        }
1.52      www      3499:     }
                   3500:    
                   3501: #
                   3502: # Rest of the restrictions depend on selected course
                   3503: #
                   3504: 
1.620     albertel 3505:     unless ($env{'request.course.id'}) {
1.52      www      3506:        return '1';
                   3507:     }
1.29      www      3508: 
1.52      www      3509: #
                   3510: # Now user is definitely in a course
                   3511: #
1.53      www      3512: 
                   3513: 
                   3514: # Course preferences
                   3515: 
                   3516:    if ($thisallowed=~/C/) {
1.620     albertel 3517:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3518:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3519:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3520: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3521: 	   if ($priv ne 'pch') { 
                   3522: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3523: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3524: 			$env{'request.course.id'});
                   3525: 	   }
1.237     www      3526:            return '';
                   3527:        }
                   3528: 
1.620     albertel 3529:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3530: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3531: 	   if ($priv ne 'pch') { 
                   3532: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3533: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3534: 			$env{'request.course.id'});
                   3535: 	   }
1.54      www      3536:            return '';
                   3537:        }
1.53      www      3538:    }
                   3539: 
                   3540: # Resource preferences
                   3541: 
                   3542:    if ($thisallowed=~/R/) {
1.620     albertel 3543:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3544:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3545: 	   if ($priv ne 'pch') { 
                   3546: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3547: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3548: 	   }
                   3549: 	   return '';
1.54      www      3550:        }
1.53      www      3551:    }
1.30      www      3552: 
1.246     www      3553: # Restricted by state or randomout?
1.30      www      3554: 
1.52      www      3555:    if ($thisallowed=~/X/) {
1.620     albertel 3556:       if ($env{'acc.randomout'}) {
1.579     albertel 3557: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3558:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3559:             return ''; 
                   3560:          }
1.247     www      3561:       }
                   3562:       if (&condval($statecond)) {
1.52      www      3563: 	 return '2';
                   3564:       } else {
                   3565:          return '';
                   3566:       }
                   3567:    }
1.30      www      3568: 
1.52      www      3569:    return 'F';
1.232     www      3570: }
                   3571: 
1.710     albertel 3572: sub split_uri_for_cond {
                   3573:     my $uri=&deversion(&declutter(shift));
                   3574:     my @uriparts=split(/\//,$uri);
                   3575:     my $filename=pop(@uriparts);
                   3576:     my $pathname=join('/',@uriparts);
                   3577:     return ($pathname,$filename);
                   3578: }
1.232     www      3579: # --------------------------------------------------- Is a resource on the map?
                   3580: 
                   3581: sub is_on_map {
1.710     albertel 3582:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3583:     #Trying to find the conditional for the file
1.620     albertel 3584:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3585: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3586:     if ($match) {
1.289     bowersj2 3587: 	return (1,$1);
                   3588:     } else {
1.434     www      3589: 	return (0,0);
1.289     bowersj2 3590:     }
1.12      www      3591: }
                   3592: 
1.427     www      3593: # --------------------------------------------------------- Get symb from alias
                   3594: 
                   3595: sub get_symb_from_alias {
                   3596:     my $symb=shift;
                   3597:     my ($map,$resid,$url)=&decode_symb($symb);
                   3598: # Already is a symb
                   3599:     if ($url) { return $symb; }
                   3600: # Must be an alias
                   3601:     my $aliassymb='';
                   3602:     my %bighash;
1.620     albertel 3603:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3604:                             &GDBM_READER(),0640)) {
                   3605:         my $rid=$bighash{'mapalias_'.$symb};
                   3606: 	if ($rid) {
                   3607: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3608: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3609: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3610: 	}
                   3611:         untie %bighash;
                   3612:     }
                   3613:     return $aliassymb;
                   3614: }
                   3615: 
1.12      www      3616: # ----------------------------------------------------------------- Define Role
                   3617: 
                   3618: sub definerole {
                   3619:   if (allowed('mcr','/')) {
                   3620:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3621:     foreach (split(':',$sysrole)) {
1.21      www      3622: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3623:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3624:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3625: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3626:                return "refused:s:$crole&$cqual"; 
                   3627:             }
                   3628:         }
1.191     harris41 3629:     }
1.392     www      3630:     foreach (split(':',$domrole)) {
1.21      www      3631: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3632:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3633:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3634: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3635:                return "refused:d:$crole&$cqual"; 
                   3636:             }
                   3637:         }
1.191     harris41 3638:     }
1.392     www      3639:     foreach (split(':',$courole)) {
1.21      www      3640: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3641:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3642:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3643: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3644:                return "refused:c:$crole&$cqual"; 
                   3645:             }
                   3646:         }
1.191     harris41 3647:     }
1.620     albertel 3648:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3649:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3650: 	        "rolesdef_$rolename=".
                   3651:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3652:     return reply($command,$env{'user.home'});
1.12      www      3653:   } else {
                   3654:     return 'refused';
                   3655:   }
1.105     harris41 3656: }
                   3657: 
                   3658: # ---------------- Make a metadata query against the network of library servers
                   3659: 
                   3660: sub metadata_query {
1.244     matthew  3661:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3662:     my %rhash;
1.244     matthew  3663:     my @server_list = (defined($server_array) ? @$server_array
                   3664:                                               : keys(%libserv) );
                   3665:     for my $server (@server_list) {
1.118     harris41 3666: 	unless ($custom or $customshow) {
                   3667: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3668: 	    $rhash{$server}=$reply;
                   3669: 	}
                   3670: 	else {
                   3671: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3672: 			     &escape($custom).':'.&escape($customshow),
                   3673: 			     $server);
                   3674: 	    $rhash{$server}=$reply;
                   3675: 	}
1.112     harris41 3676:     }
1.118     harris41 3677:     return \%rhash;
1.240     www      3678: }
                   3679: 
                   3680: # ----------------------------------------- Send log queries and wait for reply
                   3681: 
                   3682: sub log_query {
                   3683:     my ($uname,$udom,$query,%filters)=@_;
                   3684:     my $uhome=&homeserver($uname,$udom);
                   3685:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3686:     my $uhost=$hostname{$uhome};
1.241     www      3687:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3688:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3689:                        $uhome);
1.479     albertel 3690:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3691:     return get_query_reply($queryid);
                   3692: }
                   3693: 
1.508     raeburn  3694: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3695: 
                   3696: sub fetch_enrollment_query {
1.511     raeburn  3697:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3698:     my $homeserver;
1.547     raeburn  3699:     my $maxtries = 1;
1.508     raeburn  3700:     if ($context eq 'automated') {
                   3701:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3702:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3703:     } else {
                   3704:         $homeserver = &homeserver($cnum,$dom);
                   3705:     }
1.506     raeburn  3706:     my $host=$hostname{$homeserver};
                   3707:     my $cmd = '';
                   3708:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3709:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3710:     }
                   3711:     $cmd =~ s/%%$//;
                   3712:     $cmd = &escape($cmd);
                   3713:     my $query = 'fetchenrollment';
1.620     albertel 3714:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3715:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3716:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3717:         return 'error: '.$queryid;
                   3718:     }
1.506     raeburn  3719:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3720:     my $tries = 1;
                   3721:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3722:         $reply = &get_query_reply($queryid);
                   3723:         $tries ++;
                   3724:     }
1.526     raeburn  3725:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3726:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3727:     } else {
1.515     raeburn  3728:         my @responses = split/:/,$reply;
                   3729:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3730:             foreach (@responses) {
                   3731:                 my ($key,$value) = split/=/,$_;
                   3732:                 $$replyref{$key} = $value;
                   3733:             }
                   3734:         } else {
1.506     raeburn  3735:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3736:             foreach (@responses) {
                   3737:                 my ($key,$value) = split/=/,$_;
                   3738:                 $$replyref{$key} = $value;
                   3739:                 if ($value > 0) {
                   3740:                     foreach (@{$$affiliatesref{$key}}) {
                   3741:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3742:                         my $destname = $pathname.'/'.$filename;
                   3743:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3744:                         if ($xml_classlist =~ /^error/) {
                   3745:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3746:                         } else {
1.506     raeburn  3747:                             if ( open(FILE,">$destname") ) {
                   3748:                                 print FILE &unescape($xml_classlist);
                   3749:                                 close(FILE);
1.526     raeburn  3750:                             } else {
                   3751:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3752:                             }
                   3753:                         }
                   3754:                     }
                   3755:                 }
                   3756:             }
                   3757:         }
                   3758:         return 'ok';
                   3759:     }
                   3760:     return 'error';
                   3761: }
                   3762: 
1.242     www      3763: sub get_query_reply {
                   3764:     my $queryid=shift;
1.240     www      3765:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3766:     my $reply='';
                   3767:     for (1..100) {
                   3768: 	sleep 2;
                   3769:         if (-e $replyfile.'.end') {
1.448     albertel 3770: 	    if (open(my $fh,$replyfile)) {
1.240     www      3771:                $reply.=<$fh>;
1.448     albertel 3772:                close($fh);
1.240     www      3773: 	   } else { return 'error: reply_file_error'; }
1.242     www      3774:            return &unescape($reply);
                   3775: 	}
1.240     www      3776:     }
1.242     www      3777:     return 'timeout:'.$queryid;
1.240     www      3778: }
                   3779: 
                   3780: sub courselog_query {
1.241     www      3781: #
                   3782: # possible filters:
                   3783: # url: url or symb
                   3784: # username
                   3785: # domain
                   3786: # action: view, submit, grade
                   3787: # start: timestamp
                   3788: # end: timestamp
                   3789: #
1.240     www      3790:     my (%filters)=@_;
1.620     albertel 3791:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3792:     if ($filters{'url'}) {
                   3793: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3794:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3795:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3796:     }
1.620     albertel 3797:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3798:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3799:     return &log_query($cname,$cdom,'courselog',%filters);
                   3800: }
                   3801: 
                   3802: sub userlog_query {
                   3803:     my ($uname,$udom,%filters)=@_;
                   3804:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3805: }
                   3806: 
1.506     raeburn  3807: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3808: 
                   3809: sub auto_run {
1.508     raeburn  3810:     my ($cnum,$cdom) = @_;
                   3811:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3812:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3813:     return $response;
                   3814: }
                   3815:                                                                                    
                   3816: sub auto_get_sections {
1.508     raeburn  3817:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3818:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3819:     my @secs = ();
1.511     raeburn  3820:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3821:     unless ($response eq 'refused') {
                   3822:         @secs = split/:/,$response;
                   3823:     }
                   3824:     return @secs;
                   3825: }
                   3826:                                                                                    
                   3827: sub auto_new_course {
1.508     raeburn  3828:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3829:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3830:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3831:     return $response;
                   3832: }
                   3833:                                                                                    
                   3834: sub auto_validate_courseID {
1.508     raeburn  3835:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3836:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3837:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3838:     return $response;
                   3839: }
                   3840:                                                                                    
                   3841: sub auto_create_password {
1.508     raeburn  3842:     my ($cnum,$cdom,$authparam) = @_;
                   3843:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3844:     my $create_passwd = 0;
                   3845:     my $authchk = '';
1.511     raeburn  3846:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3847:     if ($response eq 'refused') {
                   3848:         $authchk = 'refused';
                   3849:     } else {
                   3850:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3851:     }
                   3852:     return ($authparam,$create_passwd,$authchk);
                   3853: }
                   3854: 
1.706     raeburn  3855: sub auto_photo_permission {
                   3856:     my ($cnum,$cdom,$students) = @_;
                   3857:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 3858:     my ($outcome,$perm_reqd,$conditions) = 
                   3859: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 3860:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3861: 	return (undef,undef);
                   3862:     }
1.706     raeburn  3863:     return ($outcome,$perm_reqd,$conditions);
                   3864: }
                   3865: 
                   3866: sub auto_checkphotos {
                   3867:     my ($uname,$udom,$pid) = @_;
                   3868:     my $homeserver = &homeserver($uname,$udom);
                   3869:     my ($result,$resulttype);
                   3870:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 3871: 				   &escape($uname).':'.&escape($pid),
                   3872: 				   $homeserver));
1.709     albertel 3873:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3874: 	return (undef,undef);
                   3875:     }
1.706     raeburn  3876:     if ($outcome) {
                   3877:         ($result,$resulttype) = split(/:/,$outcome);
                   3878:     } 
                   3879:     return ($result,$resulttype);
                   3880: }
                   3881: 
                   3882: sub auto_photochoice {
                   3883:     my ($cnum,$cdom) = @_;
                   3884:     my $homeserver = &homeserver($cnum,$cdom);
                   3885:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 3886: 						       &escape($cdom),
                   3887: 						       $homeserver)));
1.709     albertel 3888:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3889: 	return (undef,undef);
                   3890:     }
1.706     raeburn  3891:     return ($update,$comment);
                   3892: }
                   3893: 
                   3894: sub auto_photoupdate {
                   3895:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   3896:     my $homeserver = &homeserver($cnum,$dom);
                   3897:     my $host=$hostname{$homeserver};
                   3898:     my $cmd = '';
                   3899:     my $maxtries = 1;
                   3900:     foreach (keys %{$affiliatesref}) {
                   3901:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   3902:     }
                   3903:     $cmd =~ s/%%$//;
                   3904:     $cmd = &escape($cmd);
                   3905:     my $query = 'institutionalphotos';
                   3906:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   3907:     unless ($queryid=~/^\Q$host\E\_/) {
                   3908:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   3909:         return 'error: '.$queryid;
                   3910:     }
                   3911:     my $reply = &get_query_reply($queryid);
                   3912:     my $tries = 1;
                   3913:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3914:         $reply = &get_query_reply($queryid);
                   3915:         $tries ++;
                   3916:     }
                   3917:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   3918:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   3919:     } else {
                   3920:         my @responses = split(/:/,$reply);
                   3921:         my $outcome = shift(@responses); 
                   3922:         foreach my $item (@responses) {
                   3923:             my ($key,$value) = split(/=/,$item);
                   3924:             $$photo{$key} = $value;
                   3925:         }
                   3926:         return $outcome;
                   3927:     }
                   3928:     return 'error';
                   3929: }
                   3930: 
1.521     raeburn  3931: sub auto_instcode_format {
                   3932:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3933:     my $courses = '';
                   3934:     my $homeserver;
                   3935:     if ($caller eq 'global') {
1.584     raeburn  3936:         foreach my $tryserver (keys %libserv) {
                   3937:             if ($hostdom{$tryserver} eq $codedom) {
                   3938:                 $homeserver = $tryserver;
                   3939:                 last;
                   3940:             }
                   3941:         }
1.620     albertel 3942:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3943:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3944:         }
1.521     raeburn  3945:     } else {
                   3946:         $homeserver = &homeserver($caller,$codedom);
                   3947:     }
                   3948:     foreach (keys %{$instcodes}) {
                   3949:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3950:     }
                   3951:     chop($courses);
                   3952:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3953:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3954:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3955:         %{$codes} = &str2hash($codes_str);
                   3956:         @{$codetitles} = &str2array($codetitles_str);
                   3957:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3958:         %{$cat_order} = &str2hash($cat_order_str);
                   3959:         return 'ok';
                   3960:     }
                   3961:     return $response;
                   3962: }
                   3963: 
1.679     raeburn  3964: # ------------------------------------------------------- Course Group routines
                   3965: 
                   3966: sub get_coursegroups {
1.683     raeburn  3967:     my ($cdom,$cnum,$group) = @_;
                   3968:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  3969: }
                   3970: 
                   3971: sub modify_coursegroup {
                   3972:     my ($cdom,$cnum,$groupsettings) = @_;
                   3973:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   3974: }
                   3975: 
                   3976: sub modify_group_roles {
                   3977:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   3978:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   3979:     my $role = 'gr/'.&escape($userprivs);
                   3980:     my ($uname,$udom) = split(/:/,$user);
                   3981:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  3982:     if ($result eq 'ok') {
                   3983:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   3984:     }
                   3985: 
1.679     raeburn  3986:     return $result;
                   3987: }
                   3988: 
                   3989: sub modify_coursegroup_membership {
                   3990:     my ($cdom,$cnum,$membership) = @_;
                   3991:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   3992:     return $result;
                   3993: }
                   3994: 
1.682     raeburn  3995: sub get_active_groups {
                   3996:     my ($udom,$uname,$cdom,$cnum) = @_;
                   3997:     my $now = time;
                   3998:     my %groups = ();
                   3999:     foreach my $key (keys(%env)) {
                   4000:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4001:             my ($start,$end) = split(/\./,$env{$key});
                   4002:             if (($end!=0) && ($end<$now)) { next; }
                   4003:             if (($start!=0) && ($start>$now)) { next; }
                   4004:             if ($1 eq $cdom && $2 eq $cnum) {
                   4005:                 $groups{$3} = $env{$key} ;
                   4006:             }
                   4007:         }
                   4008:     }
                   4009:     return %groups;
                   4010: }
                   4011: 
1.683     raeburn  4012: sub get_group_membership {
                   4013:     my ($cdom,$cnum,$group) = @_;
                   4014:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4015: }
                   4016: 
                   4017: sub get_users_groups {
                   4018:     my ($udom,$uname,$courseid) = @_;
                   4019:     my $cachetime=1800;
                   4020:     $courseid=~s/\_/\//g;
                   4021:     $courseid=~s/^(\w)/\/$1/;
                   4022: 
                   4023:     my $hashid="$udom:$uname:$courseid";
                   4024:     my ($result,$cached)=&is_cached_new('getgroups',$hashid);
                   4025:     if (defined($cached)) { return $result; }
                   4026: 
                   4027:     my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4028:     my ($tmp) = keys(%roleshash);
                   4029:     if ($tmp=~/^error:/) {
                   4030:         &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4031:         return '';
                   4032:     } else {
                   4033:         my $grouplist;
                   4034:         foreach my $key (keys %roleshash) {
                   4035:             if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
1.727     raeburn  4036:                 unless ($roleshash{$key} =~ /_\d+_\-1$/) {   # deleted membership
1.683     raeburn  4037:                     $grouplist .= $1.':';
                   4038:                 }
                   4039:             }
                   4040:         }
                   4041:         $grouplist =~ s/:$//;
                   4042:         return &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
                   4043:     }
                   4044: }
                   4045: 
                   4046: sub devalidate_getgroups_cache {
                   4047:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4048:     my $courseid = $cdom.'_'.$cnum;
                   4049:     $courseid=~s/\_/\//g;
                   4050:     $courseid=~s/^(\w)/\/$1/;
                   4051:     my $hashid="$udom:$uname:$courseid";
                   4052:     &devalidate_cache_new('getgroups',$hashid);
                   4053: }
                   4054: 
1.12      www      4055: # ------------------------------------------------------------------ Plain Text
                   4056: 
                   4057: sub plaintext {
1.22      www      4058:     my $short=shift;
1.676     albertel 4059:     return &Apache::lonlocal::mt($prp{$short});
1.12      www      4060: }
                   4061: 
                   4062: # ----------------------------------------------------------------- Assign Role
                   4063: 
                   4064: sub assignrole {
1.357     www      4065:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4066:     my $mrole;
                   4067:     if ($role =~ /^cr\//) {
1.393     www      4068:         my $cwosec=$url;
                   4069:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4070: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4071:            &logthis('Refused custom assignrole: '.
                   4072:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4073: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4074:            return 'refused'; 
                   4075:         }
1.21      www      4076:         $mrole='cr';
1.678     raeburn  4077:     } elsif ($role =~ /^gr\//) {
                   4078:         my $cwogrp=$url;
                   4079:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4080:         unless (&allowed('mdg',$cwogrp)) {
                   4081:             &logthis('Refused group assignrole: '.
                   4082:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4083:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4084:             return 'refused';
                   4085:         }
                   4086:         $mrole='gr';
1.21      www      4087:     } else {
1.82      www      4088:         my $cwosec=$url;
1.83      www      4089:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4090:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4091:            &logthis('Refused assignrole: '.
                   4092:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4093: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4094:            return 'refused'; 
                   4095:         }
1.21      www      4096:         $mrole=$role;
                   4097:     }
1.620     albertel 4098:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4099:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4100:     if ($end) { $command.='_'.$end; }
1.21      www      4101:     if ($start) {
                   4102: 	if ($end) { 
1.81      www      4103:            $command.='_'.$start; 
1.21      www      4104:         } else {
1.81      www      4105:            $command.='_0_'.$start;
1.21      www      4106:         }
                   4107:     }
1.357     www      4108: # actually delete
                   4109:     if ($deleteflag) {
1.373     www      4110: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4111: # modify command to delete the role
1.620     albertel 4112:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4113:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4114: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4115: # set start and finish to negative values for userrolelog
                   4116:            $start=-1;
                   4117:            $end=-1;
                   4118:         }
                   4119:     }
                   4120: # send command
1.349     www      4121:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4122: # log new user role if status is ok
1.349     www      4123:     if ($answer eq 'ok') {
1.663     raeburn  4124: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.349     www      4125:     }
                   4126:     return $answer;
1.169     harris41 4127: }
                   4128: 
                   4129: # -------------------------------------------------- Modify user authentication
1.197     www      4130: # Overrides without validation
                   4131: 
1.169     harris41 4132: sub modifyuserauth {
                   4133:     my ($udom,$uname,$umode,$upass)=@_;
                   4134:     my $uhome=&homeserver($uname,$udom);
1.197     www      4135:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4136:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4137:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4138:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4139:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4140: 		     &escape($upass),$uhome);
1.620     albertel 4141:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4142:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4143:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4144:     &log($udom,,$uname,$uhome,
1.620     albertel 4145:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4146:                                      $env{'user.name'}.', '.$umode.
1.197     www      4147:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4148:     unless ($reply eq 'ok') {
1.197     www      4149:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4150: 	return 'error: '.$reply;
                   4151:     }   
1.170     harris41 4152:     return 'ok';
1.80      www      4153: }
                   4154: 
1.81      www      4155: # --------------------------------------------------------------- Modify a user
1.80      www      4156: 
1.81      www      4157: sub modifyuser {
1.206     matthew  4158:     my ($udom,    $uname, $uid,
                   4159:         $umode,   $upass, $first,
                   4160:         $middle,  $last,  $gene,
1.387     www      4161:         $forceid, $desiredhome, $email)=@_;
1.198     www      4162:     $udom=~s/\W//g;
                   4163:     $uname=~s/\W//g;
1.81      www      4164:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4165:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4166: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4167:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4168:                                      ' desiredhome not specified'). 
1.620     albertel 4169:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4170:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4171:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4172: # ----------------------------------------------------------------- Create User
1.406     albertel 4173:     if (($uhome eq 'no_host') && 
                   4174: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4175:         my $unhome='';
1.209     matthew  4176:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4177:             $unhome = $desiredhome;
1.620     albertel 4178: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4179: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4180:         } else { # load balancing routine for determining $unhome
1.80      www      4181:             my $tryserver;
1.81      www      4182:             my $loadm=10000000;
1.80      www      4183:             foreach $tryserver (keys %libserv) {
                   4184: 	       if ($hostdom{$tryserver} eq $udom) {
                   4185:                   my $answer=reply('load',$tryserver);
                   4186:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4187: 		      $loadm=$answer;
                   4188:                       $unhome=$tryserver;
                   4189:                   }
                   4190: 	       }
                   4191: 	    }
                   4192:         }
                   4193:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4194: 	    return 'error: unable to find a home server for '.$uname.
                   4195:                    ' in domain '.$udom;
1.80      www      4196:         }
                   4197:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4198:                          &escape($upass),$unhome);
                   4199: 	unless ($reply eq 'ok') {
                   4200:             return 'error: '.$reply;
                   4201:         }   
1.230     stredwic 4202:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4203:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4204: 	    return 'error: unable verify users home machine.';
1.80      www      4205:         }
1.209     matthew  4206:     }   # End of creation of new user
1.80      www      4207: # ---------------------------------------------------------------------- Add ID
                   4208:     if ($uid) {
                   4209:        $uid=~tr/A-Z/a-z/;
                   4210:        my %uidhash=&idrget($udom,$uname);
1.196     www      4211:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4212:          && (!$forceid)) {
1.80      www      4213: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4214: 	      return 'error: user id "'.$uid.'" does not match '.
                   4215:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4216:           }
                   4217:        } else {
                   4218: 	  &idput($udom,($uname => $uid));
                   4219:        }
                   4220:     }
                   4221: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4222:     my @tmp=&get('environment',
1.134     albertel 4223: 		   ['firstname','middlename','lastname','generation'],
                   4224: 		   $udom,$uname);
1.313     matthew  4225:     my %names;
                   4226:     if ($tmp[0] =~ m/^error:.*/) { 
                   4227:         %names=(); 
                   4228:     } else {
                   4229:         %names = @tmp;
                   4230:     }
1.388     www      4231: #
                   4232: # Make sure to not trash student environment if instructor does not bother
                   4233: # to supply name and email information
                   4234: #
                   4235:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4236:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4237:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4238:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4239:     if ($email) {
                   4240:        $email=~s/[^\w\@\.\-\,]//gs;
                   4241:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4242: 			   $names{'critnotification'} = $email;
                   4243: 			   $names{'permanentemail'} = $email; }
                   4244:     }
1.134     albertel 4245:     my $reply = &put('environment', \%names, $udom,$uname);
                   4246:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4247:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4248:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4249:              $umode.', '.$first.', '.$middle.', '.
                   4250: 	     $last.', '.$gene.' by '.
1.620     albertel 4251:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4252:     return 'ok';
1.80      www      4253: }
                   4254: 
1.81      www      4255: # -------------------------------------------------------------- Modify student
1.80      www      4256: 
1.81      www      4257: sub modifystudent {
                   4258:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4259:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4260:     if (!$cid) {
1.620     albertel 4261: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4262: 	    return 'not_in_class';
                   4263: 	}
1.80      www      4264:     }
                   4265: # --------------------------------------------------------------- Make the user
1.81      www      4266:     my $reply=&modifyuser
1.209     matthew  4267: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4268:          $desiredhome,$email);
1.80      www      4269:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4270:     # This will cause &modify_student_enrollment to get the uid from the
                   4271:     # students environment
                   4272:     $uid = undef if (!$forceid);
1.455     albertel 4273:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4274: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4275:     return $reply;
                   4276: }
                   4277: 
                   4278: sub modify_student_enrollment {
1.515     raeburn  4279:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4280:     my ($cdom,$cnum,$chome);
                   4281:     if (!$cid) {
1.620     albertel 4282: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4283: 	    return 'not_in_class';
                   4284: 	}
1.620     albertel 4285: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4286: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4287:     } else {
                   4288: 	($cdom,$cnum)=split(/_/,$cid);
                   4289:     }
1.620     albertel 4290:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4291:     if (!$chome) {
1.457     raeburn  4292: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4293:     }
1.455     albertel 4294:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4295:     # Make sure the user exists
1.81      www      4296:     my $uhome=&homeserver($uname,$udom);
                   4297:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4298: 	return 'error: no such user';
                   4299:     }
1.297     matthew  4300:     # Get student data if we were not given enough information
                   4301:     if (!defined($first)  || $first  eq '' || 
                   4302:         !defined($last)   || $last   eq '' || 
                   4303:         !defined($uid)    || $uid    eq '' || 
                   4304:         !defined($middle) || $middle eq '' || 
                   4305:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4306:         # They did not supply us with enough data to enroll the student, so
                   4307:         # we need to pick up more information.
1.297     matthew  4308:         my %tmp = &get('environment',
1.294     matthew  4309:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4310:                        ,$udom,$uname);
                   4311: 
1.455     albertel 4312:         #foreach (keys(%tmp)) {
                   4313:         #    &logthis("key $_ = ".$tmp{$_});
                   4314:         #}
1.294     matthew  4315:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4316:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4317:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4318:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4319:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4320:     }
1.556     albertel 4321:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4322:     my $reply=cput('classlist',
                   4323: 		   {"$uname:$udom" => 
1.515     raeburn  4324: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4325: 		   $cdom,$cnum);
1.81      www      4326:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4327: 	return 'error: '.$reply;
1.652     albertel 4328:     } else {
                   4329: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4330:     }
1.297     matthew  4331:     # Add student role to user
1.83      www      4332:     my $uurl='/'.$cid;
1.81      www      4333:     $uurl=~s/\_/\//g;
                   4334:     if ($usec) {
                   4335: 	$uurl.='/'.$usec;
                   4336:     }
                   4337:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4338: }
                   4339: 
1.556     albertel 4340: sub format_name {
                   4341:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4342:     my $name;
                   4343:     if ($first ne 'lastname') {
                   4344: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4345:     } else {
                   4346: 	if ($lastname=~/\S/) {
                   4347: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4348: 	    $name=~s/\s+,/,/;
                   4349: 	} else {
                   4350: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4351: 	}
                   4352:     }
                   4353:     $name=~s/^\s+//;
                   4354:     $name=~s/\s+$//;
                   4355:     $name=~s/\s+/ /g;
                   4356:     return $name;
                   4357: }
                   4358: 
1.84      www      4359: # ------------------------------------------------- Write to course preferences
                   4360: 
                   4361: sub writecoursepref {
                   4362:     my ($courseid,%prefs)=@_;
                   4363:     $courseid=~s/^\///;
                   4364:     $courseid=~s/\_/\//g;
                   4365:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4366:     my $chome=homeserver($cnum,$cdomain);
                   4367:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4368: 	return 'error: no such course';
                   4369:     }
                   4370:     my $cstring='';
1.191     harris41 4371:     foreach (keys %prefs) {
1.84      www      4372: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4373:     }
1.84      www      4374:     $cstring=~s/\&$//;
                   4375:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4376: }
                   4377: 
                   4378: # ---------------------------------------------------------- Make/modify course
                   4379: 
                   4380: sub createcourse {
1.571     raeburn  4381:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      4382:     $url=&declutter($url);
                   4383:     my $cid='';
1.264     matthew  4384:     unless (&allowed('ccc',$udom)) {
1.84      www      4385:         return 'refused';
                   4386:     }
                   4387: # ------------------------------------------------------------------- Create ID
1.674     www      4388:    my $uname=int(1+rand(9)).
                   4389:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4390:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4391:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4392: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4393:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4394:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4395:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4396:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4397:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4398:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4399:            return 'error: unable to generate unique course-ID';
                   4400:        } 
                   4401:    }
1.264     matthew  4402: # ------------------------------------------------ Check supplied server name
1.620     albertel 4403:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4404:     if (! exists($libserv{$course_server})) {
                   4405:         return 'error:bad server name '.$course_server;
                   4406:     }
1.84      www      4407: # ------------------------------------------------------------- Make the course
                   4408:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4409:                       $course_server);
1.84      www      4410:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4411:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4412:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4413: 	return 'error: no such course';
                   4414:     }
1.271     www      4415: # ----------------------------------------------------------------- Course made
1.516     raeburn  4416: # log existence
                   4417:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  4418:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      4419:     &flushcourselogs();
                   4420: # set toplevel url
1.271     www      4421:     my $topurl=$url;
                   4422:     unless ($nonstandard) {
                   4423: # ------------------------------------------ For standard courses, make top url
                   4424:         my $mapurl=&clutter($url);
1.278     www      4425:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4426:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4427: <map>
                   4428: <resource id="1" type="start"></resource>
                   4429: <resource id="2" src="$mapurl"></resource>
                   4430: <resource id="3" type="finish"></resource>
                   4431: <link index="1" from="1" to="2"></link>
                   4432: <link index="2" from="2" to="3"></link>
                   4433: </map>
                   4434: ENDINITMAP
                   4435:         $topurl=&declutter(
1.638     albertel 4436:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4437:                           );
                   4438:     }
                   4439: # ----------------------------------------------------------- Write preferences
1.84      www      4440:     &writecoursepref($udom.'_'.$uname,
                   4441:                      ('description' => $description,
1.271     www      4442:                       'url'         => $topurl));
1.84      www      4443:     return '/'.$udom.'/'.$uname;
                   4444: }
                   4445: 
1.21      www      4446: # ---------------------------------------------------------- Assign Custom Role
                   4447: 
                   4448: sub assigncustomrole {
1.357     www      4449:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4450:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4451:                        $end,$start,$deleteflag);
1.21      www      4452: }
                   4453: 
                   4454: # ----------------------------------------------------------------- Revoke Role
                   4455: 
                   4456: sub revokerole {
1.357     www      4457:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4458:     my $now=time;
1.357     www      4459:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4460: }
                   4461: 
                   4462: # ---------------------------------------------------------- Revoke Custom Role
                   4463: 
                   4464: sub revokecustomrole {
1.357     www      4465:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4466:     my $now=time;
1.357     www      4467:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4468:            $deleteflag);
1.17      www      4469: }
                   4470: 
1.533     banghart 4471: # ------------------------------------------------------------ Disk usage
1.535     albertel 4472: sub diskusage {
1.533     banghart 4473:     my ($udom,$uname,$directoryRoot)=@_;
                   4474:     $directoryRoot =~ s/\/$//;
1.535     albertel 4475:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4476:     return $listing;
1.512     banghart 4477: }
                   4478: 
1.566     banghart 4479: sub is_locked {
                   4480:     my ($file_name, $domain, $user) = @_;
                   4481:     my @check;
                   4482:     my $is_locked;
                   4483:     push @check, $file_name;
1.613     albertel 4484:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4485: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4486:     my ($tmp)=keys(%locked);
                   4487:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 4488: 
1.566     banghart 4489:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   4490:         $is_locked = 'true';
                   4491:     } else {
                   4492:         $is_locked = 'false';
                   4493:     }
                   4494: }
                   4495: 
1.559     banghart 4496: # ------------------------------------------------------------- Mark as Read Only
                   4497: 
                   4498: sub mark_as_readonly {
                   4499:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4500:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4501:     my ($tmp)=keys(%current_permissions);
                   4502:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4503:     foreach my $file (@{$files}) {
1.561     banghart 4504:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4505:     }
1.613     albertel 4506:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4507:     return;
                   4508: }
                   4509: 
1.572     banghart 4510: # ------------------------------------------------------------Save Selected Files
                   4511: 
                   4512: sub save_selected_files {
                   4513:     my ($user, $path, @files) = @_;
                   4514:     my $filename = $user."savedfiles";
1.573     banghart 4515:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4516:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4517:     foreach my $file (@files) {
1.620     albertel 4518:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4519:     }
                   4520:     foreach my $file (@other_files) {
1.574     banghart 4521:         print (OUT $file."\n");
1.572     banghart 4522:     }
1.574     banghart 4523:     close (OUT);
1.572     banghart 4524:     return 'ok';
                   4525: }
                   4526: 
1.574     banghart 4527: sub clear_selected_files {
                   4528:     my ($user) = @_;
                   4529:     my $filename = $user."savedfiles";
                   4530:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4531:     print (OUT undef);
                   4532:     close (OUT);
                   4533:     return ("ok");    
                   4534: }
                   4535: 
1.572     banghart 4536: sub files_in_path {
                   4537:     my ($user, $path) = @_;
                   4538:     my $filename = $user."savedfiles";
                   4539:     my %return_files;
1.574     banghart 4540:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4541:     while (my $line_in = <IN>) {
1.574     banghart 4542:         chomp ($line_in);
                   4543:         my @paths_and_file = split (m!/!, $line_in);
                   4544:         my $file_part = pop (@paths_and_file);
                   4545:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4546:         $path_part.='/';
                   4547:         my $path_and_file = $path_part.$file_part;
                   4548:         if ($path_part eq $path) {
                   4549:             $return_files{$file_part}= 'selected';
                   4550:         }
                   4551:     }
1.574     banghart 4552:     close (IN);
                   4553:     return (\%return_files);
1.572     banghart 4554: }
                   4555: 
                   4556: # called in portfolio select mode, to show files selected NOT in current directory
                   4557: sub files_not_in_path {
                   4558:     my ($user, $path) = @_;
                   4559:     my $filename = $user."savedfiles";
                   4560:     my @return_files;
                   4561:     my $path_part;
1.574     banghart 4562:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4563:     while (<IN>) {
                   4564:         #ok, I know it's clunky, but I want it to work
                   4565:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4566:         my $file_part = pop (@paths_and_file);
                   4567:         chomp ($file_part);
                   4568:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4569:         $path_part .= '/';
                   4570:         my $path_and_file = $path_part.$file_part;
                   4571:         if ($path_part ne $path) {
1.574     banghart 4572:             push (@return_files, ($path_and_file));
1.572     banghart 4573:         }
                   4574:     }
1.574     banghart 4575:     close (OUT);
                   4576:     return (@return_files);
1.572     banghart 4577: }
                   4578: 
1.561     banghart 4579: #--------------------------------------------------------------Get Marked as Read Only
                   4580: 
1.629     banghart 4581: 
1.561     banghart 4582: sub get_marked_as_readonly {
                   4583:     my ($domain,$user,$what) = @_;
1.613     albertel 4584:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4585:     my ($tmp)=keys(%current_permissions);
                   4586:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563     banghart 4587:     my @readonly_files;
1.629     banghart 4588:     my $cmp1=$what;
                   4589:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.563     banghart 4590:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 4591:         if (ref($value) eq "ARRAY"){
                   4592:             foreach my $stored_what (@{$value}) {
1.629     banghart 4593:                 my $cmp2=$stored_what;
                   4594:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
                   4595:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4596:                     push(@readonly_files, $file_name);
1.563     banghart 4597:                 } elsif (!defined($what)) {
                   4598:                     push(@readonly_files, $file_name);
1.561     banghart 4599:                 }
                   4600:             }
                   4601:         } 
                   4602:     }
                   4603:     return @readonly_files;
                   4604: }
1.577     banghart 4605: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4606: 
1.577     banghart 4607: sub get_marked_as_readonly_hash {
                   4608:     my ($domain,$user,$what) = @_;
1.613     albertel 4609:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4610:     my ($tmp)=keys(%current_permissions);
                   4611:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4612: 
1.577     banghart 4613:     my %readonly_files;
                   4614:     while (my ($file_name,$value) = each(%current_permissions)) {
                   4615:         if (ref($value) eq "ARRAY"){
                   4616:             foreach my $stored_what (@{$value}) {
                   4617:                 if ($stored_what eq $what) {
                   4618:                     $readonly_files{$file_name} = 'locked';
                   4619:                 } elsif (!defined($what)) {
                   4620:                     $readonly_files{$file_name} = 'locked';
                   4621:                 }
                   4622:             }
                   4623:         } 
                   4624:     }
                   4625:     return %readonly_files;
                   4626: }
1.559     banghart 4627: # ------------------------------------------------------------ Unmark as Read Only
                   4628: 
                   4629: sub unmark_as_readonly {
1.629     banghart 4630:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4631:     # for portfolio submissions, $what contains [$symb,$crsid] 
                   4632:     my ($domain,$user,$what,$file_name) = @_;
1.634     albertel 4633:     my $symb_crs = $what;
                   4634:     if (ref($what)) { $symb_crs=join('',@$what); }
1.613     albertel 4635:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4636:     my ($tmp)=keys(%current_permissions);
                   4637:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4638:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.650     albertel 4639:     foreach my $file (@readonly_files) {
                   4640: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4641: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4642:         my @new_locks;
                   4643:         my @del_keys;
                   4644:         if (ref($current_locks) eq "ARRAY"){
                   4645:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4646:                 my $compare=$locker;
                   4647:                 if (ref($locker)) { $compare=join('',@{$locker}) };
1.650     albertel 4648:                 if ($compare ne $symb_crs) {
                   4649:                     push(@new_locks, $locker);
1.563     banghart 4650:                 }
                   4651:             }
1.650     albertel 4652:             if (scalar(@new_locks) > 0) {
1.563     banghart 4653:                 $current_permissions{$file} = \@new_locks;
                   4654:             } else {
                   4655:                 push(@del_keys, $file);
1.613     albertel 4656:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4657:                 delete($current_permissions{$file});
1.563     banghart 4658:             }
                   4659:         }
1.561     banghart 4660:     }
1.613     albertel 4661:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4662:     return;
                   4663: }
1.512     banghart 4664: 
1.17      www      4665: # ------------------------------------------------------------ Directory lister
                   4666: 
                   4667: sub dirlist {
1.253     stredwic 4668:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4669: 
1.18      www      4670:     $uri=~s/^\///;
                   4671:     $uri=~s/\/$//;
1.253     stredwic 4672:     my ($udom, $uname);
                   4673:     (undef,$udom,$uname)=split(/\//,$uri);
                   4674:     if(defined($userdomain)) {
                   4675:         $udom = $userdomain;
                   4676:     }
                   4677:     if(defined($username)) {
                   4678:         $uname = $username;
                   4679:     }
                   4680: 
                   4681:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4682:     if(defined($alternateDirectoryRoot)) {
                   4683:         $dirRoot = $alternateDirectoryRoot;
                   4684:         $dirRoot =~ s/\/$//;
                   4685:     }
                   4686: 
                   4687:     if($udom) {
                   4688:         if($uname) {
1.605     matthew  4689:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4690:                               homeserver($uname,$udom));
1.605     matthew  4691:             my @listing_results;
                   4692:             if ($listing eq 'unknown_cmd') {
                   4693:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4694:                                homeserver($uname,$udom));
                   4695:                 @listing_results = split(/:/,$listing);
                   4696:             } else {
                   4697:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4698:             }
                   4699:             return @listing_results;
1.253     stredwic 4700:         } elsif(!defined($alternateDirectoryRoot)) {
                   4701:             my $tryserver;
                   4702:             my %allusers=();
                   4703:             foreach $tryserver (keys %libserv) {
                   4704:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4705:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4706:                                       $udom, $tryserver);
1.605     matthew  4707:                     my @listing_results;
                   4708:                     if ($listing eq 'unknown_cmd') {
                   4709:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4710:                                        $udom, $tryserver);
                   4711:                         @listing_results = split(/:/,$listing);
                   4712:                     } else {
                   4713:                         @listing_results =
                   4714:                             map { &unescape($_); } split(/:/,$listing);
                   4715:                     }
                   4716:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4717:                         $listing_results[0] ne 'empty'       &&
                   4718:                         $listing_results[0] ne 'con_lost') {
                   4719:                         foreach (@listing_results) {
1.253     stredwic 4720:                             my ($entry,@stat)=split(/&/,$_);
                   4721:                             $allusers{$entry}=1;
                   4722:                         }
                   4723:                     }
1.191     harris41 4724:                 }
1.253     stredwic 4725:             }
                   4726:             my $alluserstr='';
                   4727:             foreach (sort keys %allusers) {
                   4728:                 $alluserstr.=$_.'&user:';
                   4729:             }
                   4730:             $alluserstr=~s/:$//;
                   4731:             return split(/:/,$alluserstr);
                   4732:         } else {
                   4733:             my @emptyResults = ();
                   4734:             push(@emptyResults, 'missing user name');
                   4735:             return split(':',@emptyResults);
                   4736:         }
                   4737:     } elsif(!defined($alternateDirectoryRoot)) {
                   4738:         my $tryserver;
                   4739:         my %alldom=();
                   4740:         foreach $tryserver (keys %libserv) {
                   4741:             $alldom{$hostdom{$tryserver}}=1;
                   4742:         }
                   4743:         my $alldomstr='';
                   4744:         foreach (sort keys %alldom) {
1.397     albertel 4745:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4746:         }
                   4747:         $alldomstr=~s/:$//;
                   4748:         return split(/:/,$alldomstr);       
                   4749:     } else {
                   4750:         my @emptyResults = ();
                   4751:         push(@emptyResults, 'missing domain');
                   4752:         return split(':',@emptyResults);
1.275     stredwic 4753:     }
                   4754: }
                   4755: 
                   4756: # --------------------------------------------- GetFileTimestamp
                   4757: # This function utilizes dirlist and returns the date stamp for
                   4758: # when it was last modified.  It will also return an error of -1
                   4759: # if an error occurs
                   4760: 
1.410     matthew  4761: ##
                   4762: ## FIXME: This subroutine assumes its caller knows something about the
                   4763: ## directory structure of the home server for the student ($root).
                   4764: ## Not a good assumption to make.  Since this is for looking up files
                   4765: ## in user directories, the full path should be constructed by lond, not
                   4766: ## whatever machine we request data from.
                   4767: ##
1.275     stredwic 4768: sub GetFileTimestamp {
                   4769:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4770:     $studentDomain=~s/\W//g;
                   4771:     $studentName=~s/\W//g;
                   4772:     my $subdir=$studentName.'__';
                   4773:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4774:     my $proname="$studentDomain/$subdir/$studentName";
                   4775:     $proname .= '/'.$filename;
1.375     matthew  4776:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4777:                                               $studentName, $root);
1.275     stredwic 4778:     my @stats = split('&', $fileStat);
                   4779:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4780:         # @stats contains first the filename, then the stat output
                   4781:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4782:     } else {
                   4783:         return -1;
1.253     stredwic 4784:     }
1.26      www      4785: }
                   4786: 
1.712     albertel 4787: sub stat_file {
                   4788:     my ($uri) = @_;
1.722     albertel 4789:     $uri = &clutter($uri);
                   4790: 
                   4791:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 4792:     if ($uri =~ m-^/adm/-) {
                   4793: 	$uri=~s-^/adm/wrapper/-/-;
                   4794: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 4795:     }
1.712     albertel 4796:     my ($udom,$uname,$file,$dir);
                   4797:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   4798: 	($udom,$uname,$file) =
                   4799: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   4800: 	$file = 'userfiles/'.$file;
                   4801: 	$dir = &Apache::loncommon::propath($udom,$uname);
                   4802:     }
                   4803:     if ($uri =~ m-^/res/-) {
                   4804: 	($udom,$uname) = 
                   4805: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   4806: 	$file = $uri;
                   4807:     }
                   4808: 
                   4809:     if (!$udom || !$uname || !$file) {
                   4810: 	# unable to handle the uri
                   4811: 	return ();
                   4812:     }
                   4813: 
                   4814:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   4815:     my @stats = split('&', $result);
1.721     banghart 4816:     
1.712     albertel 4817:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   4818: 	shift(@stats); #filename is first
                   4819: 	return @stats;
                   4820:     }
                   4821:     return ();
                   4822: }
                   4823: 
1.26      www      4824: # -------------------------------------------------------- Value of a Condition
                   4825: 
1.713     albertel 4826: # gets the value of a specific preevaluated condition
                   4827: #    stored in the string  $env{user.state.<cid>}
                   4828: # or looks up a condition reference in the bighash and if if hasn't
                   4829: # already been evaluated recurses into docondval to get the value of
                   4830: # the condition, then memoizing it to 
                   4831: #   $env{user.state.<cid>.<condition>}
1.40      www      4832: sub directcondval {
                   4833:     my $number=shift;
1.620     albertel 4834:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4835: 	&Apache::lonuserstate::evalstate();
                   4836:     }
1.713     albertel 4837:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   4838: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   4839:     } elsif ($number =~ /^_/) {
                   4840: 	my $sub_condition;
                   4841: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   4842: 		&GDBM_READER(),0640)) {
                   4843: 	    $sub_condition=$bighash{'conditions'.$number};
                   4844: 	    untie(%bighash);
                   4845: 	}
                   4846: 	my $value = &docondval($sub_condition);
                   4847: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   4848: 	return $value;
                   4849:     }
1.620     albertel 4850:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4851:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4852:     } else {
                   4853:        return 2;
                   4854:     }
                   4855: }
                   4856: 
1.713     albertel 4857: # get the collection of conditions for this resource
1.26      www      4858: sub condval {
                   4859:     my $condidx=shift;
1.54      www      4860:     my $allpathcond='';
1.713     albertel 4861:     foreach my $cond (split(/\|/,$condidx)) {
                   4862: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   4863: 	    $allpathcond.=
                   4864: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   4865: 	}
1.191     harris41 4866:     }
1.54      www      4867:     $allpathcond=~s/\|$//;
1.713     albertel 4868:     return &docondval($allpathcond);
                   4869: }
                   4870: 
                   4871: #evaluates an expression of conditions
                   4872: sub docondval {
                   4873:     my ($allpathcond) = @_;
                   4874:     my $result=0;
                   4875:     if ($env{'request.course.id'}
                   4876: 	&& defined($allpathcond)) {
                   4877: 	my $operand='|';
                   4878: 	my @stack;
                   4879: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   4880: 	    if ($chunk eq '(') {
                   4881: 		push @stack,($operand,$result);
                   4882: 	    } elsif ($chunk eq ')') {
                   4883: 		my $before=pop @stack;
                   4884: 		if (pop @stack eq '&') {
                   4885: 		    $result=$result>$before?$before:$result;
                   4886: 		} else {
                   4887: 		    $result=$result>$before?$result:$before;
                   4888: 		}
                   4889: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   4890: 		$operand=$chunk;
                   4891: 	    } else {
                   4892: 		my $new=directcondval($chunk);
                   4893: 		if ($operand eq '&') {
                   4894: 		    $result=$result>$new?$new:$result;
                   4895: 		} else {
                   4896: 		    $result=$result>$new?$result:$new;
                   4897: 		}
                   4898: 	    }
                   4899: 	}
1.26      www      4900:     }
                   4901:     return $result;
1.421     albertel 4902: }
                   4903: 
                   4904: # ---------------------------------------------------- Devalidate courseresdata
                   4905: 
                   4906: sub devalidatecourseresdata {
                   4907:     my ($coursenum,$coursedomain)=@_;
                   4908:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4909:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4910: }
                   4911: 
1.200     www      4912: # --------------------------------------------------- Course Resourcedata Query
                   4913: 
1.624     albertel 4914: sub get_courseresdata {
                   4915:     my ($coursenum,$coursedomain)=@_;
1.200     www      4916:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4917:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4918:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4919:     my %dumpreply;
1.417     albertel 4920:     unless (defined($cached)) {
1.624     albertel 4921: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4922: 	$result=\%dumpreply;
1.251     albertel 4923: 	my ($tmp) = keys(%dumpreply);
                   4924: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4925: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4926: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4927: 	    return $tmp;
1.416     albertel 4928: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4929: 	    $result=undef;
1.599     albertel 4930: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4931: 	}
                   4932:     }
1.624     albertel 4933:     return $result;
                   4934: }
                   4935: 
1.633     albertel 4936: sub devalidateuserresdata {
                   4937:     my ($uname,$udom)=@_;
                   4938:     my $hashid="$udom:$uname";
                   4939:     &devalidate_cache_new('userres',$hashid);
                   4940: }
                   4941: 
1.624     albertel 4942: sub get_userresdata {
                   4943:     my ($uname,$udom)=@_;
                   4944:     #most student don\'t have any data set, check if there is some data
                   4945:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4946: 
                   4947:     my $hashid="$udom:$uname";
                   4948:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4949:     if (!defined($cached)) {
                   4950: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4951: 	$result=\%resourcedata;
                   4952: 	&do_cache_new('userres',$hashid,$result,600);
                   4953:     }
                   4954:     my ($tmp)=keys(%$result);
                   4955:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4956: 	return $result;
                   4957:     }
                   4958:     #error 2 occurs when the .db doesn't exist
                   4959:     if ($tmp!~/error: 2 /) {
1.672     albertel 4960: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 4961: 		 " Trying to get resource data for ".
                   4962: 		 $uname." at ".$udom.": ".
                   4963: 		 $tmp."</font>");
                   4964:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 4965: 	#&EXT_cache_set($udom,$uname);
                   4966: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 4967: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 4968:     }
                   4969:     return $tmp;
                   4970: }
                   4971: 
                   4972: sub resdata {
                   4973:     my ($name,$domain,$type,@which)=@_;
                   4974:     my $result;
                   4975:     if ($type eq 'course') {
                   4976: 	$result=&get_courseresdata($name,$domain);
                   4977:     } elsif ($type eq 'user') {
                   4978: 	$result=&get_userresdata($name,$domain);
                   4979:     }
                   4980:     if (!ref($result)) { return $result; }    
1.251     albertel 4981:     foreach my $item (@which) {
1.417     albertel 4982: 	if (defined($result->{$item})) {
                   4983: 	    return $result->{$item};
1.251     albertel 4984: 	}
1.250     albertel 4985:     }
1.291     albertel 4986:     return undef;
1.200     www      4987: }
                   4988: 
1.379     matthew  4989: #
                   4990: # EXT resource caching routines
                   4991: #
                   4992: 
                   4993: sub clear_EXT_cache_status {
1.383     albertel 4994:     &delenv('cache.EXT.');
1.379     matthew  4995: }
                   4996: 
                   4997: sub EXT_cache_status {
                   4998:     my ($target_domain,$target_user) = @_;
1.383     albertel 4999:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5000:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5001:         # We know already the user has no data
                   5002:         return 1;
                   5003:     } else {
                   5004:         return 0;
                   5005:     }
                   5006: }
                   5007: 
                   5008: sub EXT_cache_set {
                   5009:     my ($target_domain,$target_user) = @_;
1.383     albertel 5010:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5011:     #&appenv($cachename => time);
1.379     matthew  5012: }
                   5013: 
1.28      www      5014: # --------------------------------------------------------- Value of a Variable
1.58      www      5015: sub EXT {
1.715     albertel 5016: 
1.395     albertel 5017:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5018:     unless ($varname) { return ''; }
1.218     albertel 5019:     #get real user name/domain, courseid and symb
                   5020:     my $courseid;
1.359     albertel 5021:     my $publicuser;
1.427     www      5022:     if ($symbparm) {
                   5023: 	$symbparm=&get_symb_from_alias($symbparm);
                   5024:     }
1.218     albertel 5025:     if (!($uname && $udom)) {
1.360     albertel 5026:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5027: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5028:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5029:     } else {
1.620     albertel 5030: 	$courseid=$env{'request.course.id'};
1.218     albertel 5031:     }
1.48      www      5032:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5033:     my $rest;
1.320     albertel 5034:     if (defined($therest[0])) {
1.48      www      5035:        $rest=join('.',@therest);
                   5036:     } else {
                   5037:        $rest='';
                   5038:     }
1.320     albertel 5039: 
1.57      www      5040:     my $qualifierrest=$qualifier;
                   5041:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5042:     my $spacequalifierrest=$space;
                   5043:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5044:     if ($realm eq 'user') {
1.48      www      5045: # --------------------------------------------------------------- user.resource
                   5046: 	if ($space eq 'resource') {
1.651     albertel 5047: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5048: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5049: 		 &&
                   5050: 		 ($symbparm eq &symbread()) ) {
1.335     albertel 5051: 		return $Apache::lonhomework::history{$qualifierrest};
                   5052: 	    } else {
1.359     albertel 5053: 		my %restored;
1.620     albertel 5054: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5055: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5056: 		} else {
                   5057: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5058: 		}
1.335     albertel 5059: 		return $restored{$qualifierrest};
                   5060: 	    }
1.48      www      5061: # ----------------------------------------------------------------- user.access
                   5062:         } elsif ($space eq 'access') {
1.218     albertel 5063: 	    # FIXME - not supporting calls for a specific user
1.48      www      5064:             return &allowed($qualifier,$rest);
                   5065: # ------------------------------------------ user.preferences, user.environment
                   5066:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5067: 	    if (($uname eq $env{'user.name'}) &&
                   5068: 		($udom eq $env{'user.domain'})) {
                   5069: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5070: 	    } else {
1.359     albertel 5071: 		my %returnhash;
                   5072: 		if (!$publicuser) {
                   5073: 		    %returnhash=&userenvironment($udom,$uname,
                   5074: 						 $qualifierrest);
                   5075: 		}
1.218     albertel 5076: 		return $returnhash{$qualifierrest};
                   5077: 	    }
1.48      www      5078: # ----------------------------------------------------------------- user.course
                   5079:         } elsif ($space eq 'course') {
1.218     albertel 5080: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5081:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5082: # ------------------------------------------------------------------- user.role
                   5083:         } elsif ($space eq 'role') {
1.218     albertel 5084: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5085:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5086:             if ($qualifier eq 'value') {
                   5087: 		return $role;
                   5088:             } elsif ($qualifier eq 'extent') {
                   5089:                 return $where;
                   5090:             }
                   5091: # ----------------------------------------------------------------- user.domain
                   5092:         } elsif ($space eq 'domain') {
1.218     albertel 5093:             return $udom;
1.48      www      5094: # ------------------------------------------------------------------- user.name
                   5095:         } elsif ($space eq 'name') {
1.218     albertel 5096:             return $uname;
1.48      www      5097: # ---------------------------------------------------- Any other user namespace
1.29      www      5098:         } else {
1.359     albertel 5099: 	    my %reply;
                   5100: 	    if (!$publicuser) {
                   5101: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5102: 	    }
                   5103: 	    return $reply{$qualifierrest};
1.48      www      5104:         }
1.236     www      5105:     } elsif ($realm eq 'query') {
                   5106: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5107:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5108: 						[$spacequalifierrest]);
1.620     albertel 5109: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5110:    } elsif ($realm eq 'request') {
1.48      www      5111: # ------------------------------------------------------------- request.browser
                   5112:         if ($space eq 'browser') {
1.430     www      5113: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5114: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5115: 		    return 1;
                   5116: 		} else {
                   5117: 		    return 0;
                   5118: 		}
                   5119: 	    } else {
1.620     albertel 5120: 		return $env{'browser.'.$qualifier};
1.430     www      5121: 	    }
1.57      www      5122: # ------------------------------------------------------------ request.filename
                   5123:         } else {
1.620     albertel 5124:             return $env{'request.'.$spacequalifierrest};
1.29      www      5125:         }
1.28      www      5126:     } elsif ($realm eq 'course') {
1.48      www      5127: # ---------------------------------------------------------- course.description
1.620     albertel 5128:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5129:     } elsif ($realm eq 'resource') {
1.165     www      5130: 
1.620     albertel 5131: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5132: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5133: 	}
1.693     albertel 5134: 
                   5135: 	if ($space eq 'title') {
                   5136: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5137: 	    return &gettitle($symbparm);
                   5138: 	}
                   5139: 	
                   5140: 	if ($space eq 'map') {
                   5141: 	    my ($map) = &decode_symb($symbparm);
                   5142: 	    return &symbread($map);
                   5143: 	}
                   5144: 
                   5145: 	my ($section, $group, @groups);
1.593     albertel 5146: 	my ($courselevelm,$courselevel);
1.539     albertel 5147: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5148: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5149: 
1.218     albertel 5150: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5151: 
1.60      www      5152: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5153: 	    my $symbp=$symbparm;
1.409     www      5154: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 5155: 
                   5156: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5157: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5158: 
1.620     albertel 5159: 	    if (($env{'user.name'} eq $uname) &&
                   5160: 		($env{'user.domain'} eq $udom)) {
                   5161: 		$section=$env{'request.course.sec'};
1.691     raeburn  5162:                 @groups=&sort_course_groups($env{'request.course.groups'},$courseid); 
1.218     albertel 5163: 	    } else {
1.539     albertel 5164: 		if (! defined($usection)) {
1.551     albertel 5165: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5166: 		} else {
                   5167: 		    $section = $usection;
                   5168: 		}
1.684     raeburn  5169:                 my $grouplist = &get_users_groups($udom,$uname,$courseid);
                   5170:                 if ($grouplist) {
1.691     raeburn  5171:                     @groups=&sort_course_groups($grouplist,$courseid);
1.684     raeburn  5172:                 }
1.218     albertel 5173: 	    }
                   5174: 
                   5175: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5176: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5177: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5178: 
1.593     albertel 5179: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5180: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5181: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5182: 
1.60      www      5183: # ----------------------------------------------------------- first, check user
1.624     albertel 5184: 
                   5185: 	    my $userreply=&resdata($uname,$udom,'user',
                   5186: 				       ($courselevelr,$courselevelm,
                   5187: 					$courselevel));
                   5188: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5189: 
1.594     albertel 5190: # ------------------------------------------------ second, check some of course
1.684     raeburn  5191:             my $coursereply;
1.691     raeburn  5192:             if (@groups > 0) {
                   5193:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5194:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5195:                 if (defined($coursereply)) { return $coursereply; }
                   5196:             }
1.96      www      5197: 
1.684     raeburn  5198: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5199: 				     $env{'course.'.$courseid.'.domain'},
                   5200: 				     'course',
                   5201: 				     ($seclevelr,$seclevelm,$seclevel,
                   5202: 				      $courselevelr));
1.287     albertel 5203: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5204: 
1.60      www      5205: # ------------------------------------------------------ third, check map parms
1.218     albertel 5206: 	    my %parmhash=();
                   5207: 	    my $thisparm='';
                   5208: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5209: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5210: 		    &GDBM_READER(),0640)) {
1.218     albertel 5211: 		$thisparm=$parmhash{$symbparm};
                   5212: 		untie(%parmhash);
                   5213: 	    }
                   5214: 	    if ($thisparm) { return $thisparm; }
                   5215: 	}
1.594     albertel 5216: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5217: 
1.218     albertel 5218: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5219: 	my $filename;
                   5220: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5221: 	if ($symbparm) {
1.409     www      5222: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5223: 	} else {
1.620     albertel 5224: 	    $filename=$env{'request.filename'};
1.282     albertel 5225: 	}
                   5226: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5227: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5228: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5229: 	if (defined($metadata)) { return $metadata; }
1.142     www      5230: 
1.594     albertel 5231: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5232: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5233: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5234: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5235: 				     $env{'course.'.$courseid.'.domain'},
                   5236: 				     'course',
                   5237: 				     ($courselevelm,$courselevel));
1.593     albertel 5238: 	    if (defined($coursereply)) { return $coursereply; }
                   5239: 	}
1.145     www      5240: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5241: 	unless ($space eq '0') {
1.336     albertel 5242: 	    my @parts=split(/_/,$space);
                   5243: 	    my $id=pop(@parts);
                   5244: 	    my $part=join('_',@parts);
                   5245: 	    if ($part eq '') { $part='0'; }
                   5246: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5247: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5248: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5249: 	}
1.395     albertel 5250: 	if ($recurse) { return undef; }
                   5251: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5252: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5253: 
1.48      www      5254: # ---------------------------------------------------- Any other user namespace
                   5255:     } elsif ($realm eq 'environment') {
                   5256: # ----------------------------------------------------------------- environment
1.620     albertel 5257: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5258: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5259: 	} else {
                   5260: 	    my %returnhash=&userenvironment($udom,$uname,
                   5261: 					    $spacequalifierrest);
                   5262: 	    return $returnhash{$spacequalifierrest};
                   5263: 	}
1.28      www      5264:     } elsif ($realm eq 'system') {
1.48      www      5265: # ----------------------------------------------------------------- system.time
                   5266: 	if ($space eq 'time') {
                   5267: 	    return time;
                   5268:         }
1.696     albertel 5269:     } elsif ($realm eq 'server') {
                   5270: # ----------------------------------------------------------------- system.time
                   5271: 	if ($space eq 'name') {
                   5272: 	    return $ENV{'SERVER_NAME'};
                   5273:         }
1.28      www      5274:     }
1.48      www      5275:     return '';
1.61      www      5276: }
                   5277: 
1.691     raeburn  5278: sub check_group_parms {
                   5279:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5280:     my @groupitems = ();
                   5281:     my $resultitem;
                   5282:     my @levels = ($symbparm,$mapparm,$what);
                   5283:     foreach my $group (@{$groups}) {
                   5284:         foreach my $level (@levels) {
                   5285:              my $item = $courseid.'.['.$group.'].'.$level;
                   5286:              push(@groupitems,$item);
                   5287:         }
                   5288:     }
                   5289:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5290:                             $env{'course.'.$courseid.'.domain'},
                   5291:                                      'course',@groupitems);
                   5292:     return $coursereply;
                   5293: }
                   5294: 
                   5295: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
                   5296:     my ($grouplist,$courseid) = @_;
1.720     albertel 5297:     my @groups = sort(split(/:/,$grouplist));
1.691     raeburn  5298:     return @groups;
                   5299: }
                   5300: 
1.395     albertel 5301: sub packages_tab_default {
                   5302:     my ($uri,$varname)=@_;
                   5303:     my (undef,$part,$name)=split(/\./,$varname);
                   5304:     my $packages=&metadata($uri,'packages');
                   5305:     foreach my $package (split(/,/,$packages)) {
                   5306: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 5307: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5308: 	    return $packagetab{"$pack_type&$name&default"};
                   5309: 	}
1.585     albertel 5310: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5311: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5312: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5313: 	}
                   5314:     }
                   5315:     return undef;
                   5316: }
                   5317: 
1.334     albertel 5318: sub add_prefix_and_part {
                   5319:     my ($prefix,$part)=@_;
                   5320:     my $keyroot;
                   5321:     if (defined($prefix) && $prefix !~ /^__/) {
                   5322: 	# prefix that has a part already
                   5323: 	$keyroot=$prefix;
                   5324:     } elsif (defined($prefix)) {
                   5325: 	# prefix that is missing a part
                   5326: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5327:     } else {
                   5328: 	# no prefix at all
                   5329: 	if (defined($part)) { $keyroot='_'.$part; }
                   5330:     }
                   5331:     return $keyroot;
                   5332: }
                   5333: 
1.71      www      5334: # ---------------------------------------------------------------- Get metadata
                   5335: 
1.599     albertel 5336: my %metaentry;
1.71      www      5337: sub metadata {
1.176     www      5338:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5339:     $uri=&declutter($uri);
1.288     albertel 5340:     # if it is a non metadata possible uri return quickly
1.529     albertel 5341:     if (($uri eq '') || 
                   5342: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5343: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5344:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5345: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5346: 	return undef;
1.288     albertel 5347:     }
1.73      www      5348:     my $filename=$uri;
                   5349:     $uri=~s/\.meta$//;
1.172     www      5350: #
                   5351: # Is the metadata already cached?
1.177     www      5352: # Look at timestamp of caching
1.172     www      5353: # Everything is cached by the main uri, libraries are never directly cached
                   5354: #
1.428     albertel 5355:     if (!defined($liburi)) {
1.599     albertel 5356: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5357: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5358:     }
                   5359:     {
1.172     www      5360: #
                   5361: # Is this a recursive call for a library?
                   5362: #
1.599     albertel 5363: #	if (! exists($metacache{$uri})) {
                   5364: #	    $metacache{$uri}={};
                   5365: #	}
1.171     www      5366:         if ($liburi) {
                   5367: 	    $liburi=&declutter($liburi);
                   5368:             $filename=$liburi;
1.401     bowersj2 5369:         } else {
1.599     albertel 5370: 	    &devalidate_cache_new('meta',$uri);
                   5371: 	    undef(%metaentry);
1.401     bowersj2 5372: 	}
1.140     www      5373:         my %metathesekeys=();
1.73      www      5374:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5375: 	my $metastring;
1.609     banghart 5376: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 5377: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5378: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5379: 	    $metastring=&getfile($file);
1.489     albertel 5380: 	}
1.208     albertel 5381:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5382:         my $token;
1.140     www      5383:         undef %metathesekeys;
1.71      www      5384:         while ($token=$parser->get_token) {
1.339     albertel 5385: 	    if ($token->[0] eq 'S') {
                   5386: 		if (defined($token->[2]->{'package'})) {
1.172     www      5387: #
                   5388: # This is a package - get package info
                   5389: #
1.339     albertel 5390: 		    my $package=$token->[2]->{'package'};
                   5391: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5392: 		    if (defined($token->[2]->{'id'})) { 
                   5393: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5394: 		    }
1.599     albertel 5395: 		    if ($metaentry{':packages'}) {
                   5396: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5397: 		    } else {
1.599     albertel 5398: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5399: 		    }
1.613     albertel 5400: 		    foreach (sort keys %packagetab) {
1.432     albertel 5401: 			my $part=$keyroot;
                   5402: 			$part=~s/^\_//;
                   5403: 			if ($_=~/^\Q$package\E\&/ || 
                   5404: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 5405: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 5406: 			    # ignore package.tab specified default values
                   5407:                             # here &package_tab_default() will fetch those
                   5408: 			    if ($subp eq 'default') { next; }
1.339     albertel 5409: 			    my $value=$packagetab{$_};
1.432     albertel 5410: 			    my $unikey;
                   5411: 			    if ($pack =~ /_0$/) {
                   5412: 				$unikey='parameter_0_'.$name;
                   5413: 				$part=0;
                   5414: 			    } else {
                   5415: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5416: 			    }
1.339     albertel 5417: 			    if ($subp eq 'display') {
                   5418: 				$value.=' [Part: '.$part.']';
                   5419: 			    }
1.599     albertel 5420: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5421: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5422: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5423: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5424: 			    }
1.599     albertel 5425: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5426: 				$metaentry{':'.$unikey}=
                   5427: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5428: 			    }
1.339     albertel 5429: 			}
                   5430: 		    }
                   5431: 		} else {
1.172     www      5432: #
                   5433: # This is not a package - some other kind of start tag
1.339     albertel 5434: #
                   5435: 		    my $entry=$token->[1];
                   5436: 		    my $unikey;
                   5437: 		    if ($entry eq 'import') {
                   5438: 			$unikey='';
                   5439: 		    } else {
                   5440: 			$unikey=$entry;
                   5441: 		    }
                   5442: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5443: 
                   5444: 		    if (defined($token->[2]->{'id'})) { 
                   5445: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5446: 		    }
1.175     www      5447: 
1.339     albertel 5448: 		    if ($entry eq 'import') {
1.175     www      5449: #
                   5450: # Importing a library here
1.339     albertel 5451: #
                   5452: 			if ($depthcount<20) {
                   5453: 			    my $location=$parser->get_text('/import');
                   5454: 			    my $dir=$filename;
                   5455: 			    $dir=~s|[^/]*$||;
                   5456: 			    $location=&filelocation($dir,$location);
                   5457: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5458: 							       $location,$unikey,
                   5459: 							       $depthcount+1)))) {
1.599     albertel 5460: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 5461: 				$metathesekeys{$_}=1;
                   5462: 			    }
                   5463: 			}
                   5464: 		    } else { 
                   5465: 			
                   5466: 			if (defined($token->[2]->{'name'})) { 
                   5467: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5468: 			}
                   5469: 			$metathesekeys{$unikey}=1;
                   5470: 			foreach (@{$token->[3]}) {
1.599     albertel 5471: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 5472: 			}
                   5473: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5474: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5475: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5476: 		 # only ws inside the tag, and not in default, so use default
                   5477: 		 # as value
1.599     albertel 5478: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5479: 			} else {
1.321     albertel 5480: 		  # either something interesting inside the tag or default
                   5481:                   # uninteresting
1.599     albertel 5482: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5483: 			}
1.172     www      5484: # end of not-a-package not-a-library import
1.339     albertel 5485: 		    }
1.172     www      5486: # end of not-a-package start tag
1.339     albertel 5487: 		}
1.172     www      5488: # the next is the end of "start tag"
1.339     albertel 5489: 	    }
                   5490: 	}
1.483     albertel 5491: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   5492: 	foreach my $key (sort(keys(%packagetab))) {
                   5493: 	    #no specific packages #how's our extension
                   5494: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5495: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5496: 					 \%metathesekeys);
                   5497: 	}
1.599     albertel 5498: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 5499: 	    foreach my $key (sort(keys(%packagetab))) {
                   5500: 		#no specific packages well let's get default then
                   5501: 		if ($key!~/^default&/) { next; }
1.488     albertel 5502: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5503: 					     \%metathesekeys);
                   5504: 	    }
                   5505: 	}
1.338     www      5506: # are there custom rights to evaluate
1.599     albertel 5507: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5508: 
1.338     www      5509:     #
                   5510:     # Importing a rights file here
1.339     albertel 5511:     #
                   5512: 	    unless ($depthcount) {
1.599     albertel 5513: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5514: 		my $dir=$filename;
                   5515: 		$dir=~s|[^/]*$||;
                   5516: 		$location=&filelocation($dir,$location);
                   5517: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5518: 						   $location,'_rights',
                   5519: 						   $depthcount+1)))) {
1.599     albertel 5520: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 5521: 		    $metathesekeys{$_}=1;
                   5522: 		}
                   5523: 	    }
                   5524: 	}
1.599     albertel 5525: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   5526: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5527: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 5528: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      5529: # this is the end of "was not already recently cached
1.71      www      5530:     }
1.599     albertel 5531:     return $metaentry{':'.$what};
1.261     albertel 5532: }
                   5533: 
1.488     albertel 5534: sub metadata_create_package_def {
1.483     albertel 5535:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5536:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5537:     if ($subp eq 'default') { next; }
                   5538:     
1.599     albertel 5539:     if (defined($metaentry{':packages'})) {
                   5540: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5541:     } else {
1.599     albertel 5542: 	$metaentry{':packages'}=$package;
1.483     albertel 5543:     }
                   5544:     my $value=$packagetab{$key};
                   5545:     my $unikey;
                   5546:     $unikey='parameter_0_'.$name;
1.599     albertel 5547:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5548:     $$metathesekeys{$unikey}=1;
1.599     albertel 5549:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5550: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5551:     }
1.599     albertel 5552:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5553: 	$metaentry{':'.$unikey}=
                   5554: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5555:     }
                   5556: }
                   5557: 
1.261     albertel 5558: sub metadata_generate_part0 {
                   5559:     my ($metadata,$metacache,$uri) = @_;
                   5560:     my %allnames;
                   5561:     foreach my $metakey (sort keys %$metadata) {
                   5562: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5563: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5564: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5565: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5566: 	    $allnames{$name}=$part;
                   5567: 	  }
                   5568: 	}
                   5569:     }
                   5570:     foreach my $name (keys(%allnames)) {
                   5571:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5572:       my $key=":parameter_0_$name";
1.261     albertel 5573:       $$metacache{"$key.part"}='0';
                   5574:       $$metacache{"$key.name"}=$name;
1.428     albertel 5575:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5576: 					   $allnames{$name}.'_'.$name.
                   5577: 					   '.type'};
1.428     albertel 5578:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5579: 			     '.display'};
1.644     www      5580:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5581:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5582:       $$metacache{"$key.display"}=$olddis;
                   5583:     }
1.71      www      5584: }
                   5585: 
1.301     www      5586: # ------------------------------------------------- Get the title of a resource
                   5587: 
                   5588: sub gettitle {
                   5589:     my $urlsymb=shift;
                   5590:     my $symb=&symbread($urlsymb);
1.534     albertel 5591:     if ($symb) {
1.620     albertel 5592: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5593: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5594: 	if (defined($cached)) { 
                   5595: 	    return $result;
                   5596: 	}
1.534     albertel 5597: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5598: 	my $title='';
                   5599: 	my %bighash;
1.620     albertel 5600: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5601: 		&GDBM_READER(),0640)) {
                   5602: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5603: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5604: 	    untie %bighash;
                   5605: 	}
                   5606: 	$title=~s/\&colon\;/\:/gs;
                   5607: 	if ($title) {
1.599     albertel 5608: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5609: 	}
                   5610: 	$urlsymb=$url;
                   5611:     }
                   5612:     my $title=&metadata($urlsymb,'title');
                   5613:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5614:     return $title;
1.301     www      5615: }
1.613     albertel 5616: 
1.614     albertel 5617: sub get_slot {
                   5618:     my ($which,$cnum,$cdom)=@_;
                   5619:     if (!$cnum || !$cdom) {
                   5620: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5621: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5622: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5623:     }
1.703     albertel 5624:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   5625:     my %slotinfo;
                   5626:     if (exists($remembered{$key})) {
                   5627: 	$slotinfo{$which} = $remembered{$key};
                   5628:     } else {
                   5629: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5630: 	&Apache::lonhomework::showhash(%slotinfo);
                   5631: 	my ($tmp)=keys(%slotinfo);
                   5632: 	if ($tmp=~/^error:/) { return (); }
                   5633: 	$remembered{$key} = $slotinfo{$which};
                   5634:     }
1.616     albertel 5635:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5636: 	return %{$slotinfo{$which}};
                   5637:     }
                   5638:     return $slotinfo{$which};
1.614     albertel 5639: }
1.31      www      5640: # ------------------------------------------------- Update symbolic store links
                   5641: 
                   5642: sub symblist {
                   5643:     my ($mapname,%newhash)=@_;
1.438     www      5644:     $mapname=&deversion(&declutter($mapname));
1.31      www      5645:     my %hash;
1.620     albertel 5646:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5647:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5648:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 5649: 	    foreach my $url (keys %newhash) {
                   5650: 		next if ($url eq 'last_known'
                   5651: 			 && $env{'form.no_update_last_known'});
                   5652: 		$hash{declutter($url)}=&encode_symb($mapname,
                   5653: 						    $newhash{$url}->[1],
                   5654: 						    $newhash{$url}->[0]);
1.191     harris41 5655:             }
1.31      www      5656:             if (untie(%hash)) {
                   5657: 		return 'ok';
                   5658:             }
                   5659:         }
                   5660:     }
                   5661:     return 'error';
1.212     www      5662: }
                   5663: 
                   5664: # --------------------------------------------------------------- Verify a symb
                   5665: 
                   5666: sub symbverify {
1.510     www      5667:     my ($symb,$thisurl)=@_;
                   5668:     my $thisfn=$thisurl;
                   5669: # wrapper not part of symbs
                   5670:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 5671:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      5672:     $thisfn=&declutter($thisfn);
1.215     www      5673: # direct jump to resource in page or to a sequence - will construct own symbs
                   5674:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5675: # check URL part
1.409     www      5676:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5677: 
1.431     www      5678:     unless ($url eq $thisfn) { return 0; }
1.213     www      5679: 
1.216     www      5680:     $symb=&symbclean($symb);
1.510     www      5681:     $thisurl=&deversion($thisurl);
1.439     www      5682:     $thisfn=&deversion($thisfn);
1.213     www      5683: 
                   5684:     my %bighash;
                   5685:     my $okay=0;
1.431     www      5686: 
1.620     albertel 5687:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5688:                             &GDBM_READER(),0640)) {
1.510     www      5689:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5690:         unless ($ids) { 
1.510     www      5691:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5692:         }
                   5693:         if ($ids) {
                   5694: # ------------------------------------------------------------------- Has ID(s)
                   5695: 	    foreach (split(/\,/,$ids)) {
1.644     www      5696: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5697:                if (
                   5698:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5699:    eq $symb) { 
1.620     albertel 5700: 		   if (($env{'request.role.adv'}) ||
                   5701: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5702: 		       $okay=1; 
                   5703: 		   }
                   5704: 	       }
1.216     www      5705: 	   }
                   5706:         }
1.213     www      5707: 	untie(%bighash);
                   5708:     }
                   5709:     return $okay;
1.31      www      5710: }
                   5711: 
1.210     www      5712: # --------------------------------------------------------------- Clean-up symb
                   5713: 
                   5714: sub symbclean {
                   5715:     my $symb=shift;
1.568     albertel 5716:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5717: # remove version from map
                   5718:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      5719: 
1.210     www      5720: # remove version from URL
                   5721:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      5722: 
1.507     www      5723: # remove wrapper
                   5724: 
1.510     www      5725:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 5726:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      5727:     return $symb;
1.409     www      5728: }
                   5729: 
                   5730: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 5731: 
                   5732: sub encode_symb {
                   5733:     my ($map,$resid,$url)=@_;
                   5734:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   5735: }
1.409     www      5736: 
                   5737: sub decode_symb {
1.568     albertel 5738:     my $symb=shift;
                   5739:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   5740:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      5741:     return (&fixversion($map),$resid,&fixversion($url));
                   5742: }
                   5743: 
                   5744: sub fixversion {
                   5745:     my $fn=shift;
1.609     banghart 5746:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      5747:     my %bighash;
                   5748:     my $uri=&clutter($fn);
1.620     albertel 5749:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      5750: # is this cached?
1.599     albertel 5751:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      5752:     if (defined($cached)) { return $result; }
                   5753: # unfortunately not cached, or expired
1.620     albertel 5754:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      5755: 	    &GDBM_READER(),0640)) {
                   5756:  	if ($bighash{'version_'.$uri}) {
                   5757:  	    my $version=$bighash{'version_'.$uri};
1.444     www      5758:  	    unless (($version eq 'mostrecent') || 
                   5759: 		    ($version==&getversion($uri))) {
1.440     www      5760:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   5761:  	    }
                   5762:  	}
                   5763:  	untie %bighash;
1.413     www      5764:     }
1.599     albertel 5765:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      5766: }
                   5767: 
                   5768: sub deversion {
                   5769:     my $url=shift;
                   5770:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   5771:     return $url;
1.210     www      5772: }
                   5773: 
1.31      www      5774: # ------------------------------------------------------ Return symb list entry
                   5775: 
                   5776: sub symbread {
1.249     www      5777:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 5778:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 5779:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      5780: # no filename provided? try from environment
1.44      www      5781:     unless ($thisfn) {
1.620     albertel 5782:         if ($env{'request.symb'}) {
                   5783: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 5784: 	}
1.620     albertel 5785: 	$thisfn=$env{'request.filename'};
1.44      www      5786:     }
1.569     albertel 5787:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      5788: # is that filename actually a symb? Verify, clean, and return
                   5789:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 5790: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 5791: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 5792: 	}
1.242     www      5793:     }
1.44      www      5794:     $thisfn=declutter($thisfn);
1.31      www      5795:     my %hash;
1.37      www      5796:     my %bighash;
                   5797:     my $syval='';
1.620     albertel 5798:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  5799:         my $targetfn = $thisfn;
1.609     banghart 5800:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  5801:             $targetfn = 'adm/wrapper/'.$thisfn;
                   5802:         }
1.687     albertel 5803: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   5804: 	    $targetfn=$1;
                   5805: 	}
1.620     albertel 5806:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5807:                       &GDBM_READER(),0640)) {
1.481     raeburn  5808: 	    $syval=$hash{$targetfn};
1.37      www      5809:             untie(%hash);
                   5810:         }
                   5811: # ---------------------------------------------------------- There was an entry
                   5812:         if ($syval) {
1.601     albertel 5813: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 5814: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 5815: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 5816: 		    #return $env{$cache_str}='';
1.601     albertel 5817: 		#}    
                   5818: 		#$syval.=$1;
                   5819: 	    #}
1.37      www      5820:         } else {
                   5821: # ------------------------------------------------------- Was not in symb table
1.620     albertel 5822:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5823:                             &GDBM_READER(),0640)) {
1.37      www      5824: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      5825:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      5826:               unless ($ids) { 
                   5827:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      5828:               }
                   5829:               unless ($ids) {
                   5830: # alias?
                   5831: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      5832:               }
1.37      www      5833:               if ($ids) {
                   5834: # ------------------------------------------------------------------- Has ID(s)
                   5835:                  my @possibilities=split(/\,/,$ids);
1.39      www      5836:                  if ($#possibilities==0) {
                   5837: # ----------------------------------------------- There is only one possibility
1.37      www      5838: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 5839: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5840: 						    $resid,$thisfn);
1.249     www      5841:                  } elsif (!$donotrecurse) {
1.39      www      5842: # ------------------------------------------ There is more than one possibility
                   5843:                      my $realpossible=0;
1.191     harris41 5844:                      foreach (@possibilities) {
1.39      www      5845: 			 my $file=$bighash{'src_'.$_};
                   5846:                          if (&allowed('bre',$file)) {
                   5847:          		    my ($mapid,$resid)=split(/\./,$_);
                   5848:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   5849: 				$realpossible++;
1.626     albertel 5850:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5851: 						    $resid,$thisfn);
1.39      www      5852:                             }
                   5853: 			 }
1.191     harris41 5854:                      }
1.39      www      5855: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      5856:                  } else {
                   5857:                      $syval='';
1.37      www      5858:                  }
                   5859: 	      }
                   5860:               untie(%bighash)
1.481     raeburn  5861:            }
1.31      www      5862:         }
1.62      www      5863:         if ($syval) {
1.620     albertel 5864: 	    return $env{$cache_str}=$syval;
1.62      www      5865:         }
1.31      www      5866:     }
1.44      www      5867:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 5868:     return $env{$cache_str}='';
1.31      www      5869: }
                   5870: 
                   5871: # ---------------------------------------------------------- Return random seed
                   5872: 
1.32      www      5873: sub numval {
                   5874:     my $txt=shift;
                   5875:     $txt=~tr/A-J/0-9/;
                   5876:     $txt=~tr/a-j/0-9/;
                   5877:     $txt=~tr/K-T/0-9/;
                   5878:     $txt=~tr/k-t/0-9/;
                   5879:     $txt=~tr/U-Z/0-5/;
                   5880:     $txt=~tr/u-z/0-5/;
                   5881:     $txt=~s/\D//g;
1.564     albertel 5882:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      5883:     return int($txt);
1.368     albertel 5884: }
                   5885: 
1.484     albertel 5886: sub numval2 {
                   5887:     my $txt=shift;
                   5888:     $txt=~tr/A-J/0-9/;
                   5889:     $txt=~tr/a-j/0-9/;
                   5890:     $txt=~tr/K-T/0-9/;
                   5891:     $txt=~tr/k-t/0-9/;
                   5892:     $txt=~tr/U-Z/0-5/;
                   5893:     $txt=~tr/u-z/0-5/;
                   5894:     $txt=~s/\D//g;
                   5895:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5896:     my $total;
                   5897:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5898:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5899:     return int($total);
                   5900: }
                   5901: 
1.575     albertel 5902: sub numval3 {
                   5903:     use integer;
                   5904:     my $txt=shift;
                   5905:     $txt=~tr/A-J/0-9/;
                   5906:     $txt=~tr/a-j/0-9/;
                   5907:     $txt=~tr/K-T/0-9/;
                   5908:     $txt=~tr/k-t/0-9/;
                   5909:     $txt=~tr/U-Z/0-5/;
                   5910:     $txt=~tr/u-z/0-5/;
                   5911:     $txt=~s/\D//g;
                   5912:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5913:     my $total;
                   5914:     foreach my $val (@txts) { $total+=$val; }
                   5915:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5916:     return $total;
                   5917: }
                   5918: 
1.675     albertel 5919: sub digest {
                   5920:     my ($data)=@_;
                   5921:     my $digest=&Digest::MD5::md5($data);
                   5922:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   5923:     my ($e,$f);
                   5924:     {
                   5925:         use integer;
                   5926:         $e=($a+$b);
                   5927:         $f=($c+$d);
                   5928:         if ($_64bit) {
                   5929:             $e=(($e<<32)>>32);
                   5930:             $f=(($f<<32)>>32);
                   5931:         }
                   5932:     }
                   5933:     if (wantarray) {
                   5934: 	return ($e,$f);
                   5935:     } else {
                   5936: 	my $g;
                   5937: 	{
                   5938: 	    use integer;
                   5939: 	    $g=($e+$f);
                   5940: 	    if ($_64bit) {
                   5941: 		$g=(($g<<32)>>32);
                   5942: 	    }
                   5943: 	}
                   5944: 	return $g;
                   5945:     }
                   5946: }
                   5947: 
1.368     albertel 5948: sub latest_rnd_algorithm_id {
1.675     albertel 5949:     return '64bit5';
1.366     albertel 5950: }
1.32      www      5951: 
1.503     albertel 5952: sub get_rand_alg {
                   5953:     my ($courseid)=@_;
                   5954:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   5955:     if ($courseid) {
1.620     albertel 5956: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 5957:     }
                   5958:     return &latest_rnd_algorithm_id();
                   5959: }
                   5960: 
1.562     albertel 5961: sub validCODE {
                   5962:     my ($CODE)=@_;
                   5963:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5964:     return 0;
                   5965: }
                   5966: 
1.491     albertel 5967: sub getCODE {
1.620     albertel 5968:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 5969:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   5970: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   5971: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5972: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5973:     }
                   5974:     return undef;
                   5975: }
                   5976: 
1.31      www      5977: sub rndseed {
1.155     albertel 5978:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5979: 
                   5980:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5981:     if (!$symb) {
1.366     albertel 5982: 	unless ($symb=$wsymb) { return time; }
                   5983:     }
                   5984:     if (!$courseid) { $courseid=$wcourseid; }
                   5985:     if (!$domain) { $domain=$wdomain; }
                   5986:     if (!$username) { $username=$wusername }
1.503     albertel 5987:     my $which=&get_rand_alg();
1.491     albertel 5988:     if (defined(&getCODE())) {
1.675     albertel 5989: 	if ($which eq '64bit5') {
                   5990: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   5991: 	} elsif ($which eq '64bit4') {
1.575     albertel 5992: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5993: 	} else {
                   5994: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5995: 	}
1.675     albertel 5996:     } elsif ($which eq '64bit5') {
                   5997: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 5998:     } elsif ($which eq '64bit4') {
                   5999: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6000:     } elsif ($which eq '64bit3') {
                   6001: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6002:     } elsif ($which eq '64bit2') {
                   6003: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6004:     } elsif ($which eq '64bit') {
                   6005: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6006:     }
                   6007:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6008: }
                   6009: 
                   6010: sub rndseed_32bit {
                   6011:     my ($symb,$courseid,$domain,$username)=@_;
                   6012:     {
                   6013: 	use integer;
                   6014: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6015: 	my $symbseed=numval($symb) << 22;
                   6016: 	my $namechck=unpack("%32C*",$username) << 17;
                   6017: 	my $nameseed=numval($username) << 12;
                   6018: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6019: 	my $courseseed=unpack("%32C*",$courseid);
                   6020: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6021: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6022: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6023: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6024: 	return $num;
                   6025:     }
                   6026: }
                   6027: 
                   6028: sub rndseed_64bit {
                   6029:     my ($symb,$courseid,$domain,$username)=@_;
                   6030:     {
                   6031: 	use integer;
                   6032: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6033: 	my $symbseed=numval($symb) << 10;
                   6034: 	my $namechck=unpack("%32S*",$username);
                   6035: 	
                   6036: 	my $nameseed=numval($username) << 21;
                   6037: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6038: 	my $courseseed=unpack("%32S*",$courseid);
                   6039: 	
                   6040: 	my $num1=$symbchck+$symbseed+$namechck;
                   6041: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6042: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6043: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6044: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6046: 	return "$num1,$num2";
1.155     albertel 6047:     }
1.366     albertel 6048: }
                   6049: 
1.443     albertel 6050: sub rndseed_64bit2 {
                   6051:     my ($symb,$courseid,$domain,$username)=@_;
                   6052:     {
                   6053: 	use integer;
                   6054: 	# strings need to be an even # of cahracters long, it it is odd the
                   6055:         # last characters gets thrown away
                   6056: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6057: 	my $symbseed=numval($symb) << 10;
                   6058: 	my $namechck=unpack("%32S*",$username.' ');
                   6059: 	
                   6060: 	my $nameseed=numval($username) << 21;
1.501     albertel 6061: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6062: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6063: 	
                   6064: 	my $num1=$symbchck+$symbseed+$namechck;
                   6065: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6066: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6067: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6068: 	return "$num1,$num2";
                   6069:     }
                   6070: }
                   6071: 
                   6072: sub rndseed_64bit3 {
                   6073:     my ($symb,$courseid,$domain,$username)=@_;
                   6074:     {
                   6075: 	use integer;
                   6076: 	# strings need to be an even # of cahracters long, it it is odd the
                   6077:         # last characters gets thrown away
                   6078: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6079: 	my $symbseed=numval2($symb) << 10;
                   6080: 	my $namechck=unpack("%32S*",$username.' ');
                   6081: 	
                   6082: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6083: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6084: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6085: 	
                   6086: 	my $num1=$symbchck+$symbseed+$namechck;
                   6087: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6088: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6089: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6090: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6091: 	
1.503     albertel 6092: 	return "$num1:$num2";
1.443     albertel 6093:     }
                   6094: }
                   6095: 
1.575     albertel 6096: sub rndseed_64bit4 {
                   6097:     my ($symb,$courseid,$domain,$username)=@_;
                   6098:     {
                   6099: 	use integer;
                   6100: 	# strings need to be an even # of cahracters long, it it is odd the
                   6101:         # last characters gets thrown away
                   6102: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6103: 	my $symbseed=numval3($symb) << 10;
                   6104: 	my $namechck=unpack("%32S*",$username.' ');
                   6105: 	
                   6106: 	my $nameseed=numval3($username) << 21;
                   6107: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6108: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6109: 	
                   6110: 	my $num1=$symbchck+$symbseed+$namechck;
                   6111: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6112: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6113: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6114: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6115: 	
                   6116: 	return "$num1:$num2";
                   6117:     }
                   6118: }
                   6119: 
1.675     albertel 6120: sub rndseed_64bit5 {
                   6121:     my ($symb,$courseid,$domain,$username)=@_;
                   6122:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6123:     return "$num1:$num2";
                   6124: }
                   6125: 
1.366     albertel 6126: sub rndseed_CODE_64bit {
                   6127:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6128:     {
1.366     albertel 6129: 	use integer;
1.443     albertel 6130: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6131: 	my $symbseed=numval2($symb);
1.491     albertel 6132: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6133: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6134: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6135: 	my $num1=$symbseed+$CODEchck;
                   6136: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6137: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6138: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6139: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6140: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6141: 	return "$num1:$num2";
1.366     albertel 6142:     }
                   6143: }
                   6144: 
1.575     albertel 6145: sub rndseed_CODE_64bit4 {
                   6146:     my ($symb,$courseid,$domain,$username)=@_;
                   6147:     {
                   6148: 	use integer;
                   6149: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6150: 	my $symbseed=numval3($symb);
                   6151: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6152: 	my $CODEseed=numval3(&getCODE());
                   6153: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6154: 	my $num1=$symbseed+$CODEchck;
                   6155: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6156: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6157: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6158: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6159: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6160: 	return "$num1:$num2";
                   6161:     }
                   6162: }
                   6163: 
1.675     albertel 6164: sub rndseed_CODE_64bit5 {
                   6165:     my ($symb,$courseid,$domain,$username)=@_;
                   6166:     my $code = &getCODE();
                   6167:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6168:     return "$num1:$num2";
                   6169: }
                   6170: 
1.366     albertel 6171: sub setup_random_from_rndseed {
                   6172:     my ($rndseed)=@_;
1.503     albertel 6173:     if ($rndseed =~/([,:])/) {
                   6174: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6175: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6176:     } else {
                   6177: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6178:     }
1.36      albertel 6179: }
                   6180: 
1.474     albertel 6181: sub latest_receipt_algorithm_id {
                   6182:     return 'receipt2';
                   6183: }
                   6184: 
1.480     www      6185: sub recunique {
                   6186:     my $fucourseid=shift;
                   6187:     my $unique;
1.620     albertel 6188:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6189: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6190:     } else {
                   6191: 	$unique=$perlvar{'lonReceipt'};
                   6192:     }
                   6193:     return unpack("%32C*",$unique);
                   6194: }
                   6195: 
                   6196: sub recprefix {
                   6197:     my $fucourseid=shift;
                   6198:     my $prefix;
1.620     albertel 6199:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6200: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6201:     } else {
                   6202: 	$prefix=$perlvar{'lonHostID'};
                   6203:     }
                   6204:     return unpack("%32C*",$prefix);
                   6205: }
                   6206: 
1.76      www      6207: sub ireceipt {
1.474     albertel 6208:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6209:     my $cuname=unpack("%32C*",$funame);
                   6210:     my $cudom=unpack("%32C*",$fudom);
                   6211:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6212:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6213:     my $cunique=&recunique($fucourseid);
1.474     albertel 6214:     my $cpart=unpack("%32S*",$part);
1.480     www      6215:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6216:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6217: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6218: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6219: 			       " and ".($cpart%$cudom));
                   6220: 			       
                   6221: 	$return.= ($cunique%$cuname+
                   6222: 		   $cunique%$cudom+
                   6223: 		   $cusymb%$cuname+
                   6224: 		   $cusymb%$cudom+
                   6225: 		   $cucourseid%$cuname+
                   6226: 		   $cucourseid%$cudom+
                   6227: 		   $cpart%$cuname+
                   6228: 		   $cpart%$cudom);
                   6229:     } else {
                   6230: 	$return.= ($cunique%$cuname+
                   6231: 		   $cunique%$cudom+
                   6232: 		   $cusymb%$cuname+
                   6233: 		   $cusymb%$cudom+
                   6234: 		   $cucourseid%$cuname+
                   6235: 		   $cucourseid%$cudom);
                   6236:     }
                   6237:     return $return;
1.76      www      6238: }
                   6239: 
                   6240: sub receipt {
1.474     albertel 6241:     my ($part)=@_;
                   6242:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6243:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6244: }
1.260     ng       6245: 
1.36      albertel 6246: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6247: # returns either the contents of the file or 
                   6248: # -1 if the file doesn't exist
1.481     raeburn  6249: #
                   6250: # if the target is a file that was uploaded via DOCS, 
                   6251: # a check will be made to see if a current copy exists on the local server,
                   6252: # if it does this will be served, otherwise a copy will be retrieved from
                   6253: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6254: # the local server.   
1.472     albertel 6255: 
1.36      albertel 6256: sub getfile {
1.538     albertel 6257:     my ($file) = @_;
1.609     banghart 6258:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6259:     &repcopy($file);
                   6260:     return &readfile($file);
                   6261: }
                   6262: 
                   6263: sub repcopy_userfile {
                   6264:     my ($file)=@_;
1.609     banghart 6265:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6266:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6267:     my ($cdom,$cnum,$filename) = 
                   6268: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6269:     my ($info,$rtncode);
                   6270:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6271:     if (-e "$file") {
                   6272: 	my @fileinfo = stat($file);
                   6273: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6274: 	if ($lwpresp ne 'ok') {
                   6275: 	    if ($rtncode eq '404') {
1.538     albertel 6276: 		unlink($file);
1.482     albertel 6277: 	    }
1.517     albertel 6278: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6279: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6280: 	    #my $response=$ua->request($request);
                   6281: 	    #if ($response->is_success()) {
                   6282: 	#	return $response->content;
                   6283: 	#    } else {
                   6284: 	#	return -1;
                   6285: 	#    }
1.482     albertel 6286: 	    return -1;
                   6287: 	}
                   6288: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6289: 	    return 'ok';
1.482     albertel 6290: 	}
                   6291: 	$info = '';
1.538     albertel 6292: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6293: 	if ($lwpresp ne 'ok') {
                   6294: 	    return -1;
                   6295: 	}
                   6296:     } else {
1.538     albertel 6297: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6298: 	if ($lwpresp ne 'ok') {
1.517     albertel 6299: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6300: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6301: 	    my $response=$ua->request($request);
                   6302: 	    if ($response->is_success()) {
1.538     albertel 6303: 		$info=$response->content;
1.517     albertel 6304: 	    } else {
                   6305: 		return -1;
                   6306: 	    }
1.482     albertel 6307: 	}
                   6308: 	my @parts = ($cdom,$cnum); 
                   6309: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6310: 	    push @parts, split(/\//,$1);
1.518     albertel 6311: 	}
1.538     albertel 6312: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6313: 	foreach my $part (@parts) {
                   6314: 	    $path .= '/'.$part;
                   6315: 	    if (!-e $path) {
                   6316: 		mkdir($path,0770);
                   6317: 	    }
                   6318: 	}
                   6319:     }
1.538     albertel 6320:     open(FILE,">$file");
1.482     albertel 6321:     print FILE $info;
                   6322:     close(FILE);
1.607     raeburn  6323:     return 'ok';
1.481     raeburn  6324: }
                   6325: 
1.517     albertel 6326: sub tokenwrapper {
                   6327:     my $uri=shift;
1.552     albertel 6328:     $uri=~s|^http\://([^/]+)||;
                   6329:     $uri=~s|^/||;
1.620     albertel 6330:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6331:     my $token=$1;
1.552     albertel 6332:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6333:     if ($udom && $uname && $file) {
                   6334: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6335:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6336:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6337:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6338:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6339:     } else {
                   6340:         return '/adm/notfound.html';
                   6341:     }
                   6342: }
                   6343: 
1.481     raeburn  6344: sub getuploaded {
                   6345:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6346:     $uri=~s/^\///;
                   6347:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6348:     my $ua=new LWP::UserAgent;
                   6349:     my $request=new HTTP::Request($reqtype,$uri);
                   6350:     my $response=$ua->request($request);
                   6351:     $$rtncode = $response->code;
1.482     albertel 6352:     if (! $response->is_success()) {
                   6353: 	return 'failed';
                   6354:     }      
                   6355:     if ($reqtype eq 'HEAD') {
1.486     www      6356: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6357:     } elsif ($reqtype eq 'GET') {
                   6358: 	$$info = $response->content;
1.472     albertel 6359:     }
1.482     albertel 6360:     return 'ok';
1.36      albertel 6361: }
                   6362: 
1.481     raeburn  6363: sub readfile {
                   6364:     my $file = shift;
                   6365:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6366:     my $fh;
                   6367:     open($fh,"<$file");
                   6368:     my $a='';
                   6369:     while (<$fh>) { $a .=$_; }
                   6370:     return $a;
                   6371: }
                   6372: 
1.36      albertel 6373: sub filelocation {
1.590     banghart 6374:     my ($dir,$file) = @_;
                   6375:     my $location;
                   6376:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6377: 
                   6378:     if ($file =~ m-^/adm/-) {
                   6379: 	$file=~s-^/adm/wrapper/-/-;
                   6380: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6381:     }
1.590     banghart 6382:     if ($file=~m:^/~:) { # is a contruction space reference
                   6383:         $location = $file;
                   6384:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6385:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6386: 	# is a correct contruction space reference
                   6387:         $location = $file;
1.609     banghart 6388:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6389:         my ($udom,$uname,$filename)=
1.609     banghart 6390:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6391:         my $home=&homeserver($uname,$udom);
                   6392:         my $is_me=0;
                   6393:         my @ids=&current_machine_ids();
                   6394:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6395:         if ($is_me) {
                   6396:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   6397:   	      '/userfiles/'.$filename;
                   6398:         } else {
                   6399:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6400:   	      $udom.'/'.$uname.'/'.$filename;
                   6401:         }
                   6402:     } else {
                   6403:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6404:         $file=~s:^/res/:/:;
                   6405:         if ( !( $file =~ m:^/:) ) {
                   6406:             $location = $dir. '/'.$file;
                   6407:         } else {
                   6408:             $location = '/home/httpd/html/res'.$file;
                   6409:         }
1.59      albertel 6410:     }
1.590     banghart 6411:     $location=~s://+:/:g; # remove duplicate /
                   6412:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6413:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6414:     return $location;
1.46      www      6415: }
1.36      albertel 6416: 
1.46      www      6417: sub hreflocation {
                   6418:     my ($dir,$file)=@_;
1.460     albertel 6419:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6420: 	$file=filelocation($dir,$file);
1.700     albertel 6421:     } elsif ($file=~m-^/adm/-) {
                   6422: 	$file=~s-^/adm/wrapper/-/-;
                   6423: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6424:     }
                   6425:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6426: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6427:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6428: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6429:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6430: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6431: 	    -/uploaded/$1/$2/-x;
1.46      www      6432:     }
1.462     albertel 6433:     return $file;
1.465     albertel 6434: }
                   6435: 
                   6436: sub current_machine_domains {
                   6437:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6438:     my @domains;
                   6439:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6440: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6441: 	if ($hostname eq $name) {
                   6442: 	    push(@domains,$hostdom{$id});
                   6443: 	}
                   6444:     }
                   6445:     return @domains;
                   6446: }
                   6447: 
                   6448: sub current_machine_ids {
                   6449:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6450:     my @ids;
                   6451:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6452: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6453: 	if ($hostname eq $name) {
                   6454: 	    push(@ids,$id);
                   6455: 	}
                   6456:     }
                   6457:     return @ids;
1.31      www      6458: }
                   6459: 
                   6460: # ------------------------------------------------------------- Declutters URLs
                   6461: 
                   6462: sub declutter {
                   6463:     my $thisfn=shift;
1.569     albertel 6464:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6465:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6466:     $thisfn=~s/^\///;
1.697     albertel 6467:     $thisfn=~s|^adm/wrapper/||;
                   6468:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      6469:     $thisfn=~s/^res\///;
1.235     www      6470:     $thisfn=~s/\?.+$//;
1.268     www      6471:     return $thisfn;
                   6472: }
                   6473: 
                   6474: # ------------------------------------------------------------- Clutter up URLs
                   6475: 
                   6476: sub clutter {
                   6477:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6478:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6479:        $thisfn='/res'.$thisfn; 
                   6480:     }
1.694     albertel 6481:     if ($thisfn !~m|/adm|) {
1.695     albertel 6482: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 6483: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 6484: 	} else {
                   6485: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   6486: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 6487: 	    if ($embstyle eq 'ssi'
                   6488: 		|| ($embstyle eq 'hdn')
                   6489: 		|| ($embstyle eq 'rat')
                   6490: 		|| ($embstyle eq 'prv')
                   6491: 		|| ($embstyle eq 'ign')) {
                   6492: 		#do nothing with these
                   6493: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 6494: 		|| ($embstyle eq 'emb')
                   6495: 		|| ($embstyle eq 'wrp')) {
                   6496: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 6497: 	    } elsif ($embstyle eq 'unk'
                   6498: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 6499: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 6500: 	    } else {
1.718     www      6501: #		&logthis("Got a blank emb style");
1.695     albertel 6502: 	    }
1.694     albertel 6503: 	}
                   6504:     }
1.31      www      6505:     return $thisfn;
1.12      www      6506: }
                   6507: 
1.557     albertel 6508: sub freeze_escape {
                   6509:     my ($value)=@_;
                   6510:     if (ref($value)) {
                   6511: 	$value=&nfreeze($value);
                   6512: 	return '__FROZEN__'.&escape($value);
                   6513:     }
                   6514:     return &escape($value);
                   6515: }
                   6516: 
1.12      www      6517: # -------------------------------------------------------- Escape Special Chars
                   6518: 
                   6519: sub escape {
                   6520:     my $str=shift;
                   6521:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   6522:     return $str;
                   6523: }
                   6524: 
                   6525: # ----------------------------------------------------- Un-Escape Special Chars
                   6526: 
                   6527: sub unescape {
                   6528:     my $str=shift;
                   6529:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   6530:     return $str;
                   6531: }
1.11      www      6532: 
1.557     albertel 6533: sub thaw_unescape {
                   6534:     my ($value)=@_;
                   6535:     if ($value =~ /^__FROZEN__/) {
                   6536: 	substr($value,0,10,undef);
                   6537: 	$value=&unescape($value);
                   6538: 	return &thaw($value);
                   6539:     }
                   6540:     return &unescape($value);
                   6541: }
                   6542: 
1.436     albertel 6543: sub correct_line_ends {
                   6544:     my ($result)=@_;
                   6545:     $$result =~s/\r\n/\n/mg;
                   6546:     $$result =~s/\r/\n/mg;
1.415     albertel 6547: }
1.1       albertel 6548: # ================================================================ Main Program
                   6549: 
1.184     www      6550: sub goodbye {
1.204     albertel 6551:    &logthis("Starting Shut down");
1.443     albertel 6552: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6553:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6554: #converted
1.599     albertel 6555: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6556:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6557: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6558: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6559: #1.1 only
1.599     albertel 6560: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6561: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6562: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6563: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6564:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6565:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6566:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6567:    &flushcourselogs();
                   6568:    &logthis("Shutting down");
                   6569: }
                   6570: 
1.179     www      6571: BEGIN {
1.228     harris41 6572: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6573:     unless ($readit) {
1.217     harris41 6574: {
1.581     matthew  6575:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6576:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6577: 
                   6578:     while (my $configline=<$config>) {
1.484     albertel 6579:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6580: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6581:            chomp($varvalue);
1.1       albertel 6582:            $perlvar{$varname}=$varvalue;
                   6583:         }
                   6584:     }
1.448     albertel 6585:     close($config);
1.1       albertel 6586: }
1.227     harris41 6587: {
1.448     albertel 6588:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6589: 
                   6590:     while (my $configline=<$config>) {
                   6591:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6592: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6593:            chomp($varvalue);
                   6594:            $perlvar{$varname}=$varvalue;
                   6595:         }
                   6596:     }
1.448     albertel 6597:     close($config);
1.227     harris41 6598: }
1.1       albertel 6599: 
1.327     albertel 6600: # ------------------------------------------------------------ Read domain file
                   6601: {
                   6602:     %domaindescription = ();
                   6603:     %domain_auth_def = ();
                   6604:     %domain_auth_arg_def = ();
1.448     albertel 6605:     my $fh;
                   6606:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6607:        while (<$fh>) {
1.390     matthew  6608:            next if (/^(\#|\s*$)/);
                   6609: #           next if /^\#/;
1.327     albertel 6610:            chomp;
1.403     www      6611:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  6612: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      6613: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6614:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6615: 	   $domaindescription{$domain}=$domain_description;
                   6616: 	   $domain_lang_def{$domain}=$def_lang;
                   6617: 	   $domain_city{$domain}=$city;
                   6618: 	   $domain_longi{$domain}=$longi;
                   6619: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  6620:            $domain_primary{$domain}=$primary;
1.403     www      6621: 
1.448     albertel 6622:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6623: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6624: 	}
1.327     albertel 6625:     }
1.448     albertel 6626:     close ($fh);
1.327     albertel 6627: }
                   6628: 
                   6629: 
1.1       albertel 6630: # ------------------------------------------------------------- Read hosts file
                   6631: {
1.448     albertel 6632:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6633: 
                   6634:     while (my $configline=<$config>) {
1.303     matthew  6635:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6636:        chomp($configline);
1.595     albertel 6637:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6638:        $name=~s/\s//g;
1.595     albertel 6639:        if ($id && $domain && $role && $name) {
1.252     albertel 6640: 	 $hostname{$id}=$name;
                   6641: 	 $hostdom{$id}=$domain;
                   6642: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6643:        }
1.1       albertel 6644:     }
1.448     albertel 6645:     close($config);
1.619     albertel 6646:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 6647:     #&get_iphost();
1.1       albertel 6648: }
                   6649: 
1.598     albertel 6650: sub get_iphost {
                   6651:     if (%iphost) { return %iphost; }
1.653     albertel 6652:     my %name_to_ip;
1.598     albertel 6653:     foreach my $id (keys(%hostname)) {
                   6654: 	my $name=$hostname{$id};
1.653     albertel 6655: 	my $ip;
                   6656: 	if (!exists($name_to_ip{$name})) {
                   6657: 	    $ip = gethostbyname($name);
                   6658: 	    if (!$ip || length($ip) ne 4) {
                   6659: 		&logthis("Skipping host $id name $name no IP found\n");
                   6660: 		next;
                   6661: 	    }
                   6662: 	    $ip=inet_ntoa($ip);
                   6663: 	    $name_to_ip{$name} = $ip;
                   6664: 	} else {
                   6665: 	    $ip = $name_to_ip{$name};
1.598     albertel 6666: 	}
                   6667: 	push(@{$iphost{$ip}},$id);
                   6668:     }
                   6669:     return %iphost;
                   6670: }
                   6671: 
1.1       albertel 6672: # ------------------------------------------------------ Read spare server file
                   6673: {
1.448     albertel 6674:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 6675: 
                   6676:     while (my $configline=<$config>) {
                   6677:        chomp($configline);
1.284     matthew  6678:        if ($configline) {
1.1       albertel 6679:           $spareid{$configline}=1;
                   6680:        }
                   6681:     }
1.448     albertel 6682:     close($config);
1.1       albertel 6683: }
1.11      www      6684: # ------------------------------------------------------------ Read permissions
                   6685: {
1.448     albertel 6686:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      6687: 
                   6688:     while (my $configline=<$config>) {
1.448     albertel 6689: 	chomp($configline);
                   6690: 	if ($configline) {
                   6691: 	    my ($role,$perm)=split(/ /,$configline);
                   6692: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   6693: 	}
1.11      www      6694:     }
1.448     albertel 6695:     close($config);
1.11      www      6696: }
                   6697: 
                   6698: # -------------------------------------------- Read plain texts for permissions
                   6699: {
1.448     albertel 6700:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      6701: 
                   6702:     while (my $configline=<$config>) {
1.448     albertel 6703: 	chomp($configline);
                   6704: 	if ($configline) {
                   6705: 	    my ($short,$plain)=split(/:/,$configline);
                   6706: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   6707: 	}
1.135     www      6708:     }
1.448     albertel 6709:     close($config);
1.135     www      6710: }
                   6711: 
                   6712: # ---------------------------------------------------------- Read package table
                   6713: {
1.448     albertel 6714:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      6715: 
                   6716:     while (my $configline=<$config>) {
1.483     albertel 6717: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 6718: 	chomp($configline);
                   6719: 	my ($short,$plain)=split(/:/,$configline);
                   6720: 	my ($pack,$name)=split(/\&/,$short);
                   6721: 	if ($plain ne '') {
                   6722: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   6723: 	    $packagetab{$short}=$plain; 
                   6724: 	}
1.11      www      6725:     }
1.448     albertel 6726:     close($config);
1.329     matthew  6727: }
                   6728: 
                   6729: # ------------- set up temporary directory
                   6730: {
                   6731:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   6732: 
1.11      www      6733: }
                   6734: 
1.599     albertel 6735: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      6736: 
1.281     www      6737: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      6738: $dumpcount=0;
1.22      www      6739: 
1.163     harris41 6740: &logtouch();
1.672     albertel 6741: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      6742: $readit=1;
1.564     albertel 6743:     {
                   6744: 	use integer;
                   6745: 	my $test=(2**32)+1;
1.568     albertel 6746: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 6747: 	&logthis(" Detected 64bit platform ($_64bit)");
                   6748:     }
1.195     www      6749: }
1.1       albertel 6750: }
1.179     www      6751: 
1.1       albertel 6752: 1;
1.191     harris41 6753: __END__
                   6754: 
1.243     albertel 6755: =pod
                   6756: 
1.191     harris41 6757: =head1 NAME
                   6758: 
1.243     albertel 6759: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 6760: 
                   6761: =head1 SYNOPSIS
                   6762: 
1.243     albertel 6763: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 6764: 
                   6765:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   6766: 
1.243     albertel 6767: Common parameters:
                   6768: 
                   6769: =over 4
                   6770: 
                   6771: =item *
                   6772: 
                   6773: $uname : an internal username (if $cname expecting a course Id specifically)
                   6774: 
                   6775: =item *
                   6776: 
                   6777: $udom : a domain (if $cdom expecting a course's domain specifically)
                   6778: 
                   6779: =item *
                   6780: 
                   6781: $symb : a resource instance identifier
                   6782: 
                   6783: =item *
                   6784: 
                   6785: $namespace : the name of a .db file that contains the data needed or
                   6786: being set.
                   6787: 
                   6788: =back
                   6789: 
1.394     bowersj2 6790: =head1 OVERVIEW
1.191     harris41 6791: 
1.394     bowersj2 6792: lonnet provides subroutines which interact with the
                   6793: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   6794: about classes, users, and resources.
1.243     albertel 6795: 
                   6796: For many of these objects you can also use this to store data about
                   6797: them or modify them in various ways.
1.191     harris41 6798: 
1.394     bowersj2 6799: =head2 Symbs
1.191     harris41 6800: 
1.394     bowersj2 6801: To identify a specific instance of a resource, LON-CAPA uses symbols
                   6802: or "symbs"X<symb>. These identifiers are built from the URL of the
                   6803: map, the resource number of the resource in the map, and the URL of
                   6804: the resource itself. The latter is somewhat redundant, but might help
                   6805: if maps change.
                   6806: 
                   6807: An example is
                   6808: 
                   6809:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   6810: 
                   6811: The respective map entry is
                   6812: 
                   6813:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   6814:   title="Problem 2">
                   6815:  </resource>
                   6816: 
                   6817: Symbs are used by the random number generator, as well as to store and
                   6818: restore data specific to a certain instance of for example a problem.
                   6819: 
                   6820: =head2 Storing And Retrieving Data
                   6821: 
                   6822: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   6823: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   6824: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   6825: is is the non-critical message twin of cstore. These functions are for
                   6826: handlers to store a perl hash to a user's permanent data space in an
                   6827: easy manner, and to retrieve it again on another call. It is expected
                   6828: that a handler would use this once at the beginning to retrieve data,
                   6829: and then again once at the end to send only the new data back.
                   6830: 
                   6831: The data is stored in the user's data directory on the user's
                   6832: homeserver under the ID of the course.
                   6833: 
                   6834: The hash that is returned by restore will have all of the previous
                   6835: value for all of the elements of the hash.
                   6836: 
                   6837: Example:
                   6838: 
                   6839:  #creating a hash
                   6840:  my %hash;
                   6841:  $hash{'foo'}='bar';
                   6842: 
                   6843:  #storing it
                   6844:  &Apache::lonnet::cstore(\%hash);
                   6845: 
                   6846:  #changing a value
                   6847:  $hash{'foo'}='notbar';
                   6848: 
                   6849:  #adding a new value
                   6850:  $hash{'bar'}='foo';
                   6851:  &Apache::lonnet::cstore(\%hash);
                   6852: 
                   6853:  #retrieving the hash
                   6854:  my %history=&Apache::lonnet::restore();
                   6855: 
                   6856:  #print the hash
                   6857:  foreach my $key (sort(keys(%history))) {
                   6858:    print("\%history{$key} = $history{$key}");
                   6859:  }
                   6860: 
                   6861: Will print out:
1.191     harris41 6862: 
1.394     bowersj2 6863:  %history{1:foo} = bar
                   6864:  %history{1:keys} = foo:timestamp
                   6865:  %history{1:timestamp} = 990455579
                   6866:  %history{2:bar} = foo
                   6867:  %history{2:foo} = notbar
                   6868:  %history{2:keys} = foo:bar:timestamp
                   6869:  %history{2:timestamp} = 990455580
                   6870:  %history{bar} = foo
                   6871:  %history{foo} = notbar
                   6872:  %history{timestamp} = 990455580
                   6873:  %history{version} = 2
                   6874: 
                   6875: Note that the special hash entries C<keys>, C<version> and
                   6876: C<timestamp> were added to the hash. C<version> will be equal to the
                   6877: total number of versions of the data that have been stored. The
                   6878: C<timestamp> attribute will be the UNIX time the hash was
                   6879: stored. C<keys> is available in every historical section to list which
                   6880: keys were added or changed at a specific historical revision of a
                   6881: hash.
                   6882: 
                   6883: B<Warning>: do not store the hash that restore returns directly. This
                   6884: will cause a mess since it will restore the historical keys as if the
                   6885: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 6886: 
1.394     bowersj2 6887: Calling convention:
1.191     harris41 6888: 
1.394     bowersj2 6889:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   6890:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 6891: 
1.394     bowersj2 6892: For more detailed information, see lonnet specific documentation.
1.191     harris41 6893: 
1.394     bowersj2 6894: =head1 RETURN MESSAGES
1.191     harris41 6895: 
1.394     bowersj2 6896: =over 4
1.191     harris41 6897: 
1.394     bowersj2 6898: =item * B<con_lost>: unable to contact remote host
1.191     harris41 6899: 
1.394     bowersj2 6900: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   6901: when the connection is brought back up
1.191     harris41 6902: 
1.394     bowersj2 6903: =item * B<con_failed>: unable to contact remote host and unable to save message
                   6904: for later delivery
1.191     harris41 6905: 
1.394     bowersj2 6906: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 6907: 
1.394     bowersj2 6908: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 6909: that was requested
1.191     harris41 6910: 
1.243     albertel 6911: =back
1.191     harris41 6912: 
1.243     albertel 6913: =head1 PUBLIC SUBROUTINES
1.191     harris41 6914: 
1.243     albertel 6915: =head2 Session Environment Functions
1.191     harris41 6916: 
1.243     albertel 6917: =over 4
1.191     harris41 6918: 
1.394     bowersj2 6919: =item * 
                   6920: X<appenv()>
                   6921: B<appenv(%hash)>: the value of %hash is written to
                   6922: the user envirnoment file, and will be restored for each access this
1.620     albertel 6923: user makes during this session, also modifies the %env for the current
1.394     bowersj2 6924: process
1.191     harris41 6925: 
                   6926: =item *
1.394     bowersj2 6927: X<delenv()>
                   6928: B<delenv($regexp)>: removes all items from the session
                   6929: environment file that matches the regular expression in $regexp. The
1.620     albertel 6930: values are also delted from the current processes %env.
1.191     harris41 6931: 
1.243     albertel 6932: =back
                   6933: 
                   6934: =head2 User Information
1.191     harris41 6935: 
1.243     albertel 6936: =over 4
1.191     harris41 6937: 
                   6938: =item *
1.394     bowersj2 6939: X<queryauthenticate()>
                   6940: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 6941: authentication scheme
                   6942: 
                   6943: =item *
1.394     bowersj2 6944: X<authenticate()>
                   6945: B<authenticate($uname,$upass,$udom)>: try to
                   6946: authenticate user from domain's lib servers (first use the current
                   6947: one). C<$upass> should be the users password.
1.191     harris41 6948: 
                   6949: =item *
1.394     bowersj2 6950: X<homeserver()>
                   6951: B<homeserver($uname,$udom)>: find the server which has
                   6952: the user's directory and files (there must be only one), this caches
                   6953: the answer, and also caches if there is a borken connection.
1.191     harris41 6954: 
                   6955: =item *
1.394     bowersj2 6956: X<idget()>
                   6957: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   6958: (IDs are a unique resource in a domain, there must be only 1 ID per
                   6959: username, and only 1 username per ID in a specific domain) (returns
                   6960: hash: id=>name,id=>name)
1.191     harris41 6961: 
                   6962: =item *
1.394     bowersj2 6963: X<idrget()>
                   6964: B<idrget($udom,@unames)>: find the IDs behind a list of
                   6965: usernames (returns hash: name=>id,name=>id)
1.191     harris41 6966: 
                   6967: =item *
1.394     bowersj2 6968: X<idput()>
                   6969: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 6970: 
                   6971: =item *
1.394     bowersj2 6972: X<rolesinit()>
                   6973: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 6974: 
                   6975: =item *
1.551     albertel 6976: X<getsection()>
                   6977: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 6978: course $cname, return section name/number or '' for "not in course"
                   6979: and '-1' for "no section"
                   6980: 
                   6981: =item *
1.394     bowersj2 6982: X<userenvironment()>
                   6983: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 6984: passed in @what from the requested user's environment, returns a hash
                   6985: 
                   6986: =back
                   6987: 
                   6988: =head2 User Roles
                   6989: 
                   6990: =over 4
                   6991: 
                   6992: =item *
                   6993: 
                   6994: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   6995: actions
                   6996:  F: full access
                   6997:  U,I,K: authentication modes (cxx only)
                   6998:  '': forbidden
                   6999:  1: user needs to choose course
                   7000:  2: browse allowed
                   7001: 
                   7002: =item *
                   7003: 
                   7004: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7005: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7006: and course level
                   7007: 
                   7008: =item *
                   7009: 
                   7010: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7011: explanation of a user role term
                   7012: 
                   7013: =back
                   7014: 
                   7015: =head2 User Modification
                   7016: 
                   7017: =over 4
                   7018: 
                   7019: =item *
                   7020: 
                   7021: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7022: user for the level given by URL.  Optional start and end dates (leave empty
                   7023: string or zero for "no date")
1.191     harris41 7024: 
                   7025: =item *
                   7026: 
1.243     albertel 7027: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7028: change a users, password, possible return values are: ok,
                   7029: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7030: refused
1.191     harris41 7031: 
                   7032: =item *
                   7033: 
1.243     albertel 7034: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7035: 
                   7036: =item *
                   7037: 
1.243     albertel 7038: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7039: modify user
1.191     harris41 7040: 
                   7041: =item *
                   7042: 
1.286     matthew  7043: modifystudent
                   7044: 
                   7045: modify a students enrollment and identification information.
                   7046: The course id is resolved based on the current users environment.  
                   7047: This means the envoking user must be a course coordinator or otherwise
                   7048: associated with a course.
                   7049: 
1.297     matthew  7050: This call is essentially a wrapper for lonnet::modifyuser and
                   7051: lonnet::modify_student_enrollment
1.286     matthew  7052: 
                   7053: Inputs: 
                   7054: 
                   7055: =over 4
                   7056: 
                   7057: =item B<$udom> Students loncapa domain
                   7058: 
                   7059: =item B<$uname> Students loncapa login name
                   7060: 
                   7061: =item B<$uid> Students id/student number
                   7062: 
                   7063: =item B<$umode> Students authentication mode
                   7064: 
                   7065: =item B<$upass> Students password
                   7066: 
                   7067: =item B<$first> Students first name
                   7068: 
                   7069: =item B<$middle> Students middle name
                   7070: 
                   7071: =item B<$last> Students last name
                   7072: 
                   7073: =item B<$gene> Students generation
                   7074: 
                   7075: =item B<$usec> Students section in course
                   7076: 
                   7077: =item B<$end> Unix time of the roles expiration
                   7078: 
                   7079: =item B<$start> Unix time of the roles start date
                   7080: 
                   7081: =item B<$forceid> If defined, allow $uid to be changed
                   7082: 
                   7083: =item B<$desiredhome> server to use as home server for student
                   7084: 
                   7085: =back
1.297     matthew  7086: 
                   7087: =item *
                   7088: 
                   7089: modify_student_enrollment
                   7090: 
                   7091: Change a students enrollment status in a class.  The environment variable
                   7092: 'role.request.course' must be defined for this function to proceed.
                   7093: 
                   7094: Inputs:
                   7095: 
                   7096: =over 4
                   7097: 
                   7098: =item $udom, students domain
                   7099: 
                   7100: =item $uname, students name
                   7101: 
                   7102: =item $uid, students user id
                   7103: 
                   7104: =item $first, students first name
                   7105: 
                   7106: =item $middle
                   7107: 
                   7108: =item $last
                   7109: 
                   7110: =item $gene
                   7111: 
                   7112: =item $usec
                   7113: 
                   7114: =item $end
                   7115: 
                   7116: =item $start
                   7117: 
                   7118: =back
                   7119: 
1.191     harris41 7120: 
                   7121: =item *
                   7122: 
1.243     albertel 7123: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7124: custom role; give a custom role to a user for the level given by URL.  Specify
                   7125: name and domain of role author, and role name
1.191     harris41 7126: 
                   7127: =item *
                   7128: 
1.243     albertel 7129: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7130: 
                   7131: =item *
                   7132: 
1.243     albertel 7133: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7134: 
                   7135: =back
                   7136: 
                   7137: =head2 Course Infomation
                   7138: 
                   7139: =over 4
1.191     harris41 7140: 
                   7141: =item *
                   7142: 
1.631     albertel 7143: coursedescription($courseid) : returns a hash of information about the
                   7144: specified course id, including all environment settings for the
                   7145: course, the description of the course will be in the hash under the
                   7146: key 'description'
1.191     harris41 7147: 
                   7148: =item *
                   7149: 
1.624     albertel 7150: resdata($name,$domain,$type,@which) : request for current parameter
                   7151: setting for a specific $type, where $type is either 'course' or 'user',
                   7152: @what should be a list of parameters to ask about. This routine caches
                   7153: answers for 5 minutes.
1.243     albertel 7154: 
                   7155: =back
                   7156: 
                   7157: =head2 Course Modification
                   7158: 
                   7159: =over 4
1.191     harris41 7160: 
                   7161: =item *
                   7162: 
1.243     albertel 7163: writecoursepref($courseid,%prefs) : write preferences (environment
                   7164: database) for a course
1.191     harris41 7165: 
                   7166: =item *
                   7167: 
1.243     albertel 7168: createcourse($udom,$description,$url) : make/modify course
                   7169: 
                   7170: =back
                   7171: 
                   7172: =head2 Resource Subroutines
                   7173: 
                   7174: =over 4
1.191     harris41 7175: 
                   7176: =item *
                   7177: 
1.243     albertel 7178: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7179: 
                   7180: =item *
                   7181: 
1.243     albertel 7182: repcopy($filename) : subscribes to the requested file, and attempts to
                   7183: replicate from the owning library server, Might return
1.607     raeburn  7184: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7185: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7186: resource. Expects the local filesystem pathname
                   7187: (/home/httpd/html/res/....)
                   7188: 
                   7189: =back
                   7190: 
                   7191: =head2 Resource Information
                   7192: 
                   7193: =over 4
1.191     harris41 7194: 
                   7195: =item *
                   7196: 
1.243     albertel 7197: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7198: a vairety of different possible values, $varname should be a request
                   7199: string, and the other parameters can be used to specify who and what
                   7200: one is asking about.
                   7201: 
                   7202: Possible values for $varname are environment.lastname (or other item
                   7203: from the envirnment hash), user.name (or someother aspect about the
                   7204: user), resource.0.maxtries (or some other part and parameter of a
                   7205: resource)
1.204     albertel 7206: 
                   7207: =item *
                   7208: 
1.243     albertel 7209: directcondval($number) : get current value of a condition; reads from a state
                   7210: string
1.204     albertel 7211: 
                   7212: =item *
                   7213: 
1.243     albertel 7214: condval($condidx) : value of condition index based on state
1.204     albertel 7215: 
                   7216: =item *
                   7217: 
1.243     albertel 7218: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7219: resource's metadata, $what should be either a specific key, or either
                   7220: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7221: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7222: 
                   7223: this function automatically caches all requests
1.191     harris41 7224: 
                   7225: =item *
                   7226: 
1.243     albertel 7227: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7228: network of library servers; returns file handle of where SQL and regex results
                   7229: will be stored for query
1.191     harris41 7230: 
                   7231: =item *
                   7232: 
1.243     albertel 7233: symbread($filename) : return symbolic list entry (filename argument optional);
                   7234: returns the data handle
1.191     harris41 7235: 
                   7236: =item *
                   7237: 
1.243     albertel 7238: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7239: a possible symb for the URL in $thisfn, and if is an encryypted
                   7240: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7241: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7242: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7243: 
1.191     harris41 7244: 
                   7245: =item *
                   7246: 
1.243     albertel 7247: symbclean($symb) : removes versions numbers from a symb, returns the
                   7248: cleaned symb
1.191     harris41 7249: 
                   7250: =item *
                   7251: 
1.243     albertel 7252: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7253: course map, user must be in a course for it to work.
1.191     harris41 7254: 
                   7255: =item *
                   7256: 
1.243     albertel 7257: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7258: 
                   7259: =item *
                   7260: 
1.243     albertel 7261: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7262: a random seed, all arguments are optional, if they aren't sent it uses the
                   7263: environment to derive them. Note: if symb isn't sent and it can't get one
                   7264: from &symbread it will use the current time as its return value
1.191     harris41 7265: 
                   7266: =item *
                   7267: 
1.243     albertel 7268: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7269: unfakeable, receipt
1.191     harris41 7270: 
                   7271: =item *
                   7272: 
1.620     albertel 7273: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7274: 
                   7275: =item *
                   7276: 
1.243     albertel 7277: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7278: 
                   7279: =item *
                   7280: 
1.243     albertel 7281: 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 7282: 
                   7283: =item *
                   7284: 
1.243     albertel 7285: 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 7286: 
                   7287: =item *
                   7288: 
1.243     albertel 7289: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7290: 
                   7291: =item *
                   7292: 
1.243     albertel 7293: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7294: forcing spreadsheet to reevaluate the resource scores next time.
                   7295: 
                   7296: =back
                   7297: 
                   7298: =head2 Storing/Retreiving Data
                   7299: 
                   7300: =over 4
1.191     harris41 7301: 
                   7302: =item *
                   7303: 
1.243     albertel 7304: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7305: for this url; hashref needs to be given and should be a \%hashname; the
                   7306: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7307: be derived from the env
1.191     harris41 7308: 
                   7309: =item *
                   7310: 
1.243     albertel 7311: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7312: uses critical subroutine
1.191     harris41 7313: 
                   7314: =item *
                   7315: 
1.243     albertel 7316: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7317: all args are optional
1.191     harris41 7318: 
                   7319: =item *
                   7320: 
1.717     albertel 7321: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7322: dumps the complete (or key matching regexp) namespace into a hash
                   7323: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7324: normally &store()ed into
                   7325: 
                   7326: $range should be either an integer '100' (give me the first 100
                   7327:                                            matching records)
                   7328:               or be  two integers sperated by a - with no spaces
                   7329:                  '30-50' (give me the 30th through the 50th matching
                   7330:                           records)
                   7331: 
                   7332: 
                   7333: =item *
                   7334: 
                   7335: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7336: replaces a &store() version of data with a replacement set of data
                   7337: for a particular resource in a namespace passed in the $storehash hash 
                   7338: reference
                   7339: 
                   7340: =item *
                   7341: 
1.243     albertel 7342: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7343: works very similar to store/cstore, but all data is stored in a
                   7344: temporary location and can be reset using tmpreset, $storehash should
                   7345: be a hash reference, returns nothing on success
1.191     harris41 7346: 
                   7347: =item *
                   7348: 
1.243     albertel 7349: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7350: similar to restore, but all data is stored in a temporary location and
                   7351: can be reset using tmpreset. Returns a hash of values on success,
                   7352: error string otherwise.
1.191     harris41 7353: 
                   7354: =item *
                   7355: 
1.243     albertel 7356: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7357: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7358: 
                   7359: =item *
                   7360: 
1.243     albertel 7361: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7362: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7363: 
                   7364: =item *
                   7365: 
1.243     albertel 7366: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7367: namesp ($udom and $uname are optional)
1.191     harris41 7368: 
                   7369: =item *
                   7370: 
1.702     albertel 7371: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7372: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7373: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7374: 
1.702     albertel 7375: $range should be either an integer '100' (give me the first 100
                   7376:                                            matching records)
                   7377:               or be  two integers sperated by a - with no spaces
                   7378:                  '30-50' (give me the 30th through the 50th matching
                   7379:                           records)
1.449     matthew  7380: =item *
                   7381: 
                   7382: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7383: $store can be a scalar, an array reference, or if the amount to be 
                   7384: incremented is > 1, a hash reference.
                   7385: 
                   7386: ($udom and $uname are optional)
1.191     harris41 7387: 
                   7388: =item *
                   7389: 
1.243     albertel 7390: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7391: ($udom and $uname are optional)
1.191     harris41 7392: 
                   7393: =item *
                   7394: 
1.243     albertel 7395: cput($namespace,$storehash,$udom,$uname) : critical put
                   7396: ($udom and $uname are optional)
1.191     harris41 7397: 
                   7398: =item *
                   7399: 
1.243     albertel 7400: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7401: reference filled in from namesp (encrypts the return communication)
                   7402: ($udom and $uname are optional)
1.191     harris41 7403: 
                   7404: =item *
                   7405: 
1.243     albertel 7406: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7407: critical subroutine
                   7408: 
                   7409: =back
                   7410: 
                   7411: =head2 Network Status Functions
                   7412: 
                   7413: =over 4
1.191     harris41 7414: 
                   7415: =item *
                   7416: 
                   7417: dirlist($uri) : return directory list based on URI
                   7418: 
                   7419: =item *
                   7420: 
1.243     albertel 7421: spareserver() : find server with least workload from spare.tab
                   7422: 
                   7423: =back
                   7424: 
                   7425: =head2 Apache Request
                   7426: 
                   7427: =over 4
1.191     harris41 7428: 
                   7429: =item *
                   7430: 
1.243     albertel 7431: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7432: localhost, posts hash
                   7433: 
                   7434: =back
                   7435: 
                   7436: =head2 Data to String to Data
                   7437: 
                   7438: =over 4
1.191     harris41 7439: 
                   7440: =item *
                   7441: 
1.243     albertel 7442: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7443: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7444: 
                   7445: =item *
                   7446: 
1.243     albertel 7447: hashref2str($hashref) : convert a hashref into a string complete with
                   7448: escaping and '=' and '&' separators, supports elements that are
                   7449: arrayrefs and hashrefs
1.191     harris41 7450: 
                   7451: =item *
                   7452: 
1.243     albertel 7453: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7454: with escaping and '&' separators, supports elements that are arrayrefs
                   7455: and hashrefs
1.191     harris41 7456: 
                   7457: =item *
                   7458: 
1.243     albertel 7459: str2hash($string) : convert string to hash using unescaping and
                   7460: splitting on '=' and '&', supports elements that are arrayrefs and
                   7461: hashrefs
1.191     harris41 7462: 
                   7463: =item *
                   7464: 
1.243     albertel 7465: str2array($string) : convert string to hash using unescaping and
                   7466: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7467: 
                   7468: =back
                   7469: 
                   7470: =head2 Logging Routines
                   7471: 
                   7472: =over 4
                   7473: 
                   7474: These routines allow one to make log messages in the lonnet.log and
                   7475: lonnet.perm logfiles.
1.191     harris41 7476: 
                   7477: =item *
                   7478: 
1.243     albertel 7479: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 7480: 
                   7481: =item *
                   7482: 
1.243     albertel 7483: logthis() : append message to the normal lonnet.log file, it gets
                   7484: preiodically rolled over and deleted.
1.191     harris41 7485: 
                   7486: =item *
                   7487: 
1.243     albertel 7488: logperm() : append a permanent message to lonnet.perm.log, this log
                   7489: file never gets deleted by any automated portion of the system, only
                   7490: messages of critical importance should go in here.
                   7491: 
                   7492: =back
                   7493: 
                   7494: =head2 General File Helper Routines
                   7495: 
                   7496: =over 4
1.191     harris41 7497: 
                   7498: =item *
                   7499: 
1.481     raeburn  7500: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7501: (a) files in /uploaded
                   7502:   (i) If a local copy of the file exists - 
                   7503:       compares modification date of local copy with last-modified date for 
                   7504:       definitive version stored on home server for course. If local copy is 
                   7505:       stale, requests a new version from the home server and stores it. 
                   7506:       If the original has been removed from the home server, then local copy 
                   7507:       is unlinked.
                   7508:   (ii) If local copy does not exist -
                   7509:       requests the file from the home server and stores it. 
                   7510:   
                   7511:   If $caller is 'uploadrep':  
                   7512:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7513:     for request for files originally uploaded via DOCS. 
                   7514:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7515:   
                   7516:   Otherwise:
                   7517:      This indicates a call from the content generation phase of the request.
                   7518:      -  returns the entire contents of the file or -1.
                   7519:      
                   7520: (b) files in /res
                   7521:    - returns the entire contents of a file or -1; 
                   7522:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7523: 
1.712     albertel 7524: 
                   7525: =item *
                   7526: 
                   7527: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   7528:                   reference
                   7529: 
                   7530: returns either a stat() list of data about the file or an empty list
                   7531: if the file doesn't exist or couldn't find out about it (connection
                   7532: problems or user unknown)
                   7533: 
1.191     harris41 7534: =item *
                   7535: 
1.243     albertel 7536: filelocation($dir,$file) : returns file system location of a file
                   7537: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7538: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7539: and a file of ../bob will become /a/bob)
1.191     harris41 7540: 
                   7541: =item *
                   7542: 
                   7543: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7544: filelocation except for hrefs
                   7545: 
                   7546: =item *
                   7547: 
                   7548: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7549: 
1.243     albertel 7550: =back
                   7551: 
1.608     albertel 7552: =head2 Usererfile file routines (/uploaded*)
                   7553: 
                   7554: =over 4
                   7555: 
                   7556: =item *
                   7557: 
                   7558: userfileupload(): main rotine for putting a file in a user or course's
                   7559:                   filespace, arguments are,
                   7560: 
1.620     albertel 7561:  formname - required - this is the name of the element in $env where the
1.608     albertel 7562:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7563:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7564:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7565:  coursedoc - if true, store the file in the course of the active role
                   7566:              of the current user
                   7567:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7568:          if undefined, it will be placed in "unknown"
                   7569: 
                   7570:  (This routine calls clean_filename() to remove any dangerous
                   7571:  characters from the filename, and then calls finuserfileupload() to
                   7572:  complete the transaction)
                   7573: 
                   7574:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7575:  and /adm/notfound.html if unsuccessful
                   7576: 
                   7577: =item *
                   7578: 
                   7579: clean_filename(): routine for cleaing a filename up for storage in
                   7580:                  userfile space, argument is:
                   7581: 
                   7582:  filename - proposed filename
                   7583: 
                   7584: returns: the new clean filename
                   7585: 
                   7586: =item *
                   7587: 
                   7588: finishuserfileupload(): routine that creaes and sends the file to
                   7589: userspace, probably shouldn't be called directly
                   7590: 
                   7591:   docuname: username or courseid of destination for the file
                   7592:   docudom: domain of user/course of destination for the file
                   7593:   formname: same as for userfileupload()
                   7594:   fname: filename (inculding subdirectories) for the file
                   7595: 
                   7596:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7597:  and /adm/notfound.html if unsuccessful
                   7598: 
                   7599: =item *
                   7600: 
                   7601: renameuserfile(): renames an existing userfile to a new name
                   7602: 
                   7603:   Args:
                   7604:    docuname: username or courseid of destination for the file
                   7605:    docudom: domain of user/course of destination for the file
                   7606:    old: current file name (including any subdirs under userfiles)
                   7607:    new: desired file name (including any subdirs under userfiles)
                   7608: 
                   7609: =item *
                   7610: 
                   7611: mkdiruserfile(): creates a directory is a userfiles dir
                   7612: 
                   7613:   Args:
                   7614:    docuname: username or courseid of destination for the file
                   7615:    docudom: domain of user/course of destination for the file
                   7616:    dir: dir to create (including any subdirs under userfiles)
                   7617: 
                   7618: =item *
                   7619: 
                   7620: removeuserfile(): removes a file that exists in userfiles
                   7621: 
                   7622:   Args:
                   7623:    docuname: username or courseid of destination for the file
                   7624:    docudom: domain of user/course of destination for the file
                   7625:    fname: filname to delete (including any subdirs under userfiles)
                   7626: 
                   7627: =item *
                   7628: 
                   7629: removeuploadedurl(): convience function for removeuserfile()
                   7630: 
                   7631:   Args:
                   7632:    url:  a full /uploaded/... url to delete
                   7633: 
                   7634: =back
                   7635: 
1.243     albertel 7636: =head2 HTTP Helper Routines
                   7637: 
                   7638: =over 4
                   7639: 
1.191     harris41 7640: =item *
                   7641: 
                   7642: escape() : unpack non-word characters into CGI-compatible hex codes
                   7643: 
                   7644: =item *
                   7645: 
                   7646: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   7647: 
1.243     albertel 7648: =back
                   7649: 
                   7650: =head1 PRIVATE SUBROUTINES
                   7651: 
                   7652: =head2 Underlying communication routines (Shouldn't call)
                   7653: 
                   7654: =over 4
                   7655: 
                   7656: =item *
                   7657: 
                   7658: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   7659: 
                   7660: =item *
                   7661: 
                   7662: reply() : uses subreply to send a message to remote machine, logs all failures
                   7663: 
                   7664: =item *
                   7665: 
                   7666: critical() : passes a critical message to another server; if cannot
                   7667: get through then place message in connection buffer directory and
                   7668: returns con_delayed, if incapable of saving message, returns
                   7669: con_failed
                   7670: 
                   7671: =item *
                   7672: 
                   7673: reconlonc() : tries to reconnect lonc client processes.
                   7674: 
                   7675: =back
                   7676: 
                   7677: =head2 Resource Access Logging
                   7678: 
                   7679: =over 4
                   7680: 
                   7681: =item *
                   7682: 
                   7683: flushcourselogs() : flush (save) buffer logs and access logs
                   7684: 
                   7685: =item *
                   7686: 
                   7687: courselog($what) : save message for course in hash
                   7688: 
                   7689: =item *
                   7690: 
                   7691: courseacclog($what) : save message for course using &courselog().  Perform
                   7692: special processing for specific resource types (problems, exams, quizzes, etc).
                   7693: 
1.191     harris41 7694: =item *
                   7695: 
                   7696: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   7697: as a PerlChildExitHandler
1.243     albertel 7698: 
                   7699: =back
                   7700: 
                   7701: =head2 Other
                   7702: 
                   7703: =over 4
                   7704: 
                   7705: =item *
                   7706: 
                   7707: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 7708: 
                   7709: =back
                   7710: 
                   7711: =cut

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