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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.731   ! albertel    4: # $Id: lonnet.pm,v 1.730 2006/04/18 20:36:00 www 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.731   ! albertel  191:     &Apache::lonnet::logthis("$cmd");
1.65      www       192:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  193:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       194:                 " $cmd to $server returned $answer</font>");
                    195:     }
1.1       albertel  196:     return $answer;
                    197: }
                    198: 
                    199: # ----------------------------------------------------------- Send USR1 to lonc
                    200: 
                    201: sub reconlonc {
                    202:     my $peerfile=shift;
                    203:     &logthis("Trying to reconnect for $peerfile");
                    204:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  205:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  206: 	my $loncpid=<$fh>;
                    207:         chomp($loncpid);
                    208:         if (kill 0 => $loncpid) {
                    209: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    210:             kill USR1 => $loncpid;
                    211:             sleep 1;
                    212:             if (-e "$peerfile") { return; }
                    213:             &logthis("$peerfile still not there, give it another try");
                    214:             sleep 5;
                    215:             if (-e "$peerfile") { return; }
1.12      www       216:             &logthis(
1.672     albertel  217:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  218:         } else {
1.12      www       219: 	    &logthis(
1.672     albertel  220:                "<font color=\"blue\">WARNING:".
1.12      www       221:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  222:         }
                    223:     } else {
1.672     albertel  224:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  225:     }
                    226: }
                    227: 
                    228: # ------------------------------------------------------ Critical communication
1.12      www       229: 
1.1       albertel  230: sub critical {
                    231:     my ($cmd,$server)=@_;
1.89      www       232:     unless ($hostname{$server}) {
1.672     albertel  233:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       234:                " Critical message to unknown server ($server)</font>");
                    235:         return 'no_such_host';
                    236:     }
1.1       albertel  237:     my $answer=reply($cmd,$server);
                    238:     if ($answer eq 'con_lost') {
                    239: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  240: 	my $answer=reply($cmd,$server);
1.1       albertel  241:         if ($answer eq 'con_lost') {
                    242:             my $now=time;
                    243:             my $middlename=$cmd;
1.5       www       244:             $middlename=substr($middlename,0,16);
1.1       albertel  245:             $middlename=~s/\W//g;
                    246:             my $dfilename=
1.305     www       247:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    248:             $dumpcount++;
1.1       albertel  249:             {
1.448     albertel  250: 		my $dfh;
                    251: 		if (open($dfh,">$dfilename")) {
                    252: 		    print $dfh "$cmd\n"; 
                    253: 		    close($dfh);
                    254: 		}
1.1       albertel  255:             }
                    256:             sleep 2;
                    257:             my $wcmd='';
                    258:             {
1.448     albertel  259: 		my $dfh;
                    260: 		if (open($dfh,"<$dfilename")) {
                    261: 		    $wcmd=<$dfh>; 
                    262: 		    close($dfh);
                    263: 		}
1.1       albertel  264:             }
                    265:             chomp($wcmd);
1.7       www       266:             if ($wcmd eq $cmd) {
1.672     albertel  267: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       268:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  269:                 &logperm("D:$server:$cmd");
                    270: 	        return 'con_delayed';
                    271:             } else {
1.672     albertel  272:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       273:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  274:                 &logperm("F:$server:$cmd");
                    275:                 return 'con_failed';
                    276:             }
                    277:         }
                    278:     }
                    279:     return $answer;
1.405     albertel  280: }
                    281: 
1.374     www       282: # ------------------------------------------- Transfer profile into environment
                    283: 
                    284: sub transfer_profile_to_env {
                    285:     my ($lonidsdir,$handle)=@_;
1.720     albertel  286:     if (!defined($lonidsdir)) {
                    287: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    288:     }
                    289:     if (!defined($handle)) {
                    290:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    291:     }
                    292: 
1.374     www       293:     my @profile;
                    294:     {
1.448     albertel  295: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       296: 	flock($idf,LOCK_SH);
                    297: 	@profile=<$idf>;
1.448     albertel  298: 	close($idf);
1.374     www       299:     }
                    300:     my $envi;
1.433     matthew   301:     my %Remove;
1.374     www       302:     for ($envi=0;$envi<=$#profile;$envi++) {
                    303: 	chomp($profile[$envi]);
1.690     albertel  304: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  305: 	$envname=&unescape($envname);
                    306: 	$envvalue=&unescape($envvalue);
1.619     albertel  307: 	$env{$envname} = $envvalue;
1.433     matthew   308:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    309:             if ($time < time-300) {
                    310:                 $Remove{$key}++;
                    311:             }
                    312:         }
                    313:     }
1.619     albertel  314:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   315:     foreach my $expired_key (keys(%Remove)) {
                    316:         &delenv($expired_key);
1.374     www       317:     }
1.1       albertel  318: }
                    319: 
1.5       www       320: # ---------------------------------------------------------- Append Environment
                    321: 
                    322: sub appenv {
1.6       www       323:     my %newenv=@_;
1.692     albertel  324:     foreach my $key (keys(%newenv)) {
                    325: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  326:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  327:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       328:                 .'</font>');
1.692     albertel  329: 	    delete($newenv{$key});
1.35      www       330:         } else {
1.692     albertel  331:             $env{$key}=$newenv{$key};
1.35      www       332:         }
1.191     harris41  333:     }
1.95      www       334: 
                    335:     my $lockfh;
1.620     albertel  336:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  337: 	return 'error: '.$!;
1.95      www       338:     }
                    339:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  340:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       341:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  342:          close($lockfh);
1.95      www       343:          return 'error: '.$!;
                    344:     }
                    345: 
1.6       www       346:     my @oldenv;
                    347:     {
1.448     albertel  348: 	my $fh;
1.620     albertel  349: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  350: 	    return 'error: '.$!;
                    351: 	}
                    352: 	@oldenv=<$fh>;
                    353: 	close($fh);
1.6       www       354:     }
                    355:     for (my $i=0; $i<=$#oldenv; $i++) {
                    356:         chomp($oldenv[$i]);
1.9       www       357:         if ($oldenv[$i] ne '') {
1.690     albertel  358: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.726     albertel  359: 	    $name=&unescape($name);
                    360: 	    $value=&unescape($value);
1.448     albertel  361: 	    unless (defined($newenv{$name})) {
                    362: 		$newenv{$name}=$value;
                    363: 	    }
1.9       www       364:         }
1.6       www       365:     }
                    366:     {
1.448     albertel  367: 	my $fh;
1.620     albertel  368: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  369: 	    return 'error';
                    370: 	}
                    371: 	my $newname;
                    372: 	foreach $newname (keys %newenv) {
1.726     albertel  373: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
1.448     albertel  374: 	}
                    375: 	close($fh);
1.56      www       376:     }
1.448     albertel  377: 	
                    378:     close($lockfh);
1.56      www       379:     return 'ok';
                    380: }
                    381: # ----------------------------------------------------- Delete from Environment
                    382: 
                    383: sub delenv {
                    384:     my $delthis=shift;
                    385:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  386:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       387:                 "Attempt to delete from environment ".$delthis);
                    388:         return 'error';
                    389:     }
                    390:     my @oldenv;
                    391:     {
1.448     albertel  392: 	my $fh;
1.620     albertel  393: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  394: 	    return 'error';
                    395: 	}
                    396: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  397: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  398: 		     'Could not obtain shared lock in delenv: '.$!);
                    399: 	    close($fh);
                    400: 	    return 'error: '.$!;
                    401: 	}
                    402: 	@oldenv=<$fh>;
                    403: 	close($fh);
1.56      www       404:     }
                    405:     {
1.448     albertel  406: 	my $fh;
1.620     albertel  407: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  408: 	    return 'error';
                    409: 	}
                    410: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  411: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  412: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    413: 	    close($fh);
                    414: 	    return 'error: '.$!;
                    415: 	}
1.692     albertel  416: 	foreach my $cur_key (@oldenv) {
1.726     albertel  417: 	    my $unescaped_cur_key = &unescape($cur_key);
                    418: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    419:                 my ($key) = split('=',$cur_key,2);
                    420: 		$key = &unescape($key);
1.619     albertel  421:                 delete($env{$key});
1.473     matthew   422:             } else {
1.692     albertel  423:                 print $fh $cur_key; 
1.473     matthew   424:             }
1.448     albertel  425: 	}
                    426: 	close($fh);
1.5       www       427:     }
                    428:     return 'ok';
1.369     albertel  429: }
                    430: 
                    431: # ------------------------------------------ Find out current server userload
                    432: # there is a copy in lond
                    433: sub userload {
                    434:     my $numusers=0;
                    435:     {
                    436: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    437: 	my $filename;
                    438: 	my $curtime=time;
                    439: 	while ($filename=readdir(LONIDS)) {
                    440: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  441: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  442: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  443: 	}
                    444: 	closedir(LONIDS);
                    445:     }
                    446:     my $userloadpercent=0;
                    447:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    448:     if ($maxuserload) {
1.371     albertel  449: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  450:     }
1.372     albertel  451:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  452:     return $userloadpercent;
1.283     www       453: }
                    454: 
                    455: # ------------------------------------------ Fight off request when overloaded
                    456: 
                    457: sub overloaderror {
                    458:     my ($r,$checkserver)=@_;
                    459:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    460:     my $loadavg;
                    461:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  462:        open(my $loadfile,'/proc/loadavg');
1.283     www       463:        $loadavg=<$loadfile>;
                    464:        $loadavg =~ s/\s.*//g;
1.285     matthew   465:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  466:        close($loadfile);
1.283     www       467:     } else {
                    468:        $loadavg=&reply('load',$checkserver);
                    469:     }
1.285     matthew   470:     my $overload=$loadavg-100;
1.283     www       471:     if ($overload>0) {
1.285     matthew   472: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       473:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       474:         return 413;
1.283     www       475:     }    
                    476:     return '';
1.5       www       477: }
1.1       albertel  478: 
                    479: # ------------------------------ Find server with least workload from spare.tab
1.11      www       480: 
1.1       albertel  481: sub spareserver {
1.670     albertel  482:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  483:     my $tryserver;
                    484:     my $spareserver='';
1.370     albertel  485:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    486:     my $lowestserver=$loadpercent > $userloadpercent?
                    487: 	             $loadpercent :  $userloadpercent;
1.670     albertel  488:     foreach $tryserver (keys(%spareid)) {
                    489: 	my $loadans=&reply('load',$tryserver);
                    490: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  491: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    492: 	    next; #didn't get a number from the server
                    493: 	}
                    494: 	my $answer;
                    495: 	if ($loadans =~ /\d/) {
                    496: 	    if ($userloadans =~ /\d/) {
                    497: 		#both are numbers, pick the bigger one
                    498: 		$answer=$loadans > $userloadans?
                    499: 		    $loadans :  $userloadans;
                    500: 	    } else {
                    501: 		$answer = $loadans;
                    502: 	    }
                    503: 	} else {
                    504: 	    $answer = $userloadans;
                    505: 	}
                    506: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  507: 	    if ($want_server_name) {
                    508: 		$spareserver=$tryserver;
                    509: 	    } else {
                    510: 		$spareserver="http://$hostname{$tryserver}";
                    511: 	    }
1.411     albertel  512: 	    $lowestserver=$answer;
                    513: 	}
1.370     albertel  514:     }
1.1       albertel  515:     return $spareserver;
1.202     matthew   516: }
                    517: 
                    518: # --------------------------------------------- Try to change a user's password
                    519: 
                    520: sub changepass {
                    521:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    522:     $currentpass = &escape($currentpass);
                    523:     $newpass     = &escape($newpass);
                    524:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    525: 		       $server);
                    526:     if (! $answer) {
                    527: 	&logthis("No reply on password change request to $server ".
                    528: 		 "by $uname in domain $udom.");
                    529:     } elsif ($answer =~ "^ok") {
                    530:         &logthis("$uname in $udom successfully changed their password ".
                    531: 		 "on $server.");
                    532:     } elsif ($answer =~ "^pwchange_failure") {
                    533: 	&logthis("$uname in $udom was unable to change their password ".
                    534: 		 "on $server.  The action was blocked by either lcpasswd ".
                    535: 		 "or pwchange");
                    536:     } elsif ($answer =~ "^non_authorized") {
                    537:         &logthis("$uname in $udom did not get their password correct when ".
                    538: 		 "attempting to change it on $server.");
                    539:     } elsif ($answer =~ "^auth_mode_error") {
                    540:         &logthis("$uname in $udom attempted to change their password despite ".
                    541: 		 "not being locally or internally authenticated on $server.");
                    542:     } elsif ($answer =~ "^unknown_user") {
                    543:         &logthis("$uname in $udom attempted to change their password ".
                    544: 		 "on $server but were unable to because $server is not ".
                    545: 		 "their home server.");
                    546:     } elsif ($answer =~ "^refused") {
                    547: 	&logthis("$server refused to change $uname in $udom password because ".
                    548: 		 "it was sent an unencrypted request to change the password.");
                    549:     }
                    550:     return $answer;
1.1       albertel  551: }
                    552: 
1.169     harris41  553: # ----------------------- Try to determine user's current authentication scheme
                    554: 
                    555: sub queryauthenticate {
                    556:     my ($uname,$udom)=@_;
1.456     albertel  557:     my $uhome=&homeserver($uname,$udom);
                    558:     if (!$uhome) {
                    559: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    560: 	return 'no_host';
                    561:     }
                    562:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    563:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    564: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  565:     }
1.456     albertel  566:     return $answer;
1.169     harris41  567: }
                    568: 
1.1       albertel  569: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       570: 
1.1       albertel  571: sub authenticate {
                    572:     my ($uname,$upass,$udom)=@_;
1.12      www       573:     $upass=escape($upass);
1.199     www       574:     $uname=~s/\W//g;
1.471     albertel  575:     my $uhome=&homeserver($uname,$udom);
                    576:     if (!$uhome) {
                    577: 	&logthis("User $uname at $udom is unknown in authenticate");
                    578: 	return 'no_host';
1.1       albertel  579:     }
1.471     albertel  580:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    581:     if ($answer eq 'authorized') {
                    582: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    583: 	return $uhome; 
                    584:     }
                    585:     if ($answer eq 'non_authorized') {
                    586: 	&logthis("User $uname at $udom rejected by $uhome");
                    587: 	return 'no_host'; 
1.9       www       588:     }
1.471     albertel  589:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  590:     return 'no_host';
                    591: }
                    592: 
                    593: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       594: 
1.599     albertel  595: my %homecache;
1.1       albertel  596: sub homeserver {
1.230     stredwic  597:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  598:     my $index="$uname:$udom";
1.426     albertel  599: 
1.599     albertel  600:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  601:     my $tryserver;
                    602:     foreach $tryserver (keys %libserv) {
1.230     stredwic  603:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  604: 		 exists($badServerCache{$tryserver}));
1.1       albertel  605: 	if ($hostdom{$tryserver} eq $udom) {
                    606:            my $answer=reply("home:$udom:$uname",$tryserver);
                    607:            if ($answer eq 'found') { 
1.599     albertel  608: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  609:            } elsif ($answer eq 'no_host') {
                    610: 	       $badServerCache{$tryserver}=1;
1.221     matthew   611:            }
1.1       albertel  612:        }
                    613:     }    
                    614:     return 'no_host';
1.70      www       615: }
                    616: 
                    617: # ------------------------------------- Find the usernames behind a list of IDs
                    618: 
                    619: sub idget {
                    620:     my ($udom,@ids)=@_;
                    621:     my %returnhash=();
                    622:     
                    623:     my $tryserver;
                    624:     foreach $tryserver (keys %libserv) {
                    625:        if ($hostdom{$tryserver} eq $udom) {
                    626: 	  my $idlist=join('&',@ids);
                    627:           $idlist=~tr/A-Z/a-z/; 
                    628: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    629:           my @answer=();
1.76      www       630:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       631: 	      @answer=split(/\&/,$reply);
                    632:           }                    ;
                    633:           my $i;
                    634:           for ($i=0;$i<=$#ids;$i++) {
                    635:               if ($answer[$i]) {
                    636: 		  $returnhash{$ids[$i]}=$answer[$i];
                    637:               } 
                    638:           }
                    639:        }
                    640:     }    
                    641:     return %returnhash;
                    642: }
                    643: 
                    644: # ------------------------------------- Find the IDs behind a list of usernames
                    645: 
                    646: sub idrget {
                    647:     my ($udom,@unames)=@_;
                    648:     my %returnhash=();
1.191     harris41  649:     foreach (@unames) {
1.70      www       650:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  651:     }
1.70      www       652:     return %returnhash;
                    653: }
                    654: 
                    655: # ------------------------------- Store away a list of names and associated IDs
                    656: 
                    657: sub idput {
                    658:     my ($udom,%ids)=@_;
                    659:     my %servers=();
1.191     harris41  660:     foreach (keys %ids) {
1.487     albertel  661: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       662:         my $uhom=&homeserver($_,$udom);
                    663:         if ($uhom ne 'no_host') {
                    664:             my $id=&escape($ids{$_});
                    665:             $id=~tr/A-Z/a-z/;
                    666:             my $unam=&escape($_);
                    667: 	    if ($servers{$uhom}) {
                    668: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    669:             } else {
                    670:                 $servers{$uhom}=$id.'='.$unam;
                    671:             }
                    672:         }
1.191     harris41  673:     }
                    674:     foreach (keys %servers) {
1.70      www       675:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  676:     }
1.344     www       677: }
                    678: 
                    679: # --------------------------------------------------- Assign a key to a student
                    680: 
                    681: sub assign_access_key {
1.364     www       682: #
                    683: # a valid key looks like uname:udom#comments
                    684: # comments are being appended
                    685: #
1.498     www       686:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    687:     $kdom=
1.620     albertel  688:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       689:     $knum=
1.620     albertel  690:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       691:     $cdom=
1.620     albertel  692:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       693:     $cnum=
1.620     albertel  694:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    695:     $udom=$env{'user.name'} unless (defined($udom));
                    696:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       697:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       698:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  699:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       700:                                                   # assigned to this person
                    701:                                                   # - this should not happen,
1.345     www       702:                                                   # unless something went wrong
                    703:                                                   # the first time around
                    704: # ready to assign
1.364     www       705:         $logentry=$1.'; '.$logentry;
1.496     www       706:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       707:                                                  $kdom,$knum) eq 'ok') {
1.345     www       708: # key now belongs to user
1.346     www       709: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       710:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    711:                 &appenv('environment.'.$envkey => $ckey);
                    712:                 return 'ok';
                    713:             } else {
                    714:                 return 
                    715:   'error: Count not permanently assign key, will need to be re-entered later.';
                    716: 	    }
                    717:         } else {
                    718:             return 'error: Could not assign key, try again later.';
                    719:         }
1.364     www       720:     } elsif (!$existing{$ckey}) {
1.345     www       721: # the key does not exist
                    722: 	return 'error: The key does not exist';
                    723:     } else {
                    724: # the key is somebody else's
                    725: 	return 'error: The key is already in use';
                    726:     }
1.344     www       727: }
                    728: 
1.364     www       729: # ------------------------------------------ put an additional comment on a key
                    730: 
                    731: sub comment_access_key {
                    732: #
                    733: # a valid key looks like uname:udom#comments
                    734: # comments are being appended
                    735: #
                    736:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    737:     $cdom=
1.620     albertel  738:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       739:     $cnum=
1.620     albertel  740:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       741:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    742:     if ($existing{$ckey}) {
                    743:         $existing{$ckey}.='; '.$logentry;
                    744: # ready to assign
1.367     www       745:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       746:                                                  $cdom,$cnum) eq 'ok') {
                    747: 	    return 'ok';
                    748:         } else {
                    749: 	    return 'error: Count not store comment.';
                    750:         }
                    751:     } else {
                    752: # the key does not exist
                    753: 	return 'error: The key does not exist';
                    754:     }
                    755: }
                    756: 
1.344     www       757: # ------------------------------------------------------ Generate a set of keys
                    758: 
                    759: sub generate_access_keys {
1.364     www       760:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       761:     $cdom=
1.620     albertel  762:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       763:     $cnum=
1.620     albertel  764:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       765:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       766:     unless (($cdom) && ($cnum)) { return 0; }
                    767:     if ($number>10000) { return 0; }
                    768:     sleep(2); # make sure don't get same seed twice
                    769:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    770:     my $total=0;
                    771:     for (my $i=1;$i<=$number;$i++) {
                    772:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    773:                   sprintf("%lx",int(100000*rand)).'-'.
                    774:                   sprintf("%lx",int(100000*rand));
                    775:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    776:        $newkey=~s/0/h/g; # and also 0 and O
                    777:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    778:        if ($existing{$newkey}) {
                    779:            $i--;
                    780:        } else {
1.364     www       781: 	  if (&put('accesskeys',
                    782:               { $newkey => '# generated '.localtime().
1.620     albertel  783:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       784:                            '; '.$logentry },
                    785: 		   $cdom,$cnum) eq 'ok') {
1.344     www       786:               $total++;
                    787: 	  }
                    788:        }
                    789:     }
1.620     albertel  790:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       791:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    792:     return $total;
                    793: }
                    794: 
                    795: # ------------------------------------------------------- Validate an accesskey
                    796: 
                    797: sub validate_access_key {
                    798:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    799:     $cdom=
1.620     albertel  800:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       801:     $cnum=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    803:     $udom=$env{'user.domain'} unless (defined($udom));
                    804:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       805:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  806:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       807: }
                    808: 
                    809: # ------------------------------------- Find the section of student in a course
1.652     albertel  810: sub devalidate_getsection_cache {
                    811:     my ($udom,$unam,$courseid)=@_;
                    812:     $courseid=~s/\_/\//g;
                    813:     $courseid=~s/^(\w)/\/$1/;
                    814:     my $hashid="$udom:$unam:$courseid";
                    815:     &devalidate_cache_new('getsection',$hashid);
                    816: }
1.298     matthew   817: 
                    818: sub getsection {
                    819:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  820:     my $cachetime=1800;
1.298     matthew   821:     $courseid=~s/\_/\//g;
                    822:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  823: 
                    824:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  825:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  826:     if (defined($cached)) { return $result; }
                    827: 
1.298     matthew   828:     my %Pending; 
                    829:     my %Expired;
                    830:     #
                    831:     # Each role can either have not started yet (pending), be active, 
                    832:     #    or have expired.
                    833:     #
                    834:     # If there is an active role, we are done.
                    835:     #
                    836:     # If there is more than one role which has not started yet, 
                    837:     #     choose the one which will start sooner
                    838:     # If there is one role which has not started yet, return it.
                    839:     #
                    840:     # If there is more than one expired role, choose the one which ended last.
                    841:     # If there is a role which has expired, return it.
                    842:     #
                    843:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    844:                         &homeserver($unam,$udom)))) {
                    845:         my ($key,$value)=split(/\=/,$_);
                    846:         $key=&unescape($key);
1.479     albertel  847:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   848:         my $section=$1;
                    849:         if ($key eq $courseid.'_st') { $section=''; }
                    850:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    851:         my $now=time;
1.548     albertel  852:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   853:             $Expired{$end}=$section;
                    854:             next;
                    855:         }
1.548     albertel  856:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   857:             $Pending{$start}=$section;
                    858:             next;
                    859:         }
1.599     albertel  860:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   861:     }
                    862:     #
                    863:     # Presumedly there will be few matching roles from the above
                    864:     # loop and the sorting time will be negligible.
                    865:     if (scalar(keys(%Pending))) {
                    866:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  867:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   868:     } 
                    869:     if (scalar(keys(%Expired))) {
                    870:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    871:         my $time = pop(@sorted);
1.599     albertel  872:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   873:     }
1.599     albertel  874:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   875: }
1.70      www       876: 
1.599     albertel  877: sub save_cache {
                    878:     &purge_remembered();
1.722     albertel  879:     #&Apache::loncommon::validate_page();
1.620     albertel  880:     undef(%env);
1.599     albertel  881: }
1.452     albertel  882: 
1.599     albertel  883: my $to_remember=-1;
                    884: my %remembered;
                    885: my %accessed;
                    886: my $kicks=0;
                    887: my $hits=0;
                    888: sub devalidate_cache_new {
                    889:     my ($name,$id,$debug) = @_;
                    890:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    891:     $id=&escape($name.':'.$id);
                    892:     $memcache->delete($id);
                    893:     delete($remembered{$id});
                    894:     delete($accessed{$id});
                    895: }
                    896: 
                    897: sub is_cached_new {
                    898:     my ($name,$id,$debug) = @_;
                    899:     $id=&escape($name.':'.$id);
                    900:     if (exists($remembered{$id})) {
                    901: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    902: 	$accessed{$id}=[&gettimeofday()];
                    903: 	$hits++;
                    904: 	return ($remembered{$id},1);
                    905:     }
                    906:     my $value = $memcache->get($id);
                    907:     if (!(defined($value))) {
                    908: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  909: 	return (undef,undef);
1.416     albertel  910:     }
1.599     albertel  911:     if ($value eq '__undef__') {
                    912: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    913: 	$value=undef;
                    914:     }
                    915:     &make_room($id,$value,$debug);
                    916:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    917:     return ($value,1);
                    918: }
                    919: 
                    920: sub do_cache_new {
                    921:     my ($name,$id,$value,$time,$debug) = @_;
                    922:     $id=&escape($name.':'.$id);
                    923:     my $setvalue=$value;
                    924:     if (!defined($setvalue)) {
                    925: 	$setvalue='__undef__';
                    926:     }
1.623     albertel  927:     if (!defined($time) ) {
                    928: 	$time=600;
                    929:     }
1.599     albertel  930:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  931:     $memcache->set($id,$setvalue,$time);
                    932:     # need to make a copy of $value
                    933:     #&make_room($id,$value,$debug);
1.599     albertel  934:     return $value;
                    935: }
                    936: 
                    937: sub make_room {
                    938:     my ($id,$value,$debug)=@_;
                    939:     $remembered{$id}=$value;
                    940:     if ($to_remember<0) { return; }
                    941:     $accessed{$id}=[&gettimeofday()];
                    942:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    943:     my $to_kick;
                    944:     my $max_time=0;
                    945:     foreach my $other (keys(%accessed)) {
                    946: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    947: 	    $to_kick=$other;
                    948: 	    $max_time=&tv_interval($accessed{$other});
                    949: 	}
                    950:     }
                    951:     delete($remembered{$to_kick});
                    952:     delete($accessed{$to_kick});
                    953:     $kicks++;
                    954:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  955:     return;
                    956: }
                    957: 
1.599     albertel  958: sub purge_remembered {
1.604     albertel  959:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    960:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  961:     undef(%remembered);
                    962:     undef(%accessed);
1.428     albertel  963: }
1.70      www       964: # ------------------------------------- Read an entry from a user's environment
                    965: 
                    966: sub userenvironment {
                    967:     my ($udom,$unam,@what)=@_;
                    968:     my %returnhash=();
                    969:     my @answer=split(/\&/,
                    970:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    971:                       &homeserver($unam,$udom)));
                    972:     my $i;
                    973:     for ($i=0;$i<=$#what;$i++) {
                    974: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    975:     }
                    976:     return %returnhash;
1.1       albertel  977: }
                    978: 
1.617     albertel  979: # ---------------------------------------------------------- Get a studentphoto
                    980: sub studentphoto {
                    981:     my ($udom,$unam,$ext) = @_;
                    982:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   983:     if (defined($env{'request.course.id'})) {
1.708     raeburn   984:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   985:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    986:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    987:             } else {
                    988:                 my ($result,$perm_reqd)=
1.707     albertel  989: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   990:                 if ($result eq 'ok') {
                    991:                     if (!($perm_reqd eq 'yes')) {
                    992:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    993:                     }
                    994:                 }
                    995:             }
                    996:         }
                    997:     } else {
                    998:         my ($result,$perm_reqd) = 
1.707     albertel  999: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1000:         if ($result eq 'ok') {
                   1001:             if (!($perm_reqd eq 'yes')) {
                   1002:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1003:             }
                   1004:         }
                   1005:     }
                   1006:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1007: }
                   1008: 
                   1009: sub retrievestudentphoto {
                   1010:     my ($udom,$unam,$ext,$type) = @_;
                   1011:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1012:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1013:     if ($ret eq 'ok') {
                   1014:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1015:         if ($type eq 'thumbnail') {
                   1016:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1017:         }
                   1018:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1019:         return $tokenurl;
                   1020:     } else {
                   1021:         if ($type eq 'thumbnail') {
                   1022:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1023:         } else { 
                   1024:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1025:         }
1.617     albertel 1026:     }
                   1027: }
                   1028: 
1.263     www      1029: # -------------------------------------------------------------------- New chat
                   1030: 
                   1031: sub chatsend {
1.724     raeburn  1032:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1033:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1034:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1035:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1036:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1037: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1038: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1039: }
                   1040: 
                   1041: # ------------------------------------------ Find current version of a resource
                   1042: 
                   1043: sub getversion {
                   1044:     my $fname=&clutter(shift);
                   1045:     unless ($fname=~/^\/res\//) { return -1; }
                   1046:     return &currentversion(&filelocation('',$fname));
                   1047: }
                   1048: 
                   1049: sub currentversion {
                   1050:     my $fname=shift;
1.599     albertel 1051:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1052:     if (defined($cached)) { return $result; }
1.292     www      1053:     my $author=$fname;
                   1054:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1055:     my ($udom,$uname)=split(/\//,$author);
                   1056:     my $home=homeserver($uname,$udom);
                   1057:     if ($home eq 'no_host') { 
                   1058:         return -1; 
                   1059:     }
                   1060:     my $answer=reply("currentversion:$fname",$home);
                   1061:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1062: 	return -1;
                   1063:     }
1.599     albertel 1064:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1065: }
                   1066: 
1.1       albertel 1067: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1068: 
1.1       albertel 1069: sub subscribe {
                   1070:     my $fname=shift;
1.312     www      1071:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1072:     $fname=~s/[\n\r]//g;
1.1       albertel 1073:     my $author=$fname;
                   1074:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1075:     my ($udom,$uname)=split(/\//,$author);
                   1076:     my $home=homeserver($uname,$udom);
1.335     albertel 1077:     if ($home eq 'no_host') {
                   1078:         return 'not_found';
1.1       albertel 1079:     }
                   1080:     my $answer=reply("sub:$fname",$home);
1.64      www      1081:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1082: 	$answer.=' by '.$home;
                   1083:     }
1.1       albertel 1084:     return $answer;
                   1085: }
                   1086:     
1.8       www      1087: # -------------------------------------------------------------- Replicate file
                   1088: 
                   1089: sub repcopy {
                   1090:     my $filename=shift;
1.23      www      1091:     $filename=~s/\/+/\//g;
1.607     raeburn  1092:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1093:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1094:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1095: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1096: 	return &repcopy_userfile($filename);
                   1097:     }
1.532     albertel 1098:     $filename=~s/[\n\r]//g;
1.8       www      1099:     my $transname="$filename.in.transfer";
1.607     raeburn  1100:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1101:     my $remoteurl=subscribe($filename);
1.64      www      1102:     if ($remoteurl =~ /^con_lost by/) {
                   1103: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1104:            return 'unavailable';
1.8       www      1105:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1106: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1107: 	   return 'not_found';
1.64      www      1108:     } elsif ($remoteurl =~ /^rejected by/) {
                   1109: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1110:            return 'forbidden';
1.20      www      1111:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1112:            return 'ok';
1.8       www      1113:     } else {
1.290     www      1114:         my $author=$filename;
                   1115:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1116:         my ($udom,$uname)=split(/\//,$author);
                   1117:         my $home=homeserver($uname,$udom);
                   1118:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1119:            my @parts=split(/\//,$filename);
                   1120:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1121:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1122:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1123: 	       return 'bad_request';
1.8       www      1124:            }
                   1125:            my $count;
                   1126:            for ($count=5;$count<$#parts;$count++) {
                   1127:                $path.="/$parts[$count]";
                   1128:                if ((-e $path)!=1) {
                   1129: 		   mkdir($path,0777);
                   1130:                }
                   1131:            }
                   1132:            my $ua=new LWP::UserAgent;
                   1133:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1134:            my $response=$ua->request($request,$transname);
                   1135:            if ($response->is_error()) {
                   1136: 	       unlink($transname);
                   1137:                my $message=$response->status_line;
1.672     albertel 1138:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1139:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1140:                return 'unavailable';
1.8       www      1141:            } else {
1.16      www      1142: 	       if ($remoteurl!~/\.meta$/) {
                   1143:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1144:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1145:                   if ($mresponse->is_error()) {
                   1146: 		      unlink($filename.'.meta');
                   1147:                       &logthis(
1.672     albertel 1148:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1149:                   }
                   1150: 	       }
1.8       www      1151:                rename($transname,$filename);
1.607     raeburn  1152:                return 'ok';
1.8       www      1153:            }
1.290     www      1154:        }
1.8       www      1155:     }
1.330     www      1156: }
                   1157: 
                   1158: # ------------------------------------------------ Get server side include body
                   1159: sub ssi_body {
1.381     albertel 1160:     my ($filelink,%form)=@_;
1.606     matthew  1161:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1162:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1163:     }
1.330     www      1164:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1165:                                      &ssi($filelink,%form));
1.565     albertel 1166:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1167:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1168:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1169:     return $output;
1.8       www      1170: }
                   1171: 
1.15      www      1172: # --------------------------------------------------------- Server Side Include
                   1173: 
                   1174: sub ssi {
                   1175: 
1.23      www      1176:     my ($fn,%form)=@_;
1.15      www      1177: 
                   1178:     my $ua=new LWP::UserAgent;
1.23      www      1179:     
                   1180:     my $request;
1.711     albertel 1181: 
                   1182:     $form{'no_update_last_known'}=1;
                   1183: 
1.23      www      1184:     if (%form) {
                   1185:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1186:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1187:     } else {
                   1188:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1189:     }
                   1190: 
1.15      www      1191:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1192:     my $response=$ua->request($request);
                   1193: 
1.324     www      1194:     return $response->content;
                   1195: }
                   1196: 
                   1197: sub externalssi {
                   1198:     my ($url)=@_;
                   1199:     my $ua=new LWP::UserAgent;
                   1200:     my $request=new HTTP::Request('GET',$url);
                   1201:     my $response=$ua->request($request);
1.15      www      1202:     return $response->content;
                   1203: }
1.254     www      1204: 
1.492     albertel 1205: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1206: 
                   1207: sub allowuploaded {
                   1208:     my ($srcurl,$url)=@_;
                   1209:     $url=&clutter(&declutter($url));
                   1210:     my $dir=$url;
                   1211:     $dir=~s/\/[^\/]+$//;
                   1212:     my %httpref=();
                   1213:     my $httpurl=&hreflocation('',$url);
                   1214:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1215:     &Apache::lonnet::appenv(%httpref);
1.254     www      1216: }
1.477     raeburn  1217: 
1.478     albertel 1218: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1219: # input: action, courseID, current domain, intended
1.637     raeburn  1220: #        path to file, source of file, instruction to parse file for objects,
                   1221: #        ref to hash for embedded objects,
                   1222: #        ref to hash for codebase of java objects.
                   1223: #
1.485     raeburn  1224: # output: url to file (if action was uploaddoc), 
                   1225: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1226: #
1.478     albertel 1227: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1228: # course.
1.477     raeburn  1229: #
1.478     albertel 1230: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1231: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1232: #          course's home server.
1.477     raeburn  1233: #
1.478     albertel 1234: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1235: #          be copied from $source (current location) to 
                   1236: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1237: #         and will then be copied to
                   1238: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1239: #         course's home server.
1.485     raeburn  1240: #
1.481     raeburn  1241: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1242: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1243: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1244: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1245: #         in course's home server.
1.637     raeburn  1246: #
1.477     raeburn  1247: 
                   1248: sub process_coursefile {
1.638     albertel 1249:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1250:     my $fetchresult;
1.638     albertel 1251:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1252:     if ($action eq 'propagate') {
1.638     albertel 1253:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1254: 			     $home);
1.481     raeburn  1255:     } else {
1.477     raeburn  1256:         my $fpath = '';
                   1257:         my $fname = $file;
1.478     albertel 1258:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1259:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1260:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1261:         if ($action eq 'copy') {
                   1262:             if ($source eq '') {
                   1263:                 $fetchresult = 'no source file';
                   1264:                 return $fetchresult;
                   1265:             } else {
                   1266:                 my $destination = $filepath.'/'.$fname;
                   1267:                 rename($source,$destination);
                   1268:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1269:                                  $home);
1.481     raeburn  1270:             }
                   1271:         } elsif ($action eq 'uploaddoc') {
                   1272:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1273:             print $fh $env{'form.'.$source};
1.481     raeburn  1274:             close($fh);
1.637     raeburn  1275:             if ($parser eq 'parse') {
                   1276:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1277:                 unless ($parse_result eq 'ok') {
                   1278:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1279:                 }
                   1280:             }
1.477     raeburn  1281:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1282:                                  $home);
1.481     raeburn  1283:             if ($fetchresult eq 'ok') {
                   1284:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1285:             } else {
                   1286:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1287:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1288:                 return '/adm/notfound.html';
                   1289:             }
1.477     raeburn  1290:         }
                   1291:     }
1.485     raeburn  1292:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1293:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1294:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1295:     }
                   1296:     return $fetchresult;
                   1297: }
                   1298: 
1.637     raeburn  1299: sub build_filepath {
                   1300:     my ($fpath) = @_;
                   1301:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1302:     unless ($fpath eq '') {
                   1303:         my @parts=split('/',$fpath);
                   1304:         foreach my $part (@parts) {
                   1305:             $filepath.= '/'.$part;
                   1306:             if ((-e $filepath)!=1) {
                   1307:                 mkdir($filepath,0777);
                   1308:             }
                   1309:         }
                   1310:     }
                   1311:     return $filepath;
                   1312: }
                   1313: 
                   1314: sub store_edited_file {
1.638     albertel 1315:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1316:     my $file = $primary_url;
                   1317:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1318:     my $fpath = '';
                   1319:     my $fname = $file;
                   1320:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1321:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1322:     my $filepath = &build_filepath($fpath);
                   1323:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1324:     print $fh $content;
                   1325:     close($fh);
1.638     albertel 1326:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1327:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1328: 			  $home);
1.637     raeburn  1329:     if ($$fetchresult eq 'ok') {
                   1330:         return '/uploaded/'.$fpath.'/'.$fname;
                   1331:     } else {
1.638     albertel 1332:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1333: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1334:         return '/adm/notfound.html';
                   1335:     }
                   1336: }
                   1337: 
1.531     albertel 1338: sub clean_filename {
                   1339:     my ($fname)=@_;
1.315     www      1340: # Replace Windows backslashes by forward slashes
1.257     www      1341:     $fname=~s/\\/\//g;
1.315     www      1342: # Get rid of everything but the actual filename
1.257     www      1343:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1344: # Replace spaces by underscores
                   1345:     $fname=~s/\s+/\_/g;
                   1346: # Replace all other weird characters by nothing
1.317     www      1347:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1348: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1349: # numbers
                   1350:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1351:     return $fname;
                   1352: }
                   1353: 
1.608     albertel 1354: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1355: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1356: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1357: #        $coursedoc - if true up to the current course
                   1358: #                     if false
                   1359: #        $subdir - directory in userfile to store the file into
                   1360: #        $parser, $allfiles, $codebase - unknown
                   1361: #
                   1362: # output: url of file in userspace, or error: <message> 
                   1363: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1364: 
                   1365: 
1.531     albertel 1366: sub userfileupload {
1.719     banghart 1367:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1368:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1369:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1370:     $fname=&clean_filename($fname);
1.315     www      1371: # See if there is anything left
1.257     www      1372:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1373:     chop($env{'form.'.$formname});
1.523     raeburn  1374:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1375:         my $now = time;
                   1376:         my $filepath = 'tmp/helprequests/'.$now;
                   1377:         my @parts=split(/\//,$filepath);
                   1378:         my $fullpath = $perlvar{'lonDaemons'};
                   1379:         for (my $i=0;$i<@parts;$i++) {
                   1380:             $fullpath .= '/'.$parts[$i];
                   1381:             if ((-e $fullpath)!=1) {
                   1382:                 mkdir($fullpath,0777);
                   1383:             }
                   1384:         }
                   1385:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1386:         print $fh $env{'form.'.$formname};
1.523     raeburn  1387:         close($fh);
                   1388:         return $fullpath.'/'.$fname; 
                   1389:     }
1.719     banghart 1390:     
1.258     www      1391: # Create the directory if not present
1.493     albertel 1392:     $fname="$subdir/$fname";
1.259     www      1393:     if ($coursedoc) {
1.638     albertel 1394: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1395: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1396:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1397:             return &finishuserfileupload($docuname,$docudom,
                   1398: 					 $formname,$fname,$parser,$allfiles,
                   1399: 					 $codebase);
1.481     raeburn  1400:         } else {
1.620     albertel 1401:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1402:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1403: 				       $fname,$formname,$parser,
                   1404: 				       $allfiles,$codebase);
1.481     raeburn  1405:         }
1.719     banghart 1406:     } elsif (defined($destuname)) {
                   1407:         my $docuname=$destuname;
                   1408:         my $docudom=$destudom;
                   1409: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1410: 				     $fname,$parser,$allfiles,$codebase);
                   1411:         
1.259     www      1412:     } else {
1.638     albertel 1413:         my $docuname=$env{'user.name'};
                   1414:         my $docudom=$env{'user.domain'};
1.714     raeburn  1415:         if (exists($env{'form.group'})) {
                   1416:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1417:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1418:         }
1.638     albertel 1419: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1420: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1421:     }
1.271     www      1422: }
                   1423: 
                   1424: sub finishuserfileupload {
1.638     albertel 1425:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1426:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1427:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1428:     my ($fnamepath,$file);
                   1429:     $file=$fname;
                   1430:     if ($fname=~m|/|) {
                   1431:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1432: 	$path.=$fnamepath.'/';
                   1433:     }
1.259     www      1434:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1435:     my $count;
                   1436:     for ($count=4;$count<=$#parts;$count++) {
                   1437:         $filepath.="/$parts[$count]";
                   1438:         if ((-e $filepath)!=1) {
                   1439: 	    mkdir($filepath,0777);
                   1440:         }
                   1441:     }
                   1442: # Save the file
                   1443:     {
1.701     albertel 1444: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1445: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1446: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1447: 	    return '/adm/notfound.html';
                   1448: 	}
                   1449: 	if (!print FH ($env{'form.'.$formname})) {
                   1450: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1451: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1452: 	    return '/adm/notfound.html';
                   1453: 	}
1.570     albertel 1454: 	close(FH);
1.258     www      1455:     }
1.637     raeburn  1456:     if ($parser eq 'parse') {
1.638     albertel 1457:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1458: 						   $codebase);
1.637     raeburn  1459:         unless ($parse_result eq 'ok') {
1.638     albertel 1460:             &logthis('Failed to parse '.$filepath.$file.
                   1461: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1462:         }
                   1463:     }
1.259     www      1464: # Notify homeserver to grep it
                   1465: #
1.638     albertel 1466:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1467:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1468:     if ($fetchresult eq 'ok') {
1.259     www      1469: #
1.258     www      1470: # Return the URL to it
1.494     albertel 1471:         return '/uploaded/'.$path.$file;
1.263     www      1472:     } else {
1.494     albertel 1473:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1474: 		 ': '.$fetchresult);
1.263     www      1475:         return '/adm/notfound.html';
                   1476:     }    
1.493     albertel 1477: }
                   1478: 
1.637     raeburn  1479: sub extract_embedded_items {
1.648     raeburn  1480:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1481:     my @state = ();
                   1482:     my %javafiles = (
                   1483:                       codebase => '',
                   1484:                       code => '',
                   1485:                       archive => ''
                   1486:                     );
                   1487:     my %mediafiles = (
                   1488:                       src => '',
                   1489:                       movie => '',
                   1490:                      );
1.648     raeburn  1491:     my $p;
                   1492:     if ($content) {
                   1493:         $p = HTML::LCParser->new($content);
                   1494:     } else {
                   1495:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1496:     }
1.641     albertel 1497:     while (my $t=$p->get_token()) {
1.640     albertel 1498: 	if ($t->[0] eq 'S') {
                   1499: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1500: 	    push (@state, $tagname);
1.648     raeburn  1501:             if (lc($tagname) eq 'allow') {
                   1502:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1503:             }
1.640     albertel 1504: 	    if (lc($tagname) eq 'img') {
                   1505: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1506: 	    }
1.645     raeburn  1507:             if (lc($tagname) eq 'script') {
                   1508:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1509:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1510:                 } else {
                   1511:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1512:                 }
                   1513:             }
                   1514:             if (lc($tagname) eq 'link') {
                   1515:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1516:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1517:                 }
                   1518:             }
1.640     albertel 1519: 	    if (lc($tagname) eq 'object' ||
                   1520: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1521: 		foreach my $item (keys(%javafiles)) {
                   1522: 		    $javafiles{$item} = '';
                   1523: 		}
                   1524: 	    }
                   1525: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1526: 		my $name = lc($attr->{'name'});
                   1527: 		foreach my $item (keys(%javafiles)) {
                   1528: 		    if ($name eq $item) {
                   1529: 			$javafiles{$item} = $attr->{'value'};
                   1530: 			last;
                   1531: 		    }
                   1532: 		}
                   1533: 		foreach my $item (keys(%mediafiles)) {
                   1534: 		    if ($name eq $item) {
                   1535: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1536: 			last;
                   1537: 		    }
                   1538: 		}
                   1539: 	    }
                   1540: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1541: 		foreach my $item (keys(%javafiles)) {
                   1542: 		    if ($attr->{$item}) {
                   1543: 			$javafiles{$item} = $attr->{$item};
                   1544: 			last;
                   1545: 		    }
                   1546: 		}
                   1547: 		foreach my $item (keys(%mediafiles)) {
                   1548: 		    if ($attr->{$item}) {
                   1549: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1550: 			last;
                   1551: 		    }
                   1552: 		}
                   1553: 	    }
                   1554: 	} elsif ($t->[0] eq 'E') {
                   1555: 	    my ($tagname) = ($t->[1]);
                   1556: 	    if ($javafiles{'codebase'} ne '') {
                   1557: 		$javafiles{'codebase'} .= '/';
                   1558: 	    }  
                   1559: 	    if (lc($tagname) eq 'applet' ||
                   1560: 		lc($tagname) eq 'object' ||
                   1561: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1562: 		) {
                   1563: 		foreach my $item (keys(%javafiles)) {
                   1564: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1565: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1566: 			&add_filetype($allfiles,$file,$item);
                   1567: 		    }
                   1568: 		}
                   1569: 	    } 
                   1570: 	    pop @state;
                   1571: 	}
                   1572:     }
1.637     raeburn  1573:     return 'ok';
                   1574: }
                   1575: 
1.639     albertel 1576: sub add_filetype {
                   1577:     my ($allfiles,$file,$type)=@_;
                   1578:     if (exists($allfiles->{$file})) {
                   1579: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1580: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1581: 	}
                   1582:     } else {
                   1583: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1584:     }
                   1585: }
                   1586: 
1.493     albertel 1587: sub removeuploadedurl {
                   1588:     my ($url)=@_;
                   1589:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1590:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1591: }
                   1592: 
                   1593: sub removeuserfile {
                   1594:     my ($docuname,$docudom,$fname)=@_;
                   1595:     my $home=&homeserver($docuname,$docudom);
                   1596:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1597: }
1.15      www      1598: 
1.530     albertel 1599: sub mkdiruserfile {
                   1600:     my ($docuname,$docudom,$dir)=@_;
                   1601:     my $home=&homeserver($docuname,$docudom);
                   1602:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1603: }
                   1604: 
1.531     albertel 1605: sub renameuserfile {
                   1606:     my ($docuname,$docudom,$old,$new)=@_;
                   1607:     my $home=&homeserver($docuname,$docudom);
                   1608:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1609: 		  &escape("$new"),$home);
                   1610: }
                   1611: 
1.14      www      1612: # ------------------------------------------------------------------------- Log
                   1613: 
                   1614: sub log {
                   1615:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1616:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1617: }
                   1618: 
                   1619: # ------------------------------------------------------------------ Course Log
1.352     www      1620: #
                   1621: # This routine flushes several buffers of non-mission-critical nature
                   1622: #
1.157     www      1623: 
                   1624: sub flushcourselogs {
1.352     www      1625:     &logthis('Flushing log buffers');
                   1626: #
                   1627: # course logs
                   1628: # This is a log of all transactions in a course, which can be used
                   1629: # for data mining purposes
                   1630: #
                   1631: # It also collects the courseid database, which lists last transaction
                   1632: # times and course titles for all courseids
                   1633: #
                   1634:     my %courseidbuffer=();
1.191     harris41 1635:     foreach (keys %courselogs) {
1.157     www      1636:         my $crsid=$_;
1.352     www      1637:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1638: 		          &escape($courselogs{$crsid}),
                   1639: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1640: 	    delete $courselogs{$crsid};
                   1641:         } else {
                   1642:             &logthis('Failed to flush log buffer for '.$crsid);
                   1643:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1644:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1645:                         " exceeded maximum size, deleting.</font>");
                   1646:                delete $courselogs{$crsid};
                   1647:             }
1.352     www      1648:         }
                   1649:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1650:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1651: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1652:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352     www      1653:         } else {
                   1654:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1655: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1656:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
                   1657:         }
1.191     harris41 1658:     }
1.352     www      1659: #
                   1660: # Write course id database (reverse lookup) to homeserver of courses 
                   1661: # Is used in pickcourse
                   1662: #
                   1663:     foreach (keys %courseidbuffer) {
1.353     www      1664:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1665:     }
                   1666: #
                   1667: # File accesses
                   1668: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1669: #
1.449     matthew  1670:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1671:         if ($entry =~ /___count$/) {
                   1672:             my ($dom,$name);
                   1673:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1674:             if (! defined($dom) || $dom eq '' || 
                   1675:                 ! defined($name) || $name eq '') {
1.620     albertel 1676:                 my $cid = $env{'request.course.id'};
                   1677:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1678:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1679:             }
1.450     matthew  1680:             my $value = $accesshash{$entry};
                   1681:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1682:             my %temphash=($url => $value);
1.449     matthew  1683:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1684:             if ($result eq 'ok') {
                   1685:                 delete $accesshash{$entry};
                   1686:             } elsif ($result eq 'unknown_cmd') {
                   1687:                 # Target server has old code running on it.
1.450     matthew  1688:                 my %temphash=($entry => $value);
1.449     matthew  1689:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1690:                     delete $accesshash{$entry};
                   1691:                 }
                   1692:             }
                   1693:         } else {
1.458     matthew  1694:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1695:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1696:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1697:                 delete $accesshash{$entry};
                   1698:             }
1.185     www      1699:         }
1.191     harris41 1700:     }
1.352     www      1701: #
                   1702: # Roles
                   1703: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1704: #
1.349     www      1705:     foreach (keys %userrolehash) {
                   1706:         my $entry=$_;
1.351     www      1707:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1708: 	    split(/\:/,$entry);
                   1709:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1710:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1711:                 $rudom,$runame) eq 'ok') {
                   1712: 	    delete $userrolehash{$entry};
                   1713:         }
                   1714:     }
1.662     raeburn  1715: #
                   1716: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1717: #
                   1718:     my %domrolebuffer = ();
                   1719:     foreach my $entry (keys %domainrolehash) {
                   1720:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1721:         if ($domrolebuffer{$rudom}) {
                   1722:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1723:                       '='.&escape($domainrolehash{$entry});
                   1724:         } else {
                   1725:             $domrolebuffer{$rudom}.=&escape($entry).
                   1726:                       '='.&escape($domainrolehash{$entry});
                   1727:         }
                   1728:         delete $domainrolehash{$entry};
                   1729:     }
                   1730:     foreach my $dom (keys(%domrolebuffer)) {
                   1731:         foreach my $tryserver (keys %libserv) {
                   1732:             if ($hostdom{$tryserver} eq $dom) {
                   1733:                 unless (&reply('domroleput:'.$dom.':'.
                   1734:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1735:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1736:                 }
                   1737:             }
                   1738:         }
                   1739:     }
1.186     www      1740:     $dumpcount++;
1.157     www      1741: }
                   1742: 
                   1743: sub courselog {
                   1744:     my $what=shift;
1.158     www      1745:     $what=time.':'.$what;
1.620     albertel 1746:     unless ($env{'request.course.id'}) { return ''; }
                   1747:     $coursedombuf{$env{'request.course.id'}}=
                   1748:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1749:     $coursenumbuf{$env{'request.course.id'}}=
                   1750:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1751:     $coursehombuf{$env{'request.course.id'}}=
                   1752:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1753:     $coursedescrbuf{$env{'request.course.id'}}=
                   1754:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1755:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1756:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1757:     $courseownerbuf{$env{'request.course.id'}}=
                   1758:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   1759:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1760: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1761:     } else {
1.620     albertel 1762: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1763:     }
1.620     albertel 1764:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1765: 	&flushcourselogs();
                   1766:     }
1.158     www      1767: }
                   1768: 
                   1769: sub courseacclog {
                   1770:     my $fnsymb=shift;
1.620     albertel 1771:     unless ($env{'request.course.id'}) { return ''; }
                   1772:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1773:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1774:         $what.=':POST';
1.583     matthew  1775:         # FIXME: Probably ought to escape things....
1.620     albertel 1776: 	foreach (keys %env) {
1.158     www      1777:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1778: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1779:             }
1.191     harris41 1780:         }
1.583     matthew  1781:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1782:         # FIXME: We should not be depending on a form parameter that someone
                   1783:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1784:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1785:             $what.= ':POST';
                   1786:             # FIXME: Probably ought to escape things....
                   1787:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1788:                                  'crsdiscuss') {
1.620     albertel 1789:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1790:             }
                   1791:         }
1.158     www      1792:     }
                   1793:     &courselog($what);
1.149     www      1794: }
                   1795: 
1.185     www      1796: sub countacc {
                   1797:     my $url=&declutter(shift);
1.458     matthew  1798:     return if (! defined($url) || $url eq '');
1.620     albertel 1799:     unless ($env{'request.course.id'}) { return ''; }
                   1800:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1801:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1802:     $accesshash{$key}++;
1.185     www      1803: }
1.349     www      1804: 
1.361     www      1805: sub linklog {
                   1806:     my ($from,$to)=@_;
                   1807:     $from=&declutter($from);
                   1808:     $to=&declutter($to);
                   1809:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1810:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1811: }
                   1812:   
1.349     www      1813: sub userrolelog {
                   1814:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1815:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1816:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1817:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1818:         ($trole=~/^ta/)) {
1.350     www      1819:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1820:        $userrolehash
                   1821:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1822:                     =$tend.':'.$tstart;
1.662     raeburn  1823:     }
                   1824:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1825:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1826:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1827:         ($trole=~/^sc/)) {
                   1828:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1829:        $domainrolehash
                   1830:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1831:                     = $tend.':'.$tstart;
                   1832:     }
1.351     www      1833: }
                   1834: 
                   1835: sub get_course_adv_roles {
                   1836:     my $cid=shift;
1.620     albertel 1837:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1838:     my %coursehash=&coursedescription($cid);
1.470     www      1839:     my %nothide=();
                   1840:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1841: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1842:     }
1.351     www      1843:     my %returnhash=();
                   1844:     my %dumphash=
                   1845:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1846:     my $now=time;
                   1847:     foreach (keys %dumphash) {
                   1848: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1849:         if (($tstart) && ($tstart<0)) { next; }
                   1850:         if (($tend) && ($tend<$now)) { next; }
                   1851:         if (($tstart) && ($now<$tstart)) { next; }
                   1852:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1853: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1854: 	if ((&privileged($username,$domain)) && 
                   1855: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1856: 	if ($role eq 'cr') { next; }
1.351     www      1857:         my $key=&plaintext($role);
1.656     albertel 1858: 	if ($role =~ /^cr/) {
                   1859: 	    $key=(split('/',$role))[3];
                   1860: 	}
1.351     www      1861:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1862:         if ($returnhash{$key}) {
                   1863: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1864:         } else {
                   1865:             $returnhash{$key}=$username.':'.$domain;
                   1866:         }
1.400     www      1867:      }
                   1868:     return %returnhash;
                   1869: }
                   1870: 
                   1871: sub get_my_roles {
                   1872:     my ($uname,$udom)=@_;
1.620     albertel 1873:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1874:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1875:     my %dumphash=
                   1876:             &dump('nohist_userroles',$udom,$uname);
                   1877:     my %returnhash=();
                   1878:     my $now=time;
                   1879:     foreach (keys %dumphash) {
                   1880: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1881:         if (($tstart) && ($tstart<0)) { next; }
                   1882:         if (($tend) && ($tend<$now)) { next; }
                   1883:         if (($tstart) && ($now<$tstart)) { next; }
                   1884:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1885: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1886:      }
                   1887:     return %returnhash;
1.399     www      1888: }
                   1889: 
                   1890: # ----------------------------------------------------- Frontpage Announcements
                   1891: #
                   1892: #
                   1893: 
                   1894: sub postannounce {
                   1895:     my ($server,$text)=@_;
                   1896:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1897:     unless ($text=~/\w/) { $text=''; }
                   1898:     return &reply('setannounce:'.&escape($text),$server);
                   1899: }
                   1900: 
                   1901: sub getannounce {
1.448     albertel 1902: 
                   1903:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1904: 	my $announcement='';
                   1905: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1906: 	close($fh);
1.399     www      1907: 	if ($announcement=~/\w/) { 
                   1908: 	    return 
                   1909:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1910:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1911: 	} else {
                   1912: 	    return '';
                   1913: 	}
                   1914:     } else {
                   1915: 	return '';
                   1916:     }
1.351     www      1917: }
1.353     www      1918: 
                   1919: # ---------------------------------------------------------- Course ID routines
                   1920: # Deal with domain's nohist_courseid.db files
                   1921: #
                   1922: 
                   1923: sub courseidput {
                   1924:     my ($domain,$what,$coursehome)=@_;
                   1925:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1926: }
                   1927: 
                   1928: sub courseiddump {
1.622     raeburn  1929:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353     www      1930:     my %returnhash=();
1.355     www      1931:     unless ($domfilter) { $domfilter=''; }
1.353     www      1932:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1933:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1934: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1935: 	        foreach (
                   1936:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1937: 			       $sincefilter.':'.&escape($descfilter).':'.
1.622     raeburn  1938:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354     www      1939:                                $tryserver))) {
1.506     raeburn  1940: 		    my ($key,$value)=split(/\=/,$_);
                   1941:                     if (($key) && ($value)) {
1.516     raeburn  1942: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1943:                     }
1.353     www      1944:                 }
                   1945:             }
                   1946:         }
                   1947:     }
                   1948:     return %returnhash;
                   1949: }
                   1950: 
1.658     raeburn  1951: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1952: 
                   1953: sub dcmailput {
1.685     raeburn  1954:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1955:     my $status = &Apache::lonnet::critical(
                   1956:        'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='.
1.685     raeburn  1957:        &Apache::lonnet::escape($message),$server);
1.662     raeburn  1958:     return $status;
                   1959: }
                   1960: 
1.658     raeburn  1961: sub dcmaildump {
                   1962:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1963:     my %returnhash=();
                   1964:     if (exists($domain_primary{$dom})) {
                   1965:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1966:                                                          &escape($enddate).':';
                   1967: 	my @esc_senders=map { &escape($_)} @$senders;
                   1968: 	$cmd.=&escape(join('&',@esc_senders));
                   1969: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1970:             my ($key,$value) = split(/\=/,$_);
                   1971:             if (($key) && ($value)) {
                   1972:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  1973:             }
                   1974:         }
                   1975:     }
                   1976:     return %returnhash;
                   1977: }
1.662     raeburn  1978: # ---------------------------------------------------------- Domain roles
                   1979: 
                   1980: sub get_domain_roles {
                   1981:     my ($dom,$roles,$startdate,$enddate)=@_;
                   1982:     if (undef($startdate) || $startdate eq '') {
                   1983:         $startdate = '.';
                   1984:     }
                   1985:     if (undef($enddate) || $enddate eq '') {
                   1986:         $enddate = '.';
                   1987:     }
                   1988:     my $rolelist = join(':',@{$roles});
                   1989:     my %personnel = ();
                   1990:     foreach my $tryserver (keys(%libserv)) {
                   1991:         if ($hostdom{$tryserver} eq $dom) {
                   1992:             %{$personnel{$tryserver}}=();
                   1993:             foreach (
                   1994:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   1995:                    &escape($startdate).':'.&escape($enddate).':'.
                   1996:                    &escape($rolelist), $tryserver))) {
                   1997:                 my($key,$value) = split(/\=/,$_);
                   1998:                 if (($key) && ($value)) {
                   1999:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2000:                 }
                   2001:             }
                   2002:         }
                   2003:     }
                   2004:     return %personnel;
                   2005: }
1.658     raeburn  2006: 
1.149     www      2007: # ----------------------------------------------------------- Check out an item
                   2008: 
1.504     albertel 2009: sub get_first_access {
                   2010:     my ($type,$argsymb)=@_;
                   2011:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2012:     if ($argsymb) { $symb=$argsymb; }
                   2013:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2014:     if ($type eq 'map') {
                   2015: 	$res=&symbread($map);
                   2016:     } else {
                   2017: 	$res=$symb;
                   2018:     }
                   2019:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2020:     return $times{"$courseid\0$res"};
1.504     albertel 2021: }
                   2022: 
                   2023: sub set_first_access {
                   2024:     my ($type)=@_;
                   2025:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2026:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2027:     if ($type eq 'map') {
                   2028: 	$res=&symbread($map);
                   2029:     } else {
                   2030: 	$res=$symb;
                   2031:     }
                   2032:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2033:     if (!$firstaccess) {
1.588     albertel 2034: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2035:     }
                   2036:     return 'already_set';
1.504     albertel 2037: }
                   2038: 
1.149     www      2039: sub checkout {
                   2040:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2041:     my $now=time;
                   2042:     my $lonhost=$perlvar{'lonHostID'};
                   2043:     my $infostr=&escape(
1.234     www      2044:                  'CHECKOUTTOKEN&'.
1.149     www      2045:                  $tuname.'&'.
                   2046:                  $tudom.'&'.
                   2047:                  $tcrsid.'&'.
                   2048:                  $symb.'&'.
                   2049: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2050:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2051:     if ($token=~/^error\:/) { 
1.672     albertel 2052:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2053:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2054:                  "</font>");
                   2055:         return ''; 
                   2056:     }
                   2057: 
1.149     www      2058:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2059:     $token=~tr/a-z/A-Z/;
                   2060: 
1.153     www      2061:     my %infohash=('resource.0.outtoken' => $token,
                   2062:                   'resource.0.checkouttime' => $now,
                   2063:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2064: 
                   2065:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2066:        return '';
1.151     www      2067:     } else {
1.672     albertel 2068:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2069:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2070:                  "</font>");
1.149     www      2071:     }    
                   2072: 
                   2073:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2074:                          &escape('Checkout '.$infostr.' - '.
                   2075:                                                  $token)) ne 'ok') {
                   2076: 	return '';
1.151     www      2077:     } else {
1.672     albertel 2078:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2079:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2080:                  "</font>");
1.149     www      2081:     }
1.151     www      2082:     return $token;
1.149     www      2083: }
                   2084: 
                   2085: # ------------------------------------------------------------ Check in an item
                   2086: 
                   2087: sub checkin {
                   2088:     my $token=shift;
1.150     www      2089:     my $now=time;
                   2090:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2091:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2092:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2093:     $dtoken=~s/\W/\_/g;
1.234     www      2094:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2095:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2096: 
1.154     www      2097:     unless (($tuname) && ($tudom)) {
                   2098:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2099:         return '';
                   2100:     }
                   2101:     
                   2102:     unless (&allowed('mgr',$tcrsid)) {
                   2103:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2104:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2105:         return '';
                   2106:     }
                   2107: 
1.153     www      2108:     my %infohash=('resource.0.intoken' => $token,
                   2109:                   'resource.0.checkintime' => $now,
                   2110:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2111: 
                   2112:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2113:        return '';
                   2114:     }    
                   2115: 
                   2116:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2117:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2118: 	return '';
                   2119:     }
                   2120: 
                   2121:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2122: }
                   2123: 
                   2124: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2125: 
                   2126: sub expirespread {
                   2127:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2128:     my $cid=$env{'request.course.id'}; 
1.110     www      2129:     if ($cid) {
                   2130:        my $now=time;
                   2131:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2132:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2133:                             $env{'course.'.$cid.'.num'}.
1.110     www      2134: 	        	    ':nohist_expirationdates:'.
                   2135:                             &escape($key).'='.$now,
1.620     albertel 2136:                             $env{'course.'.$cid.'.home'})
1.110     www      2137:     }
                   2138:     return 'ok';
1.14      www      2139: }
                   2140: 
1.109     www      2141: # ----------------------------------------------------- Devalidate Spreadsheets
                   2142: 
                   2143: sub devalidate {
1.325     www      2144:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2145:     my $cid=$env{'request.course.id'}; 
1.109     www      2146:     if ($cid) {
1.391     matthew  2147:         # delete the stored spreadsheets for
                   2148:         # - the student level sheet of this user in course's homespace
                   2149:         # - the assessment level sheet for this resource 
                   2150:         #   for this user in user's homespace
1.553     albertel 2151: 	# - current conditional state info
1.325     www      2152: 	my $key=$uname.':'.$udom.':';
1.109     www      2153:         my $status=
1.299     matthew  2154: 	    &del('nohist_calculatedsheets',
1.391     matthew  2155: 		 [$key.'studentcalc:'],
1.620     albertel 2156: 		 $env{'course.'.$cid.'.domain'},
                   2157: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2158: 		.' '.
                   2159: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2160: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2161:         unless ($status eq 'ok ok') {
                   2162:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2163:                     $uname.' at '.$udom.' for '.
1.109     www      2164: 		    $symb.': '.$status);
1.133     albertel 2165:         }
1.553     albertel 2166: 	&delenv('user.state.'.$cid);
1.109     www      2167:     }
                   2168: }
                   2169: 
1.265     albertel 2170: sub get_scalar {
                   2171:     my ($string,$end) = @_;
                   2172:     my $value;
                   2173:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2174: 	$value = $1;
                   2175:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2176: 	$value = $1;
                   2177:     }
                   2178:     return &unescape($value);
                   2179: }
                   2180: 
                   2181: sub array2str {
                   2182:   my (@array) = @_;
                   2183:   my $result=&arrayref2str(\@array);
                   2184:   $result=~s/^__ARRAY_REF__//;
                   2185:   $result=~s/__END_ARRAY_REF__$//;
                   2186:   return $result;
                   2187: }
                   2188: 
1.204     albertel 2189: sub arrayref2str {
                   2190:   my ($arrayref) = @_;
1.265     albertel 2191:   my $result='__ARRAY_REF__';
1.204     albertel 2192:   foreach my $elem (@$arrayref) {
1.265     albertel 2193:     if(ref($elem) eq 'ARRAY') {
                   2194:       $result.=&arrayref2str($elem).'&';
                   2195:     } elsif(ref($elem) eq 'HASH') {
                   2196:       $result.=&hashref2str($elem).'&';
                   2197:     } elsif(ref($elem)) {
                   2198:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2199:     } else {
                   2200:       $result.=&escape($elem).'&';
                   2201:     }
                   2202:   }
                   2203:   $result=~s/\&$//;
1.265     albertel 2204:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2205:   return $result;
                   2206: }
                   2207: 
1.168     albertel 2208: sub hash2str {
1.204     albertel 2209:   my (%hash) = @_;
                   2210:   my $result=&hashref2str(\%hash);
1.265     albertel 2211:   $result=~s/^__HASH_REF__//;
                   2212:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2213:   return $result;
                   2214: }
                   2215: 
                   2216: sub hashref2str {
                   2217:   my ($hashref)=@_;
1.265     albertel 2218:   my $result='__HASH_REF__';
1.495     albertel 2219:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2220:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2221:       $result.=&arrayref2str($_).'=';
1.204     albertel 2222:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2223:       $result.=&hashref2str($_).'=';
1.204     albertel 2224:     } elsif (ref($_)) {
1.265     albertel 2225:       $result.='=';
                   2226:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2227:     } else {
1.265     albertel 2228: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2229:     }
                   2230: 
1.265     albertel 2231:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2232:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2233:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2234:       $result.=&hashref2str($hashref->{$_}).'&';
                   2235:     } elsif(ref($hashref->{$_})) {
                   2236:        $result.='&';
                   2237:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2238:     } else {
1.265     albertel 2239:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2240:     }
                   2241:   }
1.168     albertel 2242:   $result=~s/\&$//;
1.265     albertel 2243:   $result .= '__END_HASH_REF__';
1.168     albertel 2244:   return $result;
                   2245: }
                   2246: 
                   2247: sub str2hash {
1.265     albertel 2248:     my ($string)=@_;
                   2249:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2250:     return %$hash;
                   2251: }
                   2252: 
                   2253: sub str2hashref {
1.168     albertel 2254:   my ($string) = @_;
1.265     albertel 2255: 
                   2256:   my %hash;
                   2257: 
                   2258:   if($string !~ /^__HASH_REF__/) {
                   2259:       if (! ($string eq '' || !defined($string))) {
                   2260: 	  $hash{'error'}='Not hash reference';
                   2261:       }
                   2262:       return (\%hash, $string);
                   2263:   }
                   2264: 
                   2265:   $string =~ s/^__HASH_REF__//;
                   2266: 
                   2267:   while($string !~ /^__END_HASH_REF__/) {
                   2268:       #key
                   2269:       my $key='';
                   2270:       if($string =~ /^__HASH_REF__/) {
                   2271:           ($key, $string)=&str2hashref($string);
                   2272:           if(defined($key->{'error'})) {
                   2273:               $hash{'error'}='Bad data';
                   2274:               return (\%hash, $string);
                   2275:           }
                   2276:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2277:           ($key, $string)=&str2arrayref($string);
                   2278:           if($key->[0] eq 'Array reference error') {
                   2279:               $hash{'error'}='Bad data';
                   2280:               return (\%hash, $string);
                   2281:           }
                   2282:       } else {
                   2283:           $string =~ s/^(.*?)=//;
1.267     albertel 2284: 	  $key=&unescape($1);
1.265     albertel 2285:       }
                   2286:       $string =~ s/^=//;
                   2287: 
                   2288:       #value
                   2289:       my $value='';
                   2290:       if($string =~ /^__HASH_REF__/) {
                   2291:           ($value, $string)=&str2hashref($string);
                   2292:           if(defined($value->{'error'})) {
                   2293:               $hash{'error'}='Bad data';
                   2294:               return (\%hash, $string);
                   2295:           }
                   2296:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2297:           ($value, $string)=&str2arrayref($string);
                   2298:           if($value->[0] eq 'Array reference error') {
                   2299:               $hash{'error'}='Bad data';
                   2300:               return (\%hash, $string);
                   2301:           }
                   2302:       } else {
                   2303: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2304:       }
                   2305:       $string =~ s/^&//;
                   2306: 
                   2307:       $hash{$key}=$value;
1.204     albertel 2308:   }
1.265     albertel 2309: 
                   2310:   $string =~ s/^__END_HASH_REF__//;
                   2311: 
                   2312:   return (\%hash, $string);
1.204     albertel 2313: }
                   2314: 
                   2315: sub str2array {
1.265     albertel 2316:     my ($string)=@_;
                   2317:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2318:     return @$array;
                   2319: }
                   2320: 
                   2321: sub str2arrayref {
1.204     albertel 2322:   my ($string) = @_;
1.265     albertel 2323:   my @array;
                   2324: 
                   2325:   if($string !~ /^__ARRAY_REF__/) {
                   2326:       if (! ($string eq '' || !defined($string))) {
                   2327: 	  $array[0]='Array reference error';
                   2328:       }
                   2329:       return (\@array, $string);
                   2330:   }
                   2331: 
                   2332:   $string =~ s/^__ARRAY_REF__//;
                   2333: 
                   2334:   while($string !~ /^__END_ARRAY_REF__/) {
                   2335:       my $value='';
                   2336:       if($string =~ /^__HASH_REF__/) {
                   2337:           ($value, $string)=&str2hashref($string);
                   2338:           if(defined($value->{'error'})) {
                   2339:               $array[0] ='Array reference error';
                   2340:               return (\@array, $string);
                   2341:           }
                   2342:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2343:           ($value, $string)=&str2arrayref($string);
                   2344:           if($value->[0] eq 'Array reference error') {
                   2345:               $array[0] ='Array reference error';
                   2346:               return (\@array, $string);
                   2347:           }
                   2348:       } else {
                   2349: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2350:       }
                   2351:       $string =~ s/^&//;
                   2352: 
                   2353:       push(@array, $value);
1.191     harris41 2354:   }
1.265     albertel 2355: 
                   2356:   $string =~ s/^__END_ARRAY_REF__//;
                   2357: 
                   2358:   return (\@array, $string);
1.168     albertel 2359: }
                   2360: 
1.167     albertel 2361: # -------------------------------------------------------------------Temp Store
                   2362: 
1.168     albertel 2363: sub tmpreset {
                   2364:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2365:   if (!$symb) {
                   2366:     $symb=&symbread();
1.620     albertel 2367:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2368:   }
                   2369:   $symb=escape($symb);
                   2370: 
1.620     albertel 2371:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2372:   $namespace=~s/\//\_/g;
                   2373:   $namespace=~s/\W//g;
                   2374: 
1.620     albertel 2375:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2376:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2377:   if ($domain eq 'public' && $stuname eq 'public') {
                   2378:       $stuname=$ENV{'REMOTE_ADDR'};
                   2379:   }
1.168     albertel 2380:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2381:   my %hash;
                   2382:   if (tie(%hash,'GDBM_File',
                   2383: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2384: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2385:     foreach my $key (keys %hash) {
1.180     albertel 2386:       if ($key=~ /:$symb/) {
1.168     albertel 2387: 	delete($hash{$key});
                   2388:       }
                   2389:     }
                   2390:   }
                   2391: }
                   2392: 
1.167     albertel 2393: sub tmpstore {
1.168     albertel 2394:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2395: 
                   2396:   if (!$symb) {
                   2397:     $symb=&symbread();
1.620     albertel 2398:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2399:   }
                   2400:   $symb=escape($symb);
                   2401: 
                   2402:   if (!$namespace) {
                   2403:     # I don't think we would ever want to store this for a course.
                   2404:     # it seems this will only be used if we don't have a course.
1.620     albertel 2405:     #$namespace=$env{'request.course.id'};
1.168     albertel 2406:     #if (!$namespace) {
1.620     albertel 2407:       $namespace=$env{'request.state'};
1.168     albertel 2408:     #}
                   2409:   }
                   2410:   $namespace=~s/\//\_/g;
                   2411:   $namespace=~s/\W//g;
1.620     albertel 2412:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2413:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2414:   if ($domain eq 'public' && $stuname eq 'public') {
                   2415:       $stuname=$ENV{'REMOTE_ADDR'};
                   2416:   }
1.168     albertel 2417:   my $now=time;
                   2418:   my %hash;
                   2419:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2420:   if (tie(%hash,'GDBM_File',
                   2421: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2422: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2423:     $hash{"version:$symb"}++;
                   2424:     my $version=$hash{"version:$symb"};
                   2425:     my $allkeys=''; 
                   2426:     foreach my $key (keys(%$storehash)) {
                   2427:       $allkeys.=$key.':';
1.591     albertel 2428:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2429:     }
                   2430:     $hash{"$version:$symb:timestamp"}=$now;
                   2431:     $allkeys.='timestamp';
                   2432:     $hash{"$version:keys:$symb"}=$allkeys;
                   2433:     if (untie(%hash)) {
                   2434:       return 'ok';
                   2435:     } else {
                   2436:       return "error:$!";
                   2437:     }
                   2438:   } else {
                   2439:     return "error:$!";
                   2440:   }
                   2441: }
1.167     albertel 2442: 
1.168     albertel 2443: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2444: 
1.168     albertel 2445: sub tmprestore {
                   2446:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2447: 
1.168     albertel 2448:   if (!$symb) {
                   2449:     $symb=&symbread();
1.620     albertel 2450:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2451:   }
                   2452:   $symb=escape($symb);
                   2453: 
1.620     albertel 2454:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2455: 
1.620     albertel 2456:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2457:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2458:   if ($domain eq 'public' && $stuname eq 'public') {
                   2459:       $stuname=$ENV{'REMOTE_ADDR'};
                   2460:   }
1.168     albertel 2461:   my %returnhash;
                   2462:   $namespace=~s/\//\_/g;
                   2463:   $namespace=~s/\W//g;
                   2464:   my %hash;
                   2465:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2466:   if (tie(%hash,'GDBM_File',
                   2467: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2468: 	  &GDBM_READER(),0640)) {
1.168     albertel 2469:     my $version=$hash{"version:$symb"};
                   2470:     $returnhash{'version'}=$version;
                   2471:     my $scope;
                   2472:     for ($scope=1;$scope<=$version;$scope++) {
                   2473:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2474:       my @keys=split(/:/,$vkeys);
                   2475:       my $key;
                   2476:       $returnhash{"$scope:keys"}=$vkeys;
                   2477:       foreach $key (@keys) {
1.591     albertel 2478: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2479: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2480:       }
                   2481:     }
1.168     albertel 2482:     if (!(untie(%hash))) {
                   2483:       return "error:$!";
                   2484:     }
                   2485:   } else {
                   2486:     return "error:$!";
                   2487:   }
                   2488:   return %returnhash;
1.167     albertel 2489: }
                   2490: 
1.9       www      2491: # ----------------------------------------------------------------------- Store
                   2492: 
                   2493: sub store {
1.124     www      2494:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2495:     my $home='';
                   2496: 
1.168     albertel 2497:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2498: 
1.213     www      2499:     $symb=&symbclean($symb);
1.122     albertel 2500:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2501: 
1.620     albertel 2502:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2503:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2504: 
                   2505:     &devalidate($symb,$stuname,$domain);
1.109     www      2506: 
                   2507:     $symb=escape($symb);
1.187     www      2508:     if (!$namespace) { 
1.620     albertel 2509:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2510:           return ''; 
                   2511:        } 
                   2512:     }
1.620     albertel 2513:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2514: 
                   2515:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2516:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2517: 
1.12      www      2518:     my $namevalue='';
1.191     harris41 2519:     foreach (keys %$storehash) {
1.591     albertel 2520:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2521:     }
1.12      www      2522:     $namevalue=~s/\&$//;
1.187     www      2523:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2524:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2525: }
                   2526: 
1.47      www      2527: # -------------------------------------------------------------- Critical Store
                   2528: 
                   2529: sub cstore {
1.124     www      2530:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2531:     my $home='';
                   2532: 
1.168     albertel 2533:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2534: 
1.213     www      2535:     $symb=&symbclean($symb);
1.122     albertel 2536:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2537: 
1.620     albertel 2538:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2539:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2540: 
                   2541:     &devalidate($symb,$stuname,$domain);
1.109     www      2542: 
                   2543:     $symb=escape($symb);
1.187     www      2544:     if (!$namespace) { 
1.620     albertel 2545:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2546:           return ''; 
                   2547:        } 
                   2548:     }
1.620     albertel 2549:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2550: 
                   2551:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2552:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2553: 
1.47      www      2554:     my $namevalue='';
1.191     harris41 2555:     foreach (keys %$storehash) {
1.591     albertel 2556:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2557:     }
1.47      www      2558:     $namevalue=~s/\&$//;
1.187     www      2559:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2560:     return critical
                   2561:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2562: }
                   2563: 
1.9       www      2564: # --------------------------------------------------------------------- Restore
                   2565: 
                   2566: sub restore {
1.124     www      2567:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2568:     my $home='';
                   2569: 
1.168     albertel 2570:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2571: 
1.122     albertel 2572:     if (!$symb) {
                   2573:       unless ($symb=escape(&symbread())) { return ''; }
                   2574:     } else {
1.213     www      2575:       $symb=&escape(&symbclean($symb));
1.122     albertel 2576:     }
1.188     www      2577:     if (!$namespace) { 
1.620     albertel 2578:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2579:           return ''; 
                   2580:        } 
                   2581:     }
1.620     albertel 2582:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2583:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2584:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2585:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2586: 
1.12      www      2587:     my %returnhash=();
1.191     harris41 2588:     foreach (split(/\&/,$answer)) {
1.12      www      2589: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2590:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2591:     }
1.75      www      2592:     my $version;
                   2593:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2594:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2595:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2596:        }
1.75      www      2597:     }
1.13      www      2598:     return %returnhash;
1.34      www      2599: }
                   2600: 
                   2601: # ---------------------------------------------------------- Course Description
                   2602: 
                   2603: sub coursedescription {
1.731   ! albertel 2604:     my ($courseid,$args)=@_;
1.34      www      2605:     $courseid=~s/^\///;
1.49      www      2606:     $courseid=~s/\_/\//g;
1.34      www      2607:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2608:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2609:     my $normalid=$cdomain.'_'.$cnum;
                   2610:     # need to always cache even if we get errors otherwise we keep 
                   2611:     # trying and trying and trying to get the course description.
                   2612:     my %envhash=();
                   2613:     my %returnhash=();
1.731   ! albertel 2614:     
        !          2615:     my $expiretime=600;
        !          2616:     if ($env{'request.course.id'} eq $normalid) {
        !          2617: 	$expiretime=120;
        !          2618:     }
        !          2619: 
        !          2620:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
        !          2621:     if (!$args->{'freshen_cache'}
        !          2622: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
        !          2623: 	foreach my $key (keys(%env)) {
        !          2624: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
        !          2625: 	    my ($setting) = $1;
        !          2626: 	    $returnhash{$setting} = $env{$key};
        !          2627: 	}
        !          2628: 	return %returnhash;
        !          2629:     }
        !          2630: 
        !          2631:     # get the data agin
        !          2632:     if (!$args->{'one_time'}) {
        !          2633: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
        !          2634:     }
1.34      www      2635:     if ($chome ne 'no_host') {
1.302     albertel 2636:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2637:        if (!exists($returnhash{'con_lost'})) {
                   2638:            $returnhash{'home'}= $chome;
                   2639: 	   $returnhash{'domain'} = $cdomain;
                   2640: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2641:            while (my ($name,$value) = each %returnhash) {
1.53      www      2642:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2643:            }
1.270     www      2644:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2645:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2646: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2647:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2648:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2649:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2650:        }
                   2651:     }
1.731   ! albertel 2652:     if (!$args->{'one_time'}) {
        !          2653: 	&appenv(%envhash);
        !          2654:     }
1.302     albertel 2655:     return %returnhash;
1.461     www      2656: }
                   2657: 
                   2658: # -------------------------------------------------See if a user is privileged
                   2659: 
                   2660: sub privileged {
                   2661:     my ($username,$domain)=@_;
                   2662:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2663: 			&homeserver($username,$domain));
                   2664:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2665:     my $now=time;
                   2666:     if ($rolesdump ne '') {
                   2667:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2668: 	    if ($_!~/^rolesdef_/) {
1.461     www      2669: 		my ($area,$role)=split(/=/,$_);
                   2670: 		$area=~s/\_\w\w$//;
                   2671: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2672: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2673: 		    my $active=1;
                   2674: 		    if ($tend) {
                   2675: 			if ($tend<$now) { $active=0; }
                   2676: 		    }
                   2677: 		    if ($tstart) {
                   2678: 			if ($tstart>$now) { $active=0; }
                   2679: 		    }
                   2680: 		    if ($active) { return 1; }
                   2681: 		}
                   2682: 	    }
                   2683: 	}
                   2684:     }
                   2685:     return 0;
1.9       www      2686: }
1.1       albertel 2687: 
1.103     harris41 2688: # -------------------------------------------------------- Get user privileges
1.11      www      2689: 
                   2690: sub rolesinit {
                   2691:     my ($domain,$username,$authhost)=@_;
                   2692:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2693:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2694:     my %allroles=();
1.678     raeburn  2695:     my %allgroups=();   
1.11      www      2696:     my $now=time;
1.21      www      2697:     my $userroles="user.login.time=$now\n";
1.678     raeburn  2698:     my $group_privs;
1.11      www      2699: 
                   2700:     if ($rolesdump ne '') {
1.191     harris41 2701:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2702: 	  if ($_!~/^rolesdef_/) {
1.11      www      2703:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2704: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2705:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2706: 	    if ($role=~/^cr/) { 
1.655     albertel 2707: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2708: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2709: 		    ($tend,$tstart)=split('_',$trest);
                   2710: 		} else {
                   2711: 		    $trole=$role;
                   2712: 		}
1.678     raeburn  2713:             } elsif ($role =~ m|^gr/|) {
                   2714:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2715:                 ($trole,$group_privs) = split(/\//,$trole);
                   2716:                 $group_privs = &unescape($group_privs);
1.587     albertel 2717: 	    } else {
                   2718: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2719: 	    }
1.576     albertel 2720:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567     raeburn  2721:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2722:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2723:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2724: 		my $spec=$trole.'.'.$area;
                   2725: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2726: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2727:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2728:                 } elsif ($trole eq 'gr') {
                   2729:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2730: 		} else {
1.567     raeburn  2731:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2732: 		}
1.12      www      2733:             }
1.662     raeburn  2734:           }
1.191     harris41 2735:         }
1.678     raeburn  2736:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
1.128     www      2737:         $userroles.='user.adv='.$adv."\n".
                   2738: 	            'user.author='.$author."\n";
1.620     albertel 2739:         $env{'user.adv'}=$adv;
1.11      www      2740:     }
                   2741:     return $userroles;  
                   2742: }
                   2743: 
1.567     raeburn  2744: sub set_arearole {
                   2745:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2746: # log the associated role with the area
                   2747:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   2748:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
                   2749: }
                   2750: 
                   2751: sub custom_roleprivs {
                   2752:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2753:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2754:     my $homsvr=homeserver($rauthor,$rdomain);
                   2755:     if ($hostname{$homsvr} ne '') {
                   2756:         my ($rdummy,$roledef)=
                   2757:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2758:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2759:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2760:             if (defined($syspriv)) {
                   2761:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2762:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2763:             }
                   2764:             if ($tdomain ne '') {
                   2765:                 if (defined($dompriv)) {
                   2766:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2767:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2768:                 }
                   2769:                 if (($trest ne '') && (defined($coursepriv))) {
                   2770:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2771:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2772:                 }
                   2773:             }
                   2774:         }
                   2775:     }
                   2776: }
                   2777: 
1.678     raeburn  2778: sub group_roleprivs {
                   2779:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2780:     my $access = 1;
                   2781:     my $now = time;
                   2782:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2783:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2784:     if ($access) {
                   2785:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2786:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2787:     }
                   2788: }
1.567     raeburn  2789: 
                   2790: sub standard_roleprivs {
                   2791:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2792:     if (defined($pr{$trole.':s'})) {
                   2793:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2794:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2795:     }
                   2796:     if ($tdomain ne '') {
                   2797:         if (defined($pr{$trole.':d'})) {
                   2798:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2799:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2800:         }
                   2801:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2802:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2803:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2804:         }
                   2805:     }
                   2806: }
                   2807: 
                   2808: sub set_userprivs {
1.678     raeburn  2809:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2810:     my $author=0;
                   2811:     my $adv=0;
1.678     raeburn  2812:     my %grouproles = ();
                   2813:     if (keys(%{$allgroups}) > 0) {
                   2814:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2815:             my ($trole,$area,$sec,$extendedarea);
                   2816:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2817:                 $trole = $1;
                   2818:                 $area = $2;
1.681     raeburn  2819:                 $sec = $3;
                   2820:                 $extendedarea = $area.$sec;
                   2821:                 if (exists($$allgroups{$area})) {
                   2822:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2823:                         my $spec = $trole.'.'.$extendedarea;
                   2824:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2825:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2826:                     }
                   2827:                 }
                   2828:             }
                   2829:         }
                   2830:     }
                   2831:     foreach (keys(%grouproles)) {
                   2832:         $$allroles{$_} = $grouproles{$_};
                   2833:     }
1.567     raeburn  2834:     foreach (keys %{$allroles}) {
                   2835:         my %thesepriv=();
                   2836:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2837:         foreach (split(/:/,$$allroles{$_})) {
                   2838:             if ($_ ne '') {
                   2839:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2840:                 if ($restrictions eq '') {
                   2841:                     $thesepriv{$privilege}='F';
                   2842:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2843:                     $thesepriv{$privilege}.=$restrictions;
                   2844:                 }
                   2845:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2846:             }
                   2847:         }
                   2848:         my $thesestr='';
                   2849:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
                   2850:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
                   2851:     }
                   2852:     return ($author,$adv);
                   2853: }
                   2854: 
1.12      www      2855: # --------------------------------------------------------------- get interface
                   2856: 
                   2857: sub get {
1.131     albertel 2858:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2859:    my $items='';
1.191     harris41 2860:    foreach (@$storearr) {
1.12      www      2861:        $items.=escape($_).'&';
1.191     harris41 2862:    }
1.12      www      2863:    $items=~s/\&$//;
1.620     albertel 2864:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2865:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2866:    my $uhome=&homeserver($uname,$udomain);
                   2867: 
1.133     albertel 2868:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2869:    my @pairs=split(/\&/,$rep);
1.273     albertel 2870:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2871:      return @pairs;
                   2872:    }
1.15      www      2873:    my %returnhash=();
1.42      www      2874:    my $i=0;
1.191     harris41 2875:    foreach (@$storearr) {
1.557     albertel 2876:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2877:       $i++;
1.191     harris41 2878:    }
1.15      www      2879:    return %returnhash;
1.27      www      2880: }
                   2881: 
                   2882: # --------------------------------------------------------------- del interface
                   2883: 
                   2884: sub del {
1.133     albertel 2885:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2886:    my $items='';
1.191     harris41 2887:    foreach (@$storearr) {
1.27      www      2888:        $items.=escape($_).'&';
1.191     harris41 2889:    }
1.27      www      2890:    $items=~s/\&$//;
1.620     albertel 2891:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2892:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2893:    my $uhome=&homeserver($uname,$udomain);
                   2894: 
                   2895:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2896: }
                   2897: 
                   2898: # -------------------------------------------------------------- dump interface
                   2899: 
                   2900: sub dump {
1.702     albertel 2901:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.620     albertel 2902:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2903:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2904:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2905:    if ($regexp) {
                   2906:        $regexp=&escape($regexp);
                   2907:    } else {
                   2908:        $regexp='.';
                   2909:    }
1.702     albertel 2910:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.12      www      2911:    my @pairs=split(/\&/,$rep);
                   2912:    my %returnhash=();
1.191     harris41 2913:    foreach (@pairs) {
1.702     albertel 2914:       my ($key,$value)=split(/=/,$_,2);
1.557     albertel 2915:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2916:    }
                   2917:    return %returnhash;
1.407     www      2918: }
                   2919: 
1.717     albertel 2920: # --------------------------------------------------------- dumpstore interface
                   2921: 
                   2922: sub dumpstore {
                   2923:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2924:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2925: }
                   2926: 
1.407     www      2927: # -------------------------------------------------------------- keys interface
                   2928: 
                   2929: sub getkeys {
                   2930:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2931:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2932:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2933:    my $uhome=&homeserver($uname,$udomain);
                   2934:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2935:    my @keyarray=();
                   2936:    foreach (split(/\&/,$rep)) {
                   2937:       push (@keyarray,&unescape($_));
                   2938:    }
                   2939:    return @keyarray;
1.318     matthew  2940: }
                   2941: 
1.319     matthew  2942: # --------------------------------------------------------------- currentdump
                   2943: sub currentdump {
1.328     matthew  2944:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2945:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2946:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2947:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2948:    my $uhome = &homeserver($sname,$sdom);
                   2949:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2950:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2951:    #
1.318     matthew  2952:    my %returnhash=();
1.319     matthew  2953:    #
                   2954:    if ($rep eq "unknown_cmd") { 
                   2955:        # an old lond will not know currentdump
                   2956:        # Do a dump and make it look like a currentdump
1.326     matthew  2957:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2958:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2959:        my %hash = @tmp;
                   2960:        @tmp=();
1.424     matthew  2961:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2962:    } else {
                   2963:        my @pairs=split(/\&/,$rep);
                   2964:        foreach (@pairs) {
                   2965:            my ($key,$value)=split(/=/,$_);
                   2966:            my ($symb,$param) = split(/:/,$key);
                   2967:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2968:                                                         &thaw_unescape($value);
1.319     matthew  2969:        }
1.191     harris41 2970:    }
1.12      www      2971:    return %returnhash;
1.424     matthew  2972: }
                   2973: 
                   2974: sub convert_dump_to_currentdump{
                   2975:     my %hash = %{shift()};
                   2976:     my %returnhash;
                   2977:     # Code ripped from lond, essentially.  The only difference
                   2978:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2979:     # we might run in to problems with parameter names =~ /^v\./
                   2980:     while (my ($key,$value) = each(%hash)) {
                   2981:         my ($v,$symb,$param) = split(/:/,$key);
                   2982:         next if ($v eq 'version' || $symb eq 'keys');
                   2983:         next if (exists($returnhash{$symb}) &&
                   2984:                  exists($returnhash{$symb}->{$param}) &&
                   2985:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2986:         $returnhash{$symb}->{$param}=$value;
                   2987:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2988:     }
                   2989:     #
                   2990:     # Remove all of the keys in the hashes which keep track of
                   2991:     # the version of the parameter.
                   2992:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2993:         # use a foreach because we are going to delete from the hash.
                   2994:         foreach my $key (keys(%$param_hash)) {
                   2995:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2996:         }
                   2997:     }
                   2998:     return \%returnhash;
1.12      www      2999: }
                   3000: 
1.627     albertel 3001: # ------------------------------------------------------ critical inc interface
                   3002: 
                   3003: sub cinc {
                   3004:     return &inc(@_,'critical');
                   3005: }
                   3006: 
1.449     matthew  3007: # --------------------------------------------------------------- inc interface
                   3008: 
                   3009: sub inc {
1.627     albertel 3010:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3011:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3012:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3013:     my $uhome=&homeserver($uname,$udomain);
                   3014:     my $items='';
                   3015:     if (! ref($store)) {
                   3016:         # got a single value, so use that instead
                   3017:         $items = &escape($store).'=&';
                   3018:     } elsif (ref($store) eq 'SCALAR') {
                   3019:         $items = &escape($$store).'=&';        
                   3020:     } elsif (ref($store) eq 'ARRAY') {
                   3021:         $items = join('=&',map {&escape($_);} @{$store});
                   3022:     } elsif (ref($store) eq 'HASH') {
                   3023:         while (my($key,$value) = each(%{$store})) {
                   3024:             $items.= &escape($key).'='.&escape($value).'&';
                   3025:         }
                   3026:     }
                   3027:     $items=~s/\&$//;
1.627     albertel 3028:     if ($critical) {
                   3029: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3030:     } else {
                   3031: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3032:     }
1.449     matthew  3033: }
                   3034: 
1.12      www      3035: # --------------------------------------------------------------- put interface
                   3036: 
                   3037: sub put {
1.134     albertel 3038:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3039:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3040:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3041:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3042:    my $items='';
1.191     harris41 3043:    foreach (keys %$storehash) {
1.557     albertel 3044:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3045:    }
1.12      www      3046:    $items=~s/\&$//;
1.134     albertel 3047:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3048: }
                   3049: 
1.631     albertel 3050: # ------------------------------------------------------------ newput interface
                   3051: 
                   3052: sub newput {
                   3053:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3054:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3055:    if (!$uname) { $uname=$env{'user.name'}; }
                   3056:    my $uhome=&homeserver($uname,$udomain);
                   3057:    my $items='';
                   3058:    foreach my $key (keys(%$storehash)) {
                   3059:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3060:    }
                   3061:    $items=~s/\&$//;
                   3062:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3063: }
                   3064: 
                   3065: # ---------------------------------------------------------  putstore interface
                   3066: 
1.524     raeburn  3067: sub putstore {
1.715     albertel 3068:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3069:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3070:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3071:    my $uhome=&homeserver($uname,$udomain);
                   3072:    my $items='';
1.715     albertel 3073:    foreach my $key (keys(%$storehash)) {
                   3074:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3075:    }
1.715     albertel 3076:    $items=~s/\&$//;
1.716     albertel 3077:    my $esc_symb=&escape($symb);
                   3078:    my $esc_v=&escape($version);
1.715     albertel 3079:    my $reply =
1.716     albertel 3080:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3081: 	      $uhome);
                   3082:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3083:        # gfall back to way things use to be done
1.715     albertel 3084:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3085: 			    $uname);
1.524     raeburn  3086:    }
1.715     albertel 3087:    return $reply;
                   3088: }
                   3089: 
                   3090: sub old_putstore {
1.716     albertel 3091:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3092:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3093:     if (!$uname) { $uname=$env{'user.name'}; }
                   3094:     my $uhome=&homeserver($uname,$udomain);
                   3095:     my %newstorehash;
                   3096:     foreach (keys %$storehash) {
                   3097: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3098: 	$newstorehash{$key} = $storehash->{$_};
                   3099:     }
                   3100:     my $items='';
                   3101:     my %allitems = ();
                   3102:     foreach (keys %newstorehash) {
                   3103: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3104: 	    my $key = $1.':keys:'.$2;
                   3105: 	    $allitems{$key} .= $3.':';
                   3106: 	}
                   3107: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3108:     }
                   3109:     foreach (keys %allitems) {
                   3110: 	$allitems{$_} =~ s/\:$//;
                   3111: 	$items.= $_.'='.$allitems{$_}.'&';
                   3112:     }
                   3113:     $items=~s/\&$//;
                   3114:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3115: }
                   3116: 
1.47      www      3117: # ------------------------------------------------------ critical put interface
                   3118: 
                   3119: sub cput {
1.134     albertel 3120:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3121:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3122:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3123:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3124:    my $items='';
1.191     harris41 3125:    foreach (keys %$storehash) {
1.715     albertel 3126:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3127:    }
1.47      www      3128:    $items=~s/\&$//;
1.134     albertel 3129:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3130: }
                   3131: 
                   3132: # -------------------------------------------------------------- eget interface
                   3133: 
                   3134: sub eget {
1.133     albertel 3135:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3136:    my $items='';
1.191     harris41 3137:    foreach (@$storearr) {
1.12      www      3138:        $items.=escape($_).'&';
1.191     harris41 3139:    }
1.12      www      3140:    $items=~s/\&$//;
1.620     albertel 3141:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3142:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3143:    my $uhome=&homeserver($uname,$udomain);
                   3144:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3145:    my @pairs=split(/\&/,$rep);
                   3146:    my %returnhash=();
1.42      www      3147:    my $i=0;
1.191     harris41 3148:    foreach (@$storearr) {
1.557     albertel 3149:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3150:       $i++;
1.191     harris41 3151:    }
1.12      www      3152:    return %returnhash;
                   3153: }
                   3154: 
1.667     albertel 3155: # ------------------------------------------------------------ tmpput interface
                   3156: sub tmpput {
                   3157:     my ($storehash,$server)=@_;
                   3158:     my $items='';
                   3159:     foreach (keys(%$storehash)) {
                   3160: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3161:     }
                   3162:     $items=~s/\&$//;
                   3163:     return &reply("tmpput:$items",$server);
                   3164: }
                   3165: 
                   3166: # ------------------------------------------------------------ tmpget interface
                   3167: sub tmpget {
1.688     albertel 3168:     my ($token,$server)=@_;
                   3169:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3170:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3171:     my %returnhash;
                   3172:     foreach my $item (split(/\&/,$rep)) {
                   3173: 	my ($key,$value)=split(/=/,$item);
                   3174: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3175:     }
                   3176:     return %returnhash;
                   3177: }
                   3178: 
1.688     albertel 3179: # ------------------------------------------------------------ tmpget interface
                   3180: sub tmpdel {
                   3181:     my ($token,$server)=@_;
                   3182:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3183:     return &reply("tmpdel:$token",$server);
                   3184: }
                   3185: 
1.341     www      3186: # ---------------------------------------------- Custom access rule evaluation
                   3187: 
                   3188: sub customaccess {
                   3189:     my ($priv,$uri)=@_;
1.620     albertel 3190:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3191:     $urealm=~s/^\W//;
                   3192:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3193:     my $access=0;
                   3194:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3195: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3196:         if ($role) {
                   3197: 	   if ($role ne $urole) { next; }
                   3198:         }
                   3199:         foreach (split(/\s*\,\s*/,$realm)) {
                   3200:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3201:             if ($tdom) {
                   3202: 		if ($tdom ne $udom) { next; }
                   3203:             }
                   3204:             if ($tcrs) {
                   3205: 		if ($tcrs ne $ucrs) { next; }
                   3206:             }
                   3207:             if ($tsec) {
                   3208: 		if ($tsec ne $usec) { next; }
                   3209:             }
                   3210:             $access=($effect eq 'allow');
                   3211:             last;
1.342     www      3212:         }
1.402     bowersj2 3213: 	if ($realm eq '' && $role eq '') {
                   3214:             $access=($effect eq 'allow');
                   3215: 	}
1.341     www      3216:     }
                   3217:     return $access;
                   3218: }
                   3219: 
1.103     harris41 3220: # ------------------------------------------------- Check for a user privilege
1.12      www      3221: 
                   3222: sub allowed {
1.579     albertel 3223:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3224:     my $ver_orguri=$uri;
1.439     www      3225:     $uri=&deversion($uri);
1.152     www      3226:     my $orguri=$uri;
1.52      www      3227:     $uri=&declutter($uri);
1.545     banghart 3228:     
1.620     albertel 3229:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3230: # Free bre access to adm and meta resources
1.529     albertel 3231:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3232: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3233: 	return 'F';
1.159     www      3234:     }
                   3235: 
1.545     banghart 3236: # Free bre access to user's own portfolio contents
1.714     raeburn  3237:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3238:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3239: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3240:         return 'F';
                   3241:     }
                   3242: 
1.714     raeburn  3243: # bre access to group if user has rgf priv for this group and course.
                   3244:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3245:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3246:         if (exists($env{'request.course.id'})) {
                   3247:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3248:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3249:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3250:                 my $courseprivid=$env{'request.course.id'};
                   3251:                 $courseprivid=~s/\_/\//;
                   3252:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3253:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3254:                     return $1; 
                   3255:                 }
                   3256:             }
                   3257:         }
                   3258:     }
                   3259: 
1.159     www      3260: # Free bre to public access
                   3261: 
                   3262:     if ($priv eq 'bre') {
1.238     www      3263:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3264: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3265:            return 'F'; 
                   3266:         }
1.238     www      3267:         if ($copyright eq 'priv') {
                   3268:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3269: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3270: 		return '';
                   3271:             }
                   3272:         }
                   3273:         if ($copyright eq 'domain') {
                   3274:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3275: 	    unless (($env{'user.domain'} eq $1) ||
                   3276:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3277: 		return '';
                   3278:             }
1.262     matthew  3279:         }
1.620     albertel 3280:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3281:             # Library role, so allow browsing of resources in this domain.
                   3282:             return 'F';
1.238     www      3283:         }
1.341     www      3284:         if ($copyright eq 'custom') {
                   3285: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3286:         }
1.14      www      3287:     }
1.264     matthew  3288:     # Domain coordinator is trying to create a course
1.620     albertel 3289:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3290:         # uri is the requested domain in this case.
                   3291:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3292:         # a role of dc for the domain in question.
1.620     albertel 3293:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3294:     }
1.29      www      3295: 
1.52      www      3296:     my $thisallowed='';
                   3297:     my $statecond=0;
                   3298:     my $courseprivid='';
                   3299: 
                   3300: # Course
                   3301: 
1.620     albertel 3302:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3303:        $thisallowed.=$1;
                   3304:     }
1.29      www      3305: 
1.52      www      3306: # Domain
                   3307: 
1.620     albertel 3308:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3309:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3310:        $thisallowed.=$1;
                   3311:     }
1.52      www      3312: 
                   3313: # Course: uri itself is a course
1.66      www      3314:     my $courseuri=$uri;
                   3315:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3316:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3317: 
1.620     albertel 3318:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3319:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3320:        $thisallowed.=$1;
                   3321:     }
1.29      www      3322: 
1.678     raeburn  3323: # Group: uri itself is a group
                   3324:     my $groupuri=$uri;
                   3325:     $groupuri=~s/^([^\/])/\/$1/;
                   3326:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3327:        =~/\Q$priv\E\&([^\:]*)/) {
                   3328:        $thisallowed.=$1;
                   3329:     }
                   3330: 
1.665     albertel 3331: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3332: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3333:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3334: 	$thisallowed='';
1.671     raeburn  3335:         my ($match)=&is_on_map($uri);
                   3336:         if ($match) {
                   3337:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3338:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3339:                 $thisallowed.=$1;
                   3340:             }
                   3341:         } else {
1.705     albertel 3342:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3343:             if ($refuri) {
                   3344:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3345:                     $thisallowed='F';
1.671     raeburn  3346:                 } else {
                   3347:                     $refuri=&declutter($refuri);
                   3348:                     my ($match) = &is_on_map($refuri);
                   3349:                     if ($match) {
                   3350:                         $thisallowed='F';
                   3351:                     }
1.669     raeburn  3352:                 }
1.671     raeburn  3353:             }
                   3354:         }
1.314     www      3355:     }
1.492     albertel 3356: 
1.52      www      3357: # Full access at system, domain or course-wide level? Exit.
1.29      www      3358: 
                   3359:     if ($thisallowed=~/F/) {
                   3360: 	return 'F';
                   3361:     }
                   3362: 
1.52      www      3363: # If this is generating or modifying users, exit with special codes
1.29      www      3364: 
1.643     www      3365:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3366: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3367: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3368: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3369: 	    unless ($auname) { return $thisallowed; }
                   3370: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3371: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3372: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3373: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3374: 	}
1.52      www      3375: 	return $thisallowed;
                   3376:     }
                   3377: #
1.103     harris41 3378: # Gathered so far: system, domain and course wide privileges
1.52      www      3379: #
                   3380: # Course: See if uri or referer is an individual resource that is part of 
                   3381: # the course
                   3382: 
1.620     albertel 3383:     if ($env{'request.course.id'}) {
1.232     www      3384: 
1.620     albertel 3385:        $courseprivid=$env{'request.course.id'};
                   3386:        if ($env{'request.course.sec'}) {
                   3387:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3388:        }
                   3389:        $courseprivid=~s/\_/\//;
                   3390:        my $checkreferer=1;
1.232     www      3391:        my ($match,$cond)=&is_on_map($uri);
                   3392:        if ($match) {
                   3393:            $statecond=$cond;
1.620     albertel 3394:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3395:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3396:                $thisallowed.=$1;
                   3397:                $checkreferer=0;
                   3398:            }
1.29      www      3399:        }
1.83      www      3400:        
1.148     www      3401:        if ($checkreferer) {
1.620     albertel 3402: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3403:             unless ($refuri) {
1.620     albertel 3404:                 foreach (keys %env) {
1.148     www      3405: 		    if ($_=~/^httpref\..*\*/) {
                   3406: 			my $pattern=$_;
1.156     www      3407:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3408:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3409:                         $pattern=~s/\//\\\//g;
1.152     www      3410:                         if ($orguri=~/$pattern/) {
1.620     albertel 3411: 			    $refuri=$env{$_};
1.148     www      3412:                         }
                   3413:                     }
1.191     harris41 3414:                 }
1.148     www      3415:             }
1.232     www      3416: 
1.148     www      3417:          if ($refuri) { 
1.152     www      3418: 	  $refuri=&declutter($refuri);
1.232     www      3419:           my ($match,$cond)=&is_on_map($refuri);
                   3420:             if ($match) {
                   3421:               my $refstatecond=$cond;
1.620     albertel 3422:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3423:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3424:                   $thisallowed.=$1;
1.53      www      3425:                   $uri=$refuri;
                   3426:                   $statecond=$refstatecond;
1.52      www      3427:               }
                   3428:           }
1.148     www      3429:         }
1.29      www      3430:        }
1.52      www      3431:    }
1.29      www      3432: 
1.52      www      3433: #
1.103     harris41 3434: # Gathered now: all privileges that could apply, and condition number
1.52      www      3435: # 
                   3436: #
                   3437: # Full or no access?
                   3438: #
1.29      www      3439: 
1.52      www      3440:     if ($thisallowed=~/F/) {
                   3441: 	return 'F';
                   3442:     }
1.29      www      3443: 
1.52      www      3444:     unless ($thisallowed) {
                   3445:         return '';
                   3446:     }
1.29      www      3447: 
1.52      www      3448: # Restrictions exist, deal with them
                   3449: #
                   3450: #   C:according to course preferences
                   3451: #   R:according to resource settings
                   3452: #   L:unless locked
                   3453: #   X:according to user session state
                   3454: #
                   3455: 
                   3456: # Possibly locked functionality, check all courses
1.54      www      3457: # Locks might take effect only after 10 minutes cache expiration for other
                   3458: # courses, and 2 minutes for current course
1.52      www      3459: 
                   3460:     my $envkey;
                   3461:     if ($thisallowed=~/L/) {
1.620     albertel 3462:         foreach $envkey (keys %env) {
1.54      www      3463:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3464:                my $courseid=$2;
                   3465:                my $roleid=$1.'.'.$2;
1.92      www      3466:                $courseid=~s/^\///;
1.54      www      3467:                my $expiretime=600;
1.620     albertel 3468:                if ($env{'request.role'} eq $roleid) {
1.54      www      3469: 		  $expiretime=120;
                   3470:                }
                   3471: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3472:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3473:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731   ! albertel 3474: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3475:                }
1.620     albertel 3476:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3477:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3478: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3479:                        &log($env{'user.domain'},$env{'user.name'},
                   3480:                             $env{'user.home'},
1.57      www      3481:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3482:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3483:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3484: 		       return '';
                   3485:                    }
                   3486:                }
1.620     albertel 3487:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3488:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3489: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3490:                        &log($env{'user.domain'},$env{'user.name'},
                   3491:                             $env{'user.home'},
1.57      www      3492:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3493:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3494:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3495: 		       return '';
                   3496:                    }
                   3497:                }
                   3498: 	   }
1.29      www      3499:        }
1.52      www      3500:     }
                   3501:    
                   3502: #
                   3503: # Rest of the restrictions depend on selected course
                   3504: #
                   3505: 
1.620     albertel 3506:     unless ($env{'request.course.id'}) {
1.52      www      3507:        return '1';
                   3508:     }
1.29      www      3509: 
1.52      www      3510: #
                   3511: # Now user is definitely in a course
                   3512: #
1.53      www      3513: 
                   3514: 
                   3515: # Course preferences
                   3516: 
                   3517:    if ($thisallowed=~/C/) {
1.620     albertel 3518:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3519:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3520:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3521: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3522: 	   if ($priv ne 'pch') { 
                   3523: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3524: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3525: 			$env{'request.course.id'});
                   3526: 	   }
1.237     www      3527:            return '';
                   3528:        }
                   3529: 
1.620     albertel 3530:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3531: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3532: 	   if ($priv ne 'pch') { 
                   3533: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3534: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3535: 			$env{'request.course.id'});
                   3536: 	   }
1.54      www      3537:            return '';
                   3538:        }
1.53      www      3539:    }
                   3540: 
                   3541: # Resource preferences
                   3542: 
                   3543:    if ($thisallowed=~/R/) {
1.620     albertel 3544:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3545:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3546: 	   if ($priv ne 'pch') { 
                   3547: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3548: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3549: 	   }
                   3550: 	   return '';
1.54      www      3551:        }
1.53      www      3552:    }
1.30      www      3553: 
1.246     www      3554: # Restricted by state or randomout?
1.30      www      3555: 
1.52      www      3556:    if ($thisallowed=~/X/) {
1.620     albertel 3557:       if ($env{'acc.randomout'}) {
1.579     albertel 3558: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3559:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3560:             return ''; 
                   3561:          }
1.247     www      3562:       }
                   3563:       if (&condval($statecond)) {
1.52      www      3564: 	 return '2';
                   3565:       } else {
                   3566:          return '';
                   3567:       }
                   3568:    }
1.30      www      3569: 
1.52      www      3570:    return 'F';
1.232     www      3571: }
                   3572: 
1.710     albertel 3573: sub split_uri_for_cond {
                   3574:     my $uri=&deversion(&declutter(shift));
                   3575:     my @uriparts=split(/\//,$uri);
                   3576:     my $filename=pop(@uriparts);
                   3577:     my $pathname=join('/',@uriparts);
                   3578:     return ($pathname,$filename);
                   3579: }
1.232     www      3580: # --------------------------------------------------- Is a resource on the map?
                   3581: 
                   3582: sub is_on_map {
1.710     albertel 3583:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3584:     #Trying to find the conditional for the file
1.620     albertel 3585:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3586: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3587:     if ($match) {
1.289     bowersj2 3588: 	return (1,$1);
                   3589:     } else {
1.434     www      3590: 	return (0,0);
1.289     bowersj2 3591:     }
1.12      www      3592: }
                   3593: 
1.427     www      3594: # --------------------------------------------------------- Get symb from alias
                   3595: 
                   3596: sub get_symb_from_alias {
                   3597:     my $symb=shift;
                   3598:     my ($map,$resid,$url)=&decode_symb($symb);
                   3599: # Already is a symb
                   3600:     if ($url) { return $symb; }
                   3601: # Must be an alias
                   3602:     my $aliassymb='';
                   3603:     my %bighash;
1.620     albertel 3604:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3605:                             &GDBM_READER(),0640)) {
                   3606:         my $rid=$bighash{'mapalias_'.$symb};
                   3607: 	if ($rid) {
                   3608: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3609: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3610: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3611: 	}
                   3612:         untie %bighash;
                   3613:     }
                   3614:     return $aliassymb;
                   3615: }
                   3616: 
1.12      www      3617: # ----------------------------------------------------------------- Define Role
                   3618: 
                   3619: sub definerole {
                   3620:   if (allowed('mcr','/')) {
                   3621:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3622:     foreach (split(':',$sysrole)) {
1.21      www      3623: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3624:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3625:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3626: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3627:                return "refused:s:$crole&$cqual"; 
                   3628:             }
                   3629:         }
1.191     harris41 3630:     }
1.392     www      3631:     foreach (split(':',$domrole)) {
1.21      www      3632: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3633:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3634:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3635: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3636:                return "refused:d:$crole&$cqual"; 
                   3637:             }
                   3638:         }
1.191     harris41 3639:     }
1.392     www      3640:     foreach (split(':',$courole)) {
1.21      www      3641: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3642:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3643:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3644: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3645:                return "refused:c:$crole&$cqual"; 
                   3646:             }
                   3647:         }
1.191     harris41 3648:     }
1.620     albertel 3649:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3650:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3651: 	        "rolesdef_$rolename=".
                   3652:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3653:     return reply($command,$env{'user.home'});
1.12      www      3654:   } else {
                   3655:     return 'refused';
                   3656:   }
1.105     harris41 3657: }
                   3658: 
                   3659: # ---------------- Make a metadata query against the network of library servers
                   3660: 
                   3661: sub metadata_query {
1.244     matthew  3662:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3663:     my %rhash;
1.244     matthew  3664:     my @server_list = (defined($server_array) ? @$server_array
                   3665:                                               : keys(%libserv) );
                   3666:     for my $server (@server_list) {
1.118     harris41 3667: 	unless ($custom or $customshow) {
                   3668: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3669: 	    $rhash{$server}=$reply;
                   3670: 	}
                   3671: 	else {
                   3672: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3673: 			     &escape($custom).':'.&escape($customshow),
                   3674: 			     $server);
                   3675: 	    $rhash{$server}=$reply;
                   3676: 	}
1.112     harris41 3677:     }
1.118     harris41 3678:     return \%rhash;
1.240     www      3679: }
                   3680: 
                   3681: # ----------------------------------------- Send log queries and wait for reply
                   3682: 
                   3683: sub log_query {
                   3684:     my ($uname,$udom,$query,%filters)=@_;
                   3685:     my $uhome=&homeserver($uname,$udom);
                   3686:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3687:     my $uhost=$hostname{$uhome};
1.241     www      3688:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3689:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3690:                        $uhome);
1.479     albertel 3691:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3692:     return get_query_reply($queryid);
                   3693: }
                   3694: 
1.508     raeburn  3695: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3696: 
                   3697: sub fetch_enrollment_query {
1.511     raeburn  3698:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3699:     my $homeserver;
1.547     raeburn  3700:     my $maxtries = 1;
1.508     raeburn  3701:     if ($context eq 'automated') {
                   3702:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3703:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3704:     } else {
                   3705:         $homeserver = &homeserver($cnum,$dom);
                   3706:     }
1.506     raeburn  3707:     my $host=$hostname{$homeserver};
                   3708:     my $cmd = '';
                   3709:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3710:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3711:     }
                   3712:     $cmd =~ s/%%$//;
                   3713:     $cmd = &escape($cmd);
                   3714:     my $query = 'fetchenrollment';
1.620     albertel 3715:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3716:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3717:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3718:         return 'error: '.$queryid;
                   3719:     }
1.506     raeburn  3720:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3721:     my $tries = 1;
                   3722:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3723:         $reply = &get_query_reply($queryid);
                   3724:         $tries ++;
                   3725:     }
1.526     raeburn  3726:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3727:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3728:     } else {
1.515     raeburn  3729:         my @responses = split/:/,$reply;
                   3730:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3731:             foreach (@responses) {
                   3732:                 my ($key,$value) = split/=/,$_;
                   3733:                 $$replyref{$key} = $value;
                   3734:             }
                   3735:         } else {
1.506     raeburn  3736:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3737:             foreach (@responses) {
                   3738:                 my ($key,$value) = split/=/,$_;
                   3739:                 $$replyref{$key} = $value;
                   3740:                 if ($value > 0) {
                   3741:                     foreach (@{$$affiliatesref{$key}}) {
                   3742:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3743:                         my $destname = $pathname.'/'.$filename;
                   3744:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3745:                         if ($xml_classlist =~ /^error/) {
                   3746:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3747:                         } else {
1.506     raeburn  3748:                             if ( open(FILE,">$destname") ) {
                   3749:                                 print FILE &unescape($xml_classlist);
                   3750:                                 close(FILE);
1.526     raeburn  3751:                             } else {
                   3752:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3753:                             }
                   3754:                         }
                   3755:                     }
                   3756:                 }
                   3757:             }
                   3758:         }
                   3759:         return 'ok';
                   3760:     }
                   3761:     return 'error';
                   3762: }
                   3763: 
1.242     www      3764: sub get_query_reply {
                   3765:     my $queryid=shift;
1.240     www      3766:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3767:     my $reply='';
                   3768:     for (1..100) {
                   3769: 	sleep 2;
                   3770:         if (-e $replyfile.'.end') {
1.448     albertel 3771: 	    if (open(my $fh,$replyfile)) {
1.240     www      3772:                $reply.=<$fh>;
1.448     albertel 3773:                close($fh);
1.240     www      3774: 	   } else { return 'error: reply_file_error'; }
1.242     www      3775:            return &unescape($reply);
                   3776: 	}
1.240     www      3777:     }
1.242     www      3778:     return 'timeout:'.$queryid;
1.240     www      3779: }
                   3780: 
                   3781: sub courselog_query {
1.241     www      3782: #
                   3783: # possible filters:
                   3784: # url: url or symb
                   3785: # username
                   3786: # domain
                   3787: # action: view, submit, grade
                   3788: # start: timestamp
                   3789: # end: timestamp
                   3790: #
1.240     www      3791:     my (%filters)=@_;
1.620     albertel 3792:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3793:     if ($filters{'url'}) {
                   3794: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3795:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3796:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3797:     }
1.620     albertel 3798:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3799:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3800:     return &log_query($cname,$cdom,'courselog',%filters);
                   3801: }
                   3802: 
                   3803: sub userlog_query {
                   3804:     my ($uname,$udom,%filters)=@_;
                   3805:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3806: }
                   3807: 
1.506     raeburn  3808: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3809: 
                   3810: sub auto_run {
1.508     raeburn  3811:     my ($cnum,$cdom) = @_;
                   3812:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3813:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3814:     return $response;
                   3815: }
                   3816:                                                                                    
                   3817: sub auto_get_sections {
1.508     raeburn  3818:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3819:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3820:     my @secs = ();
1.511     raeburn  3821:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3822:     unless ($response eq 'refused') {
                   3823:         @secs = split/:/,$response;
                   3824:     }
                   3825:     return @secs;
                   3826: }
                   3827:                                                                                    
                   3828: sub auto_new_course {
1.508     raeburn  3829:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3830:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3831:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3832:     return $response;
                   3833: }
                   3834:                                                                                    
                   3835: sub auto_validate_courseID {
1.508     raeburn  3836:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3837:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3838:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3839:     return $response;
                   3840: }
                   3841:                                                                                    
                   3842: sub auto_create_password {
1.508     raeburn  3843:     my ($cnum,$cdom,$authparam) = @_;
                   3844:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3845:     my $create_passwd = 0;
                   3846:     my $authchk = '';
1.511     raeburn  3847:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3848:     if ($response eq 'refused') {
                   3849:         $authchk = 'refused';
                   3850:     } else {
                   3851:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3852:     }
                   3853:     return ($authparam,$create_passwd,$authchk);
                   3854: }
                   3855: 
1.706     raeburn  3856: sub auto_photo_permission {
                   3857:     my ($cnum,$cdom,$students) = @_;
                   3858:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 3859:     my ($outcome,$perm_reqd,$conditions) = 
                   3860: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 3861:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3862: 	return (undef,undef);
                   3863:     }
1.706     raeburn  3864:     return ($outcome,$perm_reqd,$conditions);
                   3865: }
                   3866: 
                   3867: sub auto_checkphotos {
                   3868:     my ($uname,$udom,$pid) = @_;
                   3869:     my $homeserver = &homeserver($uname,$udom);
                   3870:     my ($result,$resulttype);
                   3871:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 3872: 				   &escape($uname).':'.&escape($pid),
                   3873: 				   $homeserver));
1.709     albertel 3874:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3875: 	return (undef,undef);
                   3876:     }
1.706     raeburn  3877:     if ($outcome) {
                   3878:         ($result,$resulttype) = split(/:/,$outcome);
                   3879:     } 
                   3880:     return ($result,$resulttype);
                   3881: }
                   3882: 
                   3883: sub auto_photochoice {
                   3884:     my ($cnum,$cdom) = @_;
                   3885:     my $homeserver = &homeserver($cnum,$cdom);
                   3886:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 3887: 						       &escape($cdom),
                   3888: 						       $homeserver)));
1.709     albertel 3889:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3890: 	return (undef,undef);
                   3891:     }
1.706     raeburn  3892:     return ($update,$comment);
                   3893: }
                   3894: 
                   3895: sub auto_photoupdate {
                   3896:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   3897:     my $homeserver = &homeserver($cnum,$dom);
                   3898:     my $host=$hostname{$homeserver};
                   3899:     my $cmd = '';
                   3900:     my $maxtries = 1;
                   3901:     foreach (keys %{$affiliatesref}) {
                   3902:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   3903:     }
                   3904:     $cmd =~ s/%%$//;
                   3905:     $cmd = &escape($cmd);
                   3906:     my $query = 'institutionalphotos';
                   3907:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   3908:     unless ($queryid=~/^\Q$host\E\_/) {
                   3909:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   3910:         return 'error: '.$queryid;
                   3911:     }
                   3912:     my $reply = &get_query_reply($queryid);
                   3913:     my $tries = 1;
                   3914:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3915:         $reply = &get_query_reply($queryid);
                   3916:         $tries ++;
                   3917:     }
                   3918:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   3919:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   3920:     } else {
                   3921:         my @responses = split(/:/,$reply);
                   3922:         my $outcome = shift(@responses); 
                   3923:         foreach my $item (@responses) {
                   3924:             my ($key,$value) = split(/=/,$item);
                   3925:             $$photo{$key} = $value;
                   3926:         }
                   3927:         return $outcome;
                   3928:     }
                   3929:     return 'error';
                   3930: }
                   3931: 
1.521     raeburn  3932: sub auto_instcode_format {
                   3933:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3934:     my $courses = '';
                   3935:     my $homeserver;
                   3936:     if ($caller eq 'global') {
1.584     raeburn  3937:         foreach my $tryserver (keys %libserv) {
                   3938:             if ($hostdom{$tryserver} eq $codedom) {
                   3939:                 $homeserver = $tryserver;
                   3940:                 last;
                   3941:             }
                   3942:         }
1.620     albertel 3943:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3944:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3945:         }
1.521     raeburn  3946:     } else {
                   3947:         $homeserver = &homeserver($caller,$codedom);
                   3948:     }
                   3949:     foreach (keys %{$instcodes}) {
                   3950:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3951:     }
                   3952:     chop($courses);
                   3953:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3954:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3955:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3956:         %{$codes} = &str2hash($codes_str);
                   3957:         @{$codetitles} = &str2array($codetitles_str);
                   3958:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3959:         %{$cat_order} = &str2hash($cat_order_str);
                   3960:         return 'ok';
                   3961:     }
                   3962:     return $response;
                   3963: }
                   3964: 
1.679     raeburn  3965: # ------------------------------------------------------- Course Group routines
                   3966: 
                   3967: sub get_coursegroups {
1.683     raeburn  3968:     my ($cdom,$cnum,$group) = @_;
                   3969:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  3970: }
                   3971: 
                   3972: sub modify_coursegroup {
                   3973:     my ($cdom,$cnum,$groupsettings) = @_;
                   3974:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   3975: }
                   3976: 
                   3977: sub modify_group_roles {
                   3978:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   3979:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   3980:     my $role = 'gr/'.&escape($userprivs);
                   3981:     my ($uname,$udom) = split(/:/,$user);
                   3982:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  3983:     if ($result eq 'ok') {
                   3984:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   3985:     }
                   3986: 
1.679     raeburn  3987:     return $result;
                   3988: }
                   3989: 
                   3990: sub modify_coursegroup_membership {
                   3991:     my ($cdom,$cnum,$membership) = @_;
                   3992:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   3993:     return $result;
                   3994: }
                   3995: 
1.682     raeburn  3996: sub get_active_groups {
                   3997:     my ($udom,$uname,$cdom,$cnum) = @_;
                   3998:     my $now = time;
                   3999:     my %groups = ();
                   4000:     foreach my $key (keys(%env)) {
                   4001:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4002:             my ($start,$end) = split(/\./,$env{$key});
                   4003:             if (($end!=0) && ($end<$now)) { next; }
                   4004:             if (($start!=0) && ($start>$now)) { next; }
                   4005:             if ($1 eq $cdom && $2 eq $cnum) {
                   4006:                 $groups{$3} = $env{$key} ;
                   4007:             }
                   4008:         }
                   4009:     }
                   4010:     return %groups;
                   4011: }
                   4012: 
1.683     raeburn  4013: sub get_group_membership {
                   4014:     my ($cdom,$cnum,$group) = @_;
                   4015:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4016: }
                   4017: 
                   4018: sub get_users_groups {
                   4019:     my ($udom,$uname,$courseid) = @_;
                   4020:     my $cachetime=1800;
                   4021:     $courseid=~s/\_/\//g;
                   4022:     $courseid=~s/^(\w)/\/$1/;
                   4023: 
                   4024:     my $hashid="$udom:$uname:$courseid";
                   4025:     my ($result,$cached)=&is_cached_new('getgroups',$hashid);
                   4026:     if (defined($cached)) { return $result; }
                   4027: 
                   4028:     my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4029:     my ($tmp) = keys(%roleshash);
                   4030:     if ($tmp=~/^error:/) {
                   4031:         &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4032:         return '';
                   4033:     } else {
                   4034:         my $grouplist;
                   4035:         foreach my $key (keys %roleshash) {
                   4036:             if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
1.727     raeburn  4037:                 unless ($roleshash{$key} =~ /_\d+_\-1$/) {   # deleted membership
1.683     raeburn  4038:                     $grouplist .= $1.':';
                   4039:                 }
                   4040:             }
                   4041:         }
                   4042:         $grouplist =~ s/:$//;
                   4043:         return &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
                   4044:     }
                   4045: }
                   4046: 
                   4047: sub devalidate_getgroups_cache {
                   4048:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4049:     my $courseid = $cdom.'_'.$cnum;
                   4050:     $courseid=~s/\_/\//g;
                   4051:     $courseid=~s/^(\w)/\/$1/;
                   4052:     my $hashid="$udom:$uname:$courseid";
                   4053:     &devalidate_cache_new('getgroups',$hashid);
                   4054: }
                   4055: 
1.12      www      4056: # ------------------------------------------------------------------ Plain Text
                   4057: 
                   4058: sub plaintext {
1.22      www      4059:     my $short=shift;
1.676     albertel 4060:     return &Apache::lonlocal::mt($prp{$short});
1.12      www      4061: }
                   4062: 
                   4063: # ----------------------------------------------------------------- Assign Role
                   4064: 
                   4065: sub assignrole {
1.357     www      4066:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4067:     my $mrole;
                   4068:     if ($role =~ /^cr\//) {
1.393     www      4069:         my $cwosec=$url;
                   4070:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4071: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4072:            &logthis('Refused custom assignrole: '.
                   4073:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4074: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4075:            return 'refused'; 
                   4076:         }
1.21      www      4077:         $mrole='cr';
1.678     raeburn  4078:     } elsif ($role =~ /^gr\//) {
                   4079:         my $cwogrp=$url;
                   4080:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4081:         unless (&allowed('mdg',$cwogrp)) {
                   4082:             &logthis('Refused group assignrole: '.
                   4083:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4084:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4085:             return 'refused';
                   4086:         }
                   4087:         $mrole='gr';
1.21      www      4088:     } else {
1.82      www      4089:         my $cwosec=$url;
1.83      www      4090:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4091:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4092:            &logthis('Refused assignrole: '.
                   4093:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4094: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4095:            return 'refused'; 
                   4096:         }
1.21      www      4097:         $mrole=$role;
                   4098:     }
1.620     albertel 4099:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4100:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4101:     if ($end) { $command.='_'.$end; }
1.21      www      4102:     if ($start) {
                   4103: 	if ($end) { 
1.81      www      4104:            $command.='_'.$start; 
1.21      www      4105:         } else {
1.81      www      4106:            $command.='_0_'.$start;
1.21      www      4107:         }
                   4108:     }
1.357     www      4109: # actually delete
                   4110:     if ($deleteflag) {
1.373     www      4111: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4112: # modify command to delete the role
1.620     albertel 4113:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4114:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4115: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4116: # set start and finish to negative values for userrolelog
                   4117:            $start=-1;
                   4118:            $end=-1;
                   4119:         }
                   4120:     }
                   4121: # send command
1.349     www      4122:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4123: # log new user role if status is ok
1.349     www      4124:     if ($answer eq 'ok') {
1.663     raeburn  4125: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.349     www      4126:     }
                   4127:     return $answer;
1.169     harris41 4128: }
                   4129: 
                   4130: # -------------------------------------------------- Modify user authentication
1.197     www      4131: # Overrides without validation
                   4132: 
1.169     harris41 4133: sub modifyuserauth {
                   4134:     my ($udom,$uname,$umode,$upass)=@_;
                   4135:     my $uhome=&homeserver($uname,$udom);
1.197     www      4136:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4137:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4138:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4139:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4140:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4141: 		     &escape($upass),$uhome);
1.620     albertel 4142:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4143:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4144:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4145:     &log($udom,,$uname,$uhome,
1.620     albertel 4146:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4147:                                      $env{'user.name'}.', '.$umode.
1.197     www      4148:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4149:     unless ($reply eq 'ok') {
1.197     www      4150:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4151: 	return 'error: '.$reply;
                   4152:     }   
1.170     harris41 4153:     return 'ok';
1.80      www      4154: }
                   4155: 
1.81      www      4156: # --------------------------------------------------------------- Modify a user
1.80      www      4157: 
1.81      www      4158: sub modifyuser {
1.206     matthew  4159:     my ($udom,    $uname, $uid,
                   4160:         $umode,   $upass, $first,
                   4161:         $middle,  $last,  $gene,
1.387     www      4162:         $forceid, $desiredhome, $email)=@_;
1.198     www      4163:     $udom=~s/\W//g;
                   4164:     $uname=~s/\W//g;
1.81      www      4165:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4166:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4167: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4168:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4169:                                      ' desiredhome not specified'). 
1.620     albertel 4170:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4171:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4172:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4173: # ----------------------------------------------------------------- Create User
1.406     albertel 4174:     if (($uhome eq 'no_host') && 
                   4175: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4176:         my $unhome='';
1.209     matthew  4177:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4178:             $unhome = $desiredhome;
1.620     albertel 4179: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4180: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4181:         } else { # load balancing routine for determining $unhome
1.80      www      4182:             my $tryserver;
1.81      www      4183:             my $loadm=10000000;
1.80      www      4184:             foreach $tryserver (keys %libserv) {
                   4185: 	       if ($hostdom{$tryserver} eq $udom) {
                   4186:                   my $answer=reply('load',$tryserver);
                   4187:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4188: 		      $loadm=$answer;
                   4189:                       $unhome=$tryserver;
                   4190:                   }
                   4191: 	       }
                   4192: 	    }
                   4193:         }
                   4194:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4195: 	    return 'error: unable to find a home server for '.$uname.
                   4196:                    ' in domain '.$udom;
1.80      www      4197:         }
                   4198:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4199:                          &escape($upass),$unhome);
                   4200: 	unless ($reply eq 'ok') {
                   4201:             return 'error: '.$reply;
                   4202:         }   
1.230     stredwic 4203:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4204:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4205: 	    return 'error: unable verify users home machine.';
1.80      www      4206:         }
1.209     matthew  4207:     }   # End of creation of new user
1.80      www      4208: # ---------------------------------------------------------------------- Add ID
                   4209:     if ($uid) {
                   4210:        $uid=~tr/A-Z/a-z/;
                   4211:        my %uidhash=&idrget($udom,$uname);
1.196     www      4212:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4213:          && (!$forceid)) {
1.80      www      4214: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4215: 	      return 'error: user id "'.$uid.'" does not match '.
                   4216:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4217:           }
                   4218:        } else {
                   4219: 	  &idput($udom,($uname => $uid));
                   4220:        }
                   4221:     }
                   4222: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4223:     my @tmp=&get('environment',
1.134     albertel 4224: 		   ['firstname','middlename','lastname','generation'],
                   4225: 		   $udom,$uname);
1.313     matthew  4226:     my %names;
                   4227:     if ($tmp[0] =~ m/^error:.*/) { 
                   4228:         %names=(); 
                   4229:     } else {
                   4230:         %names = @tmp;
                   4231:     }
1.388     www      4232: #
                   4233: # Make sure to not trash student environment if instructor does not bother
                   4234: # to supply name and email information
                   4235: #
                   4236:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4237:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4238:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4239:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4240:     if ($email) {
                   4241:        $email=~s/[^\w\@\.\-\,]//gs;
                   4242:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4243: 			   $names{'critnotification'} = $email;
                   4244: 			   $names{'permanentemail'} = $email; }
                   4245:     }
1.134     albertel 4246:     my $reply = &put('environment', \%names, $udom,$uname);
                   4247:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4248:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4249:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4250:              $umode.', '.$first.', '.$middle.', '.
                   4251: 	     $last.', '.$gene.' by '.
1.620     albertel 4252:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4253:     return 'ok';
1.80      www      4254: }
                   4255: 
1.81      www      4256: # -------------------------------------------------------------- Modify student
1.80      www      4257: 
1.81      www      4258: sub modifystudent {
                   4259:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4260:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4261:     if (!$cid) {
1.620     albertel 4262: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4263: 	    return 'not_in_class';
                   4264: 	}
1.80      www      4265:     }
                   4266: # --------------------------------------------------------------- Make the user
1.81      www      4267:     my $reply=&modifyuser
1.209     matthew  4268: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4269:          $desiredhome,$email);
1.80      www      4270:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4271:     # This will cause &modify_student_enrollment to get the uid from the
                   4272:     # students environment
                   4273:     $uid = undef if (!$forceid);
1.455     albertel 4274:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4275: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4276:     return $reply;
                   4277: }
                   4278: 
                   4279: sub modify_student_enrollment {
1.515     raeburn  4280:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4281:     my ($cdom,$cnum,$chome);
                   4282:     if (!$cid) {
1.620     albertel 4283: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4284: 	    return 'not_in_class';
                   4285: 	}
1.620     albertel 4286: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4287: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4288:     } else {
                   4289: 	($cdom,$cnum)=split(/_/,$cid);
                   4290:     }
1.620     albertel 4291:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4292:     if (!$chome) {
1.457     raeburn  4293: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4294:     }
1.455     albertel 4295:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4296:     # Make sure the user exists
1.81      www      4297:     my $uhome=&homeserver($uname,$udom);
                   4298:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4299: 	return 'error: no such user';
                   4300:     }
1.297     matthew  4301:     # Get student data if we were not given enough information
                   4302:     if (!defined($first)  || $first  eq '' || 
                   4303:         !defined($last)   || $last   eq '' || 
                   4304:         !defined($uid)    || $uid    eq '' || 
                   4305:         !defined($middle) || $middle eq '' || 
                   4306:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4307:         # They did not supply us with enough data to enroll the student, so
                   4308:         # we need to pick up more information.
1.297     matthew  4309:         my %tmp = &get('environment',
1.294     matthew  4310:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4311:                        ,$udom,$uname);
                   4312: 
1.455     albertel 4313:         #foreach (keys(%tmp)) {
                   4314:         #    &logthis("key $_ = ".$tmp{$_});
                   4315:         #}
1.294     matthew  4316:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4317:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4318:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4319:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4320:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4321:     }
1.556     albertel 4322:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4323:     my $reply=cput('classlist',
                   4324: 		   {"$uname:$udom" => 
1.515     raeburn  4325: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4326: 		   $cdom,$cnum);
1.81      www      4327:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4328: 	return 'error: '.$reply;
1.652     albertel 4329:     } else {
                   4330: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4331:     }
1.297     matthew  4332:     # Add student role to user
1.83      www      4333:     my $uurl='/'.$cid;
1.81      www      4334:     $uurl=~s/\_/\//g;
                   4335:     if ($usec) {
                   4336: 	$uurl.='/'.$usec;
                   4337:     }
                   4338:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4339: }
                   4340: 
1.556     albertel 4341: sub format_name {
                   4342:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4343:     my $name;
                   4344:     if ($first ne 'lastname') {
                   4345: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4346:     } else {
                   4347: 	if ($lastname=~/\S/) {
                   4348: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4349: 	    $name=~s/\s+,/,/;
                   4350: 	} else {
                   4351: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4352: 	}
                   4353:     }
                   4354:     $name=~s/^\s+//;
                   4355:     $name=~s/\s+$//;
                   4356:     $name=~s/\s+/ /g;
                   4357:     return $name;
                   4358: }
                   4359: 
1.84      www      4360: # ------------------------------------------------- Write to course preferences
                   4361: 
                   4362: sub writecoursepref {
                   4363:     my ($courseid,%prefs)=@_;
                   4364:     $courseid=~s/^\///;
                   4365:     $courseid=~s/\_/\//g;
                   4366:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4367:     my $chome=homeserver($cnum,$cdomain);
                   4368:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4369: 	return 'error: no such course';
                   4370:     }
                   4371:     my $cstring='';
1.191     harris41 4372:     foreach (keys %prefs) {
1.84      www      4373: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4374:     }
1.84      www      4375:     $cstring=~s/\&$//;
                   4376:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4377: }
                   4378: 
                   4379: # ---------------------------------------------------------- Make/modify course
                   4380: 
                   4381: sub createcourse {
1.571     raeburn  4382:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      4383:     $url=&declutter($url);
                   4384:     my $cid='';
1.264     matthew  4385:     unless (&allowed('ccc',$udom)) {
1.84      www      4386:         return 'refused';
                   4387:     }
                   4388: # ------------------------------------------------------------------- Create ID
1.674     www      4389:    my $uname=int(1+rand(9)).
                   4390:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4391:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4392:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4393: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4394:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4395:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4396:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4397:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4398:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4399:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4400:            return 'error: unable to generate unique course-ID';
                   4401:        } 
                   4402:    }
1.264     matthew  4403: # ------------------------------------------------ Check supplied server name
1.620     albertel 4404:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4405:     if (! exists($libserv{$course_server})) {
                   4406:         return 'error:bad server name '.$course_server;
                   4407:     }
1.84      www      4408: # ------------------------------------------------------------- Make the course
                   4409:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4410:                       $course_server);
1.84      www      4411:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4412:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4413:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4414: 	return 'error: no such course';
                   4415:     }
1.271     www      4416: # ----------------------------------------------------------------- Course made
1.516     raeburn  4417: # log existence
                   4418:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  4419:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      4420:     &flushcourselogs();
                   4421: # set toplevel url
1.271     www      4422:     my $topurl=$url;
                   4423:     unless ($nonstandard) {
                   4424: # ------------------------------------------ For standard courses, make top url
                   4425:         my $mapurl=&clutter($url);
1.278     www      4426:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4427:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4428: <map>
                   4429: <resource id="1" type="start"></resource>
                   4430: <resource id="2" src="$mapurl"></resource>
                   4431: <resource id="3" type="finish"></resource>
                   4432: <link index="1" from="1" to="2"></link>
                   4433: <link index="2" from="2" to="3"></link>
                   4434: </map>
                   4435: ENDINITMAP
                   4436:         $topurl=&declutter(
1.638     albertel 4437:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4438:                           );
                   4439:     }
                   4440: # ----------------------------------------------------------- Write preferences
1.84      www      4441:     &writecoursepref($udom.'_'.$uname,
                   4442:                      ('description' => $description,
1.271     www      4443:                       'url'         => $topurl));
1.84      www      4444:     return '/'.$udom.'/'.$uname;
                   4445: }
                   4446: 
1.21      www      4447: # ---------------------------------------------------------- Assign Custom Role
                   4448: 
                   4449: sub assigncustomrole {
1.357     www      4450:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4451:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4452:                        $end,$start,$deleteflag);
1.21      www      4453: }
                   4454: 
                   4455: # ----------------------------------------------------------------- Revoke Role
                   4456: 
                   4457: sub revokerole {
1.357     www      4458:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4459:     my $now=time;
1.357     www      4460:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4461: }
                   4462: 
                   4463: # ---------------------------------------------------------- Revoke Custom Role
                   4464: 
                   4465: sub revokecustomrole {
1.357     www      4466:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4467:     my $now=time;
1.357     www      4468:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4469:            $deleteflag);
1.17      www      4470: }
                   4471: 
1.533     banghart 4472: # ------------------------------------------------------------ Disk usage
1.535     albertel 4473: sub diskusage {
1.533     banghart 4474:     my ($udom,$uname,$directoryRoot)=@_;
                   4475:     $directoryRoot =~ s/\/$//;
1.535     albertel 4476:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4477:     return $listing;
1.512     banghart 4478: }
                   4479: 
1.566     banghart 4480: sub is_locked {
                   4481:     my ($file_name, $domain, $user) = @_;
                   4482:     my @check;
                   4483:     my $is_locked;
                   4484:     push @check, $file_name;
1.613     albertel 4485:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4486: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4487:     my ($tmp)=keys(%locked);
                   4488:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 4489: 
1.566     banghart 4490:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   4491:         $is_locked = 'true';
                   4492:     } else {
                   4493:         $is_locked = 'false';
                   4494:     }
                   4495: }
                   4496: 
1.559     banghart 4497: # ------------------------------------------------------------- Mark as Read Only
                   4498: 
                   4499: sub mark_as_readonly {
                   4500:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4501:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4502:     my ($tmp)=keys(%current_permissions);
                   4503:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4504:     foreach my $file (@{$files}) {
1.561     banghart 4505:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4506:     }
1.613     albertel 4507:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4508:     return;
                   4509: }
                   4510: 
1.572     banghart 4511: # ------------------------------------------------------------Save Selected Files
                   4512: 
                   4513: sub save_selected_files {
                   4514:     my ($user, $path, @files) = @_;
                   4515:     my $filename = $user."savedfiles";
1.573     banghart 4516:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4517:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4518:     foreach my $file (@files) {
1.620     albertel 4519:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4520:     }
                   4521:     foreach my $file (@other_files) {
1.574     banghart 4522:         print (OUT $file."\n");
1.572     banghart 4523:     }
1.574     banghart 4524:     close (OUT);
1.572     banghart 4525:     return 'ok';
                   4526: }
                   4527: 
1.574     banghart 4528: sub clear_selected_files {
                   4529:     my ($user) = @_;
                   4530:     my $filename = $user."savedfiles";
                   4531:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4532:     print (OUT undef);
                   4533:     close (OUT);
                   4534:     return ("ok");    
                   4535: }
                   4536: 
1.572     banghart 4537: sub files_in_path {
                   4538:     my ($user, $path) = @_;
                   4539:     my $filename = $user."savedfiles";
                   4540:     my %return_files;
1.574     banghart 4541:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4542:     while (my $line_in = <IN>) {
1.574     banghart 4543:         chomp ($line_in);
                   4544:         my @paths_and_file = split (m!/!, $line_in);
                   4545:         my $file_part = pop (@paths_and_file);
                   4546:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4547:         $path_part.='/';
                   4548:         my $path_and_file = $path_part.$file_part;
                   4549:         if ($path_part eq $path) {
                   4550:             $return_files{$file_part}= 'selected';
                   4551:         }
                   4552:     }
1.574     banghart 4553:     close (IN);
                   4554:     return (\%return_files);
1.572     banghart 4555: }
                   4556: 
                   4557: # called in portfolio select mode, to show files selected NOT in current directory
                   4558: sub files_not_in_path {
                   4559:     my ($user, $path) = @_;
                   4560:     my $filename = $user."savedfiles";
                   4561:     my @return_files;
                   4562:     my $path_part;
1.574     banghart 4563:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4564:     while (<IN>) {
                   4565:         #ok, I know it's clunky, but I want it to work
                   4566:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4567:         my $file_part = pop (@paths_and_file);
                   4568:         chomp ($file_part);
                   4569:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4570:         $path_part .= '/';
                   4571:         my $path_and_file = $path_part.$file_part;
                   4572:         if ($path_part ne $path) {
1.574     banghart 4573:             push (@return_files, ($path_and_file));
1.572     banghart 4574:         }
                   4575:     }
1.574     banghart 4576:     close (OUT);
                   4577:     return (@return_files);
1.572     banghart 4578: }
                   4579: 
1.561     banghart 4580: #--------------------------------------------------------------Get Marked as Read Only
                   4581: 
1.629     banghart 4582: 
1.561     banghart 4583: sub get_marked_as_readonly {
                   4584:     my ($domain,$user,$what) = @_;
1.613     albertel 4585:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4586:     my ($tmp)=keys(%current_permissions);
                   4587:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563     banghart 4588:     my @readonly_files;
1.629     banghart 4589:     my $cmp1=$what;
                   4590:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.563     banghart 4591:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 4592:         if (ref($value) eq "ARRAY"){
                   4593:             foreach my $stored_what (@{$value}) {
1.629     banghart 4594:                 my $cmp2=$stored_what;
                   4595:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
                   4596:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4597:                     push(@readonly_files, $file_name);
1.563     banghart 4598:                 } elsif (!defined($what)) {
                   4599:                     push(@readonly_files, $file_name);
1.561     banghart 4600:                 }
                   4601:             }
                   4602:         } 
                   4603:     }
                   4604:     return @readonly_files;
                   4605: }
1.577     banghart 4606: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4607: 
1.577     banghart 4608: sub get_marked_as_readonly_hash {
                   4609:     my ($domain,$user,$what) = @_;
1.613     albertel 4610:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4611:     my ($tmp)=keys(%current_permissions);
                   4612:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4613: 
1.577     banghart 4614:     my %readonly_files;
                   4615:     while (my ($file_name,$value) = each(%current_permissions)) {
                   4616:         if (ref($value) eq "ARRAY"){
                   4617:             foreach my $stored_what (@{$value}) {
                   4618:                 if ($stored_what eq $what) {
                   4619:                     $readonly_files{$file_name} = 'locked';
                   4620:                 } elsif (!defined($what)) {
                   4621:                     $readonly_files{$file_name} = 'locked';
                   4622:                 }
                   4623:             }
                   4624:         } 
                   4625:     }
                   4626:     return %readonly_files;
                   4627: }
1.559     banghart 4628: # ------------------------------------------------------------ Unmark as Read Only
                   4629: 
                   4630: sub unmark_as_readonly {
1.629     banghart 4631:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4632:     # for portfolio submissions, $what contains [$symb,$crsid] 
                   4633:     my ($domain,$user,$what,$file_name) = @_;
1.634     albertel 4634:     my $symb_crs = $what;
                   4635:     if (ref($what)) { $symb_crs=join('',@$what); }
1.613     albertel 4636:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4637:     my ($tmp)=keys(%current_permissions);
                   4638:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4639:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.650     albertel 4640:     foreach my $file (@readonly_files) {
                   4641: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4642: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4643:         my @new_locks;
                   4644:         my @del_keys;
                   4645:         if (ref($current_locks) eq "ARRAY"){
                   4646:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4647:                 my $compare=$locker;
                   4648:                 if (ref($locker)) { $compare=join('',@{$locker}) };
1.650     albertel 4649:                 if ($compare ne $symb_crs) {
                   4650:                     push(@new_locks, $locker);
1.563     banghart 4651:                 }
                   4652:             }
1.650     albertel 4653:             if (scalar(@new_locks) > 0) {
1.563     banghart 4654:                 $current_permissions{$file} = \@new_locks;
                   4655:             } else {
                   4656:                 push(@del_keys, $file);
1.613     albertel 4657:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4658:                 delete($current_permissions{$file});
1.563     banghart 4659:             }
                   4660:         }
1.561     banghart 4661:     }
1.613     albertel 4662:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4663:     return;
                   4664: }
1.512     banghart 4665: 
1.17      www      4666: # ------------------------------------------------------------ Directory lister
                   4667: 
                   4668: sub dirlist {
1.253     stredwic 4669:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4670: 
1.18      www      4671:     $uri=~s/^\///;
                   4672:     $uri=~s/\/$//;
1.253     stredwic 4673:     my ($udom, $uname);
                   4674:     (undef,$udom,$uname)=split(/\//,$uri);
                   4675:     if(defined($userdomain)) {
                   4676:         $udom = $userdomain;
                   4677:     }
                   4678:     if(defined($username)) {
                   4679:         $uname = $username;
                   4680:     }
                   4681: 
                   4682:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4683:     if(defined($alternateDirectoryRoot)) {
                   4684:         $dirRoot = $alternateDirectoryRoot;
                   4685:         $dirRoot =~ s/\/$//;
                   4686:     }
                   4687: 
                   4688:     if($udom) {
                   4689:         if($uname) {
1.605     matthew  4690:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4691:                               homeserver($uname,$udom));
1.605     matthew  4692:             my @listing_results;
                   4693:             if ($listing eq 'unknown_cmd') {
                   4694:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4695:                                homeserver($uname,$udom));
                   4696:                 @listing_results = split(/:/,$listing);
                   4697:             } else {
                   4698:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4699:             }
                   4700:             return @listing_results;
1.253     stredwic 4701:         } elsif(!defined($alternateDirectoryRoot)) {
                   4702:             my $tryserver;
                   4703:             my %allusers=();
                   4704:             foreach $tryserver (keys %libserv) {
                   4705:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4706:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4707:                                       $udom, $tryserver);
1.605     matthew  4708:                     my @listing_results;
                   4709:                     if ($listing eq 'unknown_cmd') {
                   4710:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4711:                                        $udom, $tryserver);
                   4712:                         @listing_results = split(/:/,$listing);
                   4713:                     } else {
                   4714:                         @listing_results =
                   4715:                             map { &unescape($_); } split(/:/,$listing);
                   4716:                     }
                   4717:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4718:                         $listing_results[0] ne 'empty'       &&
                   4719:                         $listing_results[0] ne 'con_lost') {
                   4720:                         foreach (@listing_results) {
1.253     stredwic 4721:                             my ($entry,@stat)=split(/&/,$_);
                   4722:                             $allusers{$entry}=1;
                   4723:                         }
                   4724:                     }
1.191     harris41 4725:                 }
1.253     stredwic 4726:             }
                   4727:             my $alluserstr='';
                   4728:             foreach (sort keys %allusers) {
                   4729:                 $alluserstr.=$_.'&user:';
                   4730:             }
                   4731:             $alluserstr=~s/:$//;
                   4732:             return split(/:/,$alluserstr);
                   4733:         } else {
                   4734:             my @emptyResults = ();
                   4735:             push(@emptyResults, 'missing user name');
                   4736:             return split(':',@emptyResults);
                   4737:         }
                   4738:     } elsif(!defined($alternateDirectoryRoot)) {
                   4739:         my $tryserver;
                   4740:         my %alldom=();
                   4741:         foreach $tryserver (keys %libserv) {
                   4742:             $alldom{$hostdom{$tryserver}}=1;
                   4743:         }
                   4744:         my $alldomstr='';
                   4745:         foreach (sort keys %alldom) {
1.397     albertel 4746:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4747:         }
                   4748:         $alldomstr=~s/:$//;
                   4749:         return split(/:/,$alldomstr);       
                   4750:     } else {
                   4751:         my @emptyResults = ();
                   4752:         push(@emptyResults, 'missing domain');
                   4753:         return split(':',@emptyResults);
1.275     stredwic 4754:     }
                   4755: }
                   4756: 
                   4757: # --------------------------------------------- GetFileTimestamp
                   4758: # This function utilizes dirlist and returns the date stamp for
                   4759: # when it was last modified.  It will also return an error of -1
                   4760: # if an error occurs
                   4761: 
1.410     matthew  4762: ##
                   4763: ## FIXME: This subroutine assumes its caller knows something about the
                   4764: ## directory structure of the home server for the student ($root).
                   4765: ## Not a good assumption to make.  Since this is for looking up files
                   4766: ## in user directories, the full path should be constructed by lond, not
                   4767: ## whatever machine we request data from.
                   4768: ##
1.275     stredwic 4769: sub GetFileTimestamp {
                   4770:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4771:     $studentDomain=~s/\W//g;
                   4772:     $studentName=~s/\W//g;
                   4773:     my $subdir=$studentName.'__';
                   4774:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4775:     my $proname="$studentDomain/$subdir/$studentName";
                   4776:     $proname .= '/'.$filename;
1.375     matthew  4777:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4778:                                               $studentName, $root);
1.275     stredwic 4779:     my @stats = split('&', $fileStat);
                   4780:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4781:         # @stats contains first the filename, then the stat output
                   4782:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4783:     } else {
                   4784:         return -1;
1.253     stredwic 4785:     }
1.26      www      4786: }
                   4787: 
1.712     albertel 4788: sub stat_file {
                   4789:     my ($uri) = @_;
1.722     albertel 4790:     $uri = &clutter($uri);
                   4791: 
                   4792:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 4793:     if ($uri =~ m-^/adm/-) {
                   4794: 	$uri=~s-^/adm/wrapper/-/-;
                   4795: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 4796:     }
1.712     albertel 4797:     my ($udom,$uname,$file,$dir);
                   4798:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   4799: 	($udom,$uname,$file) =
                   4800: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   4801: 	$file = 'userfiles/'.$file;
                   4802: 	$dir = &Apache::loncommon::propath($udom,$uname);
                   4803:     }
                   4804:     if ($uri =~ m-^/res/-) {
                   4805: 	($udom,$uname) = 
                   4806: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   4807: 	$file = $uri;
                   4808:     }
                   4809: 
                   4810:     if (!$udom || !$uname || !$file) {
                   4811: 	# unable to handle the uri
                   4812: 	return ();
                   4813:     }
                   4814: 
                   4815:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   4816:     my @stats = split('&', $result);
1.721     banghart 4817:     
1.712     albertel 4818:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   4819: 	shift(@stats); #filename is first
                   4820: 	return @stats;
                   4821:     }
                   4822:     return ();
                   4823: }
                   4824: 
1.26      www      4825: # -------------------------------------------------------- Value of a Condition
                   4826: 
1.713     albertel 4827: # gets the value of a specific preevaluated condition
                   4828: #    stored in the string  $env{user.state.<cid>}
                   4829: # or looks up a condition reference in the bighash and if if hasn't
                   4830: # already been evaluated recurses into docondval to get the value of
                   4831: # the condition, then memoizing it to 
                   4832: #   $env{user.state.<cid>.<condition>}
1.40      www      4833: sub directcondval {
                   4834:     my $number=shift;
1.620     albertel 4835:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4836: 	&Apache::lonuserstate::evalstate();
                   4837:     }
1.713     albertel 4838:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   4839: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   4840:     } elsif ($number =~ /^_/) {
                   4841: 	my $sub_condition;
                   4842: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   4843: 		&GDBM_READER(),0640)) {
                   4844: 	    $sub_condition=$bighash{'conditions'.$number};
                   4845: 	    untie(%bighash);
                   4846: 	}
                   4847: 	my $value = &docondval($sub_condition);
                   4848: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   4849: 	return $value;
                   4850:     }
1.620     albertel 4851:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4852:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4853:     } else {
                   4854:        return 2;
                   4855:     }
                   4856: }
                   4857: 
1.713     albertel 4858: # get the collection of conditions for this resource
1.26      www      4859: sub condval {
                   4860:     my $condidx=shift;
1.54      www      4861:     my $allpathcond='';
1.713     albertel 4862:     foreach my $cond (split(/\|/,$condidx)) {
                   4863: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   4864: 	    $allpathcond.=
                   4865: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   4866: 	}
1.191     harris41 4867:     }
1.54      www      4868:     $allpathcond=~s/\|$//;
1.713     albertel 4869:     return &docondval($allpathcond);
                   4870: }
                   4871: 
                   4872: #evaluates an expression of conditions
                   4873: sub docondval {
                   4874:     my ($allpathcond) = @_;
                   4875:     my $result=0;
                   4876:     if ($env{'request.course.id'}
                   4877: 	&& defined($allpathcond)) {
                   4878: 	my $operand='|';
                   4879: 	my @stack;
                   4880: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   4881: 	    if ($chunk eq '(') {
                   4882: 		push @stack,($operand,$result);
                   4883: 	    } elsif ($chunk eq ')') {
                   4884: 		my $before=pop @stack;
                   4885: 		if (pop @stack eq '&') {
                   4886: 		    $result=$result>$before?$before:$result;
                   4887: 		} else {
                   4888: 		    $result=$result>$before?$result:$before;
                   4889: 		}
                   4890: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   4891: 		$operand=$chunk;
                   4892: 	    } else {
                   4893: 		my $new=directcondval($chunk);
                   4894: 		if ($operand eq '&') {
                   4895: 		    $result=$result>$new?$new:$result;
                   4896: 		} else {
                   4897: 		    $result=$result>$new?$result:$new;
                   4898: 		}
                   4899: 	    }
                   4900: 	}
1.26      www      4901:     }
                   4902:     return $result;
1.421     albertel 4903: }
                   4904: 
                   4905: # ---------------------------------------------------- Devalidate courseresdata
                   4906: 
                   4907: sub devalidatecourseresdata {
                   4908:     my ($coursenum,$coursedomain)=@_;
                   4909:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4910:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4911: }
                   4912: 
1.200     www      4913: # --------------------------------------------------- Course Resourcedata Query
                   4914: 
1.624     albertel 4915: sub get_courseresdata {
                   4916:     my ($coursenum,$coursedomain)=@_;
1.200     www      4917:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4918:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4919:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4920:     my %dumpreply;
1.417     albertel 4921:     unless (defined($cached)) {
1.624     albertel 4922: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4923: 	$result=\%dumpreply;
1.251     albertel 4924: 	my ($tmp) = keys(%dumpreply);
                   4925: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4926: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4927: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4928: 	    return $tmp;
1.416     albertel 4929: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4930: 	    $result=undef;
1.599     albertel 4931: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4932: 	}
                   4933:     }
1.624     albertel 4934:     return $result;
                   4935: }
                   4936: 
1.633     albertel 4937: sub devalidateuserresdata {
                   4938:     my ($uname,$udom)=@_;
                   4939:     my $hashid="$udom:$uname";
                   4940:     &devalidate_cache_new('userres',$hashid);
                   4941: }
                   4942: 
1.624     albertel 4943: sub get_userresdata {
                   4944:     my ($uname,$udom)=@_;
                   4945:     #most student don\'t have any data set, check if there is some data
                   4946:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4947: 
                   4948:     my $hashid="$udom:$uname";
                   4949:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4950:     if (!defined($cached)) {
                   4951: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4952: 	$result=\%resourcedata;
                   4953: 	&do_cache_new('userres',$hashid,$result,600);
                   4954:     }
                   4955:     my ($tmp)=keys(%$result);
                   4956:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4957: 	return $result;
                   4958:     }
                   4959:     #error 2 occurs when the .db doesn't exist
                   4960:     if ($tmp!~/error: 2 /) {
1.672     albertel 4961: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 4962: 		 " Trying to get resource data for ".
                   4963: 		 $uname." at ".$udom.": ".
                   4964: 		 $tmp."</font>");
                   4965:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 4966: 	#&EXT_cache_set($udom,$uname);
                   4967: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 4968: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 4969:     }
                   4970:     return $tmp;
                   4971: }
                   4972: 
                   4973: sub resdata {
                   4974:     my ($name,$domain,$type,@which)=@_;
                   4975:     my $result;
                   4976:     if ($type eq 'course') {
                   4977: 	$result=&get_courseresdata($name,$domain);
                   4978:     } elsif ($type eq 'user') {
                   4979: 	$result=&get_userresdata($name,$domain);
                   4980:     }
                   4981:     if (!ref($result)) { return $result; }    
1.251     albertel 4982:     foreach my $item (@which) {
1.417     albertel 4983: 	if (defined($result->{$item})) {
                   4984: 	    return $result->{$item};
1.251     albertel 4985: 	}
1.250     albertel 4986:     }
1.291     albertel 4987:     return undef;
1.200     www      4988: }
                   4989: 
1.379     matthew  4990: #
                   4991: # EXT resource caching routines
                   4992: #
                   4993: 
                   4994: sub clear_EXT_cache_status {
1.383     albertel 4995:     &delenv('cache.EXT.');
1.379     matthew  4996: }
                   4997: 
                   4998: sub EXT_cache_status {
                   4999:     my ($target_domain,$target_user) = @_;
1.383     albertel 5000:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5001:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5002:         # We know already the user has no data
                   5003:         return 1;
                   5004:     } else {
                   5005:         return 0;
                   5006:     }
                   5007: }
                   5008: 
                   5009: sub EXT_cache_set {
                   5010:     my ($target_domain,$target_user) = @_;
1.383     albertel 5011:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5012:     #&appenv($cachename => time);
1.379     matthew  5013: }
                   5014: 
1.28      www      5015: # --------------------------------------------------------- Value of a Variable
1.58      www      5016: sub EXT {
1.715     albertel 5017: 
1.395     albertel 5018:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5019:     unless ($varname) { return ''; }
1.218     albertel 5020:     #get real user name/domain, courseid and symb
                   5021:     my $courseid;
1.359     albertel 5022:     my $publicuser;
1.427     www      5023:     if ($symbparm) {
                   5024: 	$symbparm=&get_symb_from_alias($symbparm);
                   5025:     }
1.218     albertel 5026:     if (!($uname && $udom)) {
1.360     albertel 5027:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5028: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5029:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5030:     } else {
1.620     albertel 5031: 	$courseid=$env{'request.course.id'};
1.218     albertel 5032:     }
1.48      www      5033:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5034:     my $rest;
1.320     albertel 5035:     if (defined($therest[0])) {
1.48      www      5036:        $rest=join('.',@therest);
                   5037:     } else {
                   5038:        $rest='';
                   5039:     }
1.320     albertel 5040: 
1.57      www      5041:     my $qualifierrest=$qualifier;
                   5042:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5043:     my $spacequalifierrest=$space;
                   5044:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5045:     if ($realm eq 'user') {
1.48      www      5046: # --------------------------------------------------------------- user.resource
                   5047: 	if ($space eq 'resource') {
1.651     albertel 5048: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5049: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5050: 		 &&
                   5051: 		 ($symbparm eq &symbread()) ) {
1.335     albertel 5052: 		return $Apache::lonhomework::history{$qualifierrest};
                   5053: 	    } else {
1.359     albertel 5054: 		my %restored;
1.620     albertel 5055: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5056: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5057: 		} else {
                   5058: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5059: 		}
1.335     albertel 5060: 		return $restored{$qualifierrest};
                   5061: 	    }
1.48      www      5062: # ----------------------------------------------------------------- user.access
                   5063:         } elsif ($space eq 'access') {
1.218     albertel 5064: 	    # FIXME - not supporting calls for a specific user
1.48      www      5065:             return &allowed($qualifier,$rest);
                   5066: # ------------------------------------------ user.preferences, user.environment
                   5067:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5068: 	    if (($uname eq $env{'user.name'}) &&
                   5069: 		($udom eq $env{'user.domain'})) {
                   5070: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5071: 	    } else {
1.359     albertel 5072: 		my %returnhash;
                   5073: 		if (!$publicuser) {
                   5074: 		    %returnhash=&userenvironment($udom,$uname,
                   5075: 						 $qualifierrest);
                   5076: 		}
1.218     albertel 5077: 		return $returnhash{$qualifierrest};
                   5078: 	    }
1.48      www      5079: # ----------------------------------------------------------------- user.course
                   5080:         } elsif ($space eq 'course') {
1.218     albertel 5081: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5082:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5083: # ------------------------------------------------------------------- user.role
                   5084:         } elsif ($space eq 'role') {
1.218     albertel 5085: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5086:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5087:             if ($qualifier eq 'value') {
                   5088: 		return $role;
                   5089:             } elsif ($qualifier eq 'extent') {
                   5090:                 return $where;
                   5091:             }
                   5092: # ----------------------------------------------------------------- user.domain
                   5093:         } elsif ($space eq 'domain') {
1.218     albertel 5094:             return $udom;
1.48      www      5095: # ------------------------------------------------------------------- user.name
                   5096:         } elsif ($space eq 'name') {
1.218     albertel 5097:             return $uname;
1.48      www      5098: # ---------------------------------------------------- Any other user namespace
1.29      www      5099:         } else {
1.359     albertel 5100: 	    my %reply;
                   5101: 	    if (!$publicuser) {
                   5102: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5103: 	    }
                   5104: 	    return $reply{$qualifierrest};
1.48      www      5105:         }
1.236     www      5106:     } elsif ($realm eq 'query') {
                   5107: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5108:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5109: 						[$spacequalifierrest]);
1.620     albertel 5110: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5111:    } elsif ($realm eq 'request') {
1.48      www      5112: # ------------------------------------------------------------- request.browser
                   5113:         if ($space eq 'browser') {
1.430     www      5114: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5115: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5116: 		    return 1;
                   5117: 		} else {
                   5118: 		    return 0;
                   5119: 		}
                   5120: 	    } else {
1.620     albertel 5121: 		return $env{'browser.'.$qualifier};
1.430     www      5122: 	    }
1.57      www      5123: # ------------------------------------------------------------ request.filename
                   5124:         } else {
1.620     albertel 5125:             return $env{'request.'.$spacequalifierrest};
1.29      www      5126:         }
1.28      www      5127:     } elsif ($realm eq 'course') {
1.48      www      5128: # ---------------------------------------------------------- course.description
1.620     albertel 5129:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5130:     } elsif ($realm eq 'resource') {
1.165     www      5131: 
1.620     albertel 5132: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5133: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5134: 	}
1.693     albertel 5135: 
                   5136: 	if ($space eq 'title') {
                   5137: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5138: 	    return &gettitle($symbparm);
                   5139: 	}
                   5140: 	
                   5141: 	if ($space eq 'map') {
                   5142: 	    my ($map) = &decode_symb($symbparm);
                   5143: 	    return &symbread($map);
                   5144: 	}
                   5145: 
                   5146: 	my ($section, $group, @groups);
1.593     albertel 5147: 	my ($courselevelm,$courselevel);
1.539     albertel 5148: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5149: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5150: 
1.218     albertel 5151: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5152: 
1.60      www      5153: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5154: 	    my $symbp=$symbparm;
1.409     www      5155: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 5156: 
                   5157: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5158: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5159: 
1.620     albertel 5160: 	    if (($env{'user.name'} eq $uname) &&
                   5161: 		($env{'user.domain'} eq $udom)) {
                   5162: 		$section=$env{'request.course.sec'};
1.691     raeburn  5163:                 @groups=&sort_course_groups($env{'request.course.groups'},$courseid); 
1.218     albertel 5164: 	    } else {
1.539     albertel 5165: 		if (! defined($usection)) {
1.551     albertel 5166: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5167: 		} else {
                   5168: 		    $section = $usection;
                   5169: 		}
1.684     raeburn  5170:                 my $grouplist = &get_users_groups($udom,$uname,$courseid);
                   5171:                 if ($grouplist) {
1.691     raeburn  5172:                     @groups=&sort_course_groups($grouplist,$courseid);
1.684     raeburn  5173:                 }
1.218     albertel 5174: 	    }
                   5175: 
                   5176: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5177: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5178: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5179: 
1.593     albertel 5180: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5181: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5182: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5183: 
1.60      www      5184: # ----------------------------------------------------------- first, check user
1.624     albertel 5185: 
                   5186: 	    my $userreply=&resdata($uname,$udom,'user',
                   5187: 				       ($courselevelr,$courselevelm,
                   5188: 					$courselevel));
                   5189: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5190: 
1.594     albertel 5191: # ------------------------------------------------ second, check some of course
1.684     raeburn  5192:             my $coursereply;
1.691     raeburn  5193:             if (@groups > 0) {
                   5194:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5195:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5196:                 if (defined($coursereply)) { return $coursereply; }
                   5197:             }
1.96      www      5198: 
1.684     raeburn  5199: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5200: 				     $env{'course.'.$courseid.'.domain'},
                   5201: 				     'course',
                   5202: 				     ($seclevelr,$seclevelm,$seclevel,
                   5203: 				      $courselevelr));
1.287     albertel 5204: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5205: 
1.60      www      5206: # ------------------------------------------------------ third, check map parms
1.218     albertel 5207: 	    my %parmhash=();
                   5208: 	    my $thisparm='';
                   5209: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5210: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5211: 		    &GDBM_READER(),0640)) {
1.218     albertel 5212: 		$thisparm=$parmhash{$symbparm};
                   5213: 		untie(%parmhash);
                   5214: 	    }
                   5215: 	    if ($thisparm) { return $thisparm; }
                   5216: 	}
1.594     albertel 5217: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5218: 
1.218     albertel 5219: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5220: 	my $filename;
                   5221: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5222: 	if ($symbparm) {
1.409     www      5223: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5224: 	} else {
1.620     albertel 5225: 	    $filename=$env{'request.filename'};
1.282     albertel 5226: 	}
                   5227: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5228: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5229: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5230: 	if (defined($metadata)) { return $metadata; }
1.142     www      5231: 
1.594     albertel 5232: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5233: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5234: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5235: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5236: 				     $env{'course.'.$courseid.'.domain'},
                   5237: 				     'course',
                   5238: 				     ($courselevelm,$courselevel));
1.593     albertel 5239: 	    if (defined($coursereply)) { return $coursereply; }
                   5240: 	}
1.145     www      5241: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5242: 	unless ($space eq '0') {
1.336     albertel 5243: 	    my @parts=split(/_/,$space);
                   5244: 	    my $id=pop(@parts);
                   5245: 	    my $part=join('_',@parts);
                   5246: 	    if ($part eq '') { $part='0'; }
                   5247: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5248: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5249: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5250: 	}
1.395     albertel 5251: 	if ($recurse) { return undef; }
                   5252: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5253: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5254: 
1.48      www      5255: # ---------------------------------------------------- Any other user namespace
                   5256:     } elsif ($realm eq 'environment') {
                   5257: # ----------------------------------------------------------------- environment
1.620     albertel 5258: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5259: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5260: 	} else {
                   5261: 	    my %returnhash=&userenvironment($udom,$uname,
                   5262: 					    $spacequalifierrest);
                   5263: 	    return $returnhash{$spacequalifierrest};
                   5264: 	}
1.28      www      5265:     } elsif ($realm eq 'system') {
1.48      www      5266: # ----------------------------------------------------------------- system.time
                   5267: 	if ($space eq 'time') {
                   5268: 	    return time;
                   5269:         }
1.696     albertel 5270:     } elsif ($realm eq 'server') {
                   5271: # ----------------------------------------------------------------- system.time
                   5272: 	if ($space eq 'name') {
                   5273: 	    return $ENV{'SERVER_NAME'};
                   5274:         }
1.28      www      5275:     }
1.48      www      5276:     return '';
1.61      www      5277: }
                   5278: 
1.691     raeburn  5279: sub check_group_parms {
                   5280:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5281:     my @groupitems = ();
                   5282:     my $resultitem;
                   5283:     my @levels = ($symbparm,$mapparm,$what);
                   5284:     foreach my $group (@{$groups}) {
                   5285:         foreach my $level (@levels) {
                   5286:              my $item = $courseid.'.['.$group.'].'.$level;
                   5287:              push(@groupitems,$item);
                   5288:         }
                   5289:     }
                   5290:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5291:                             $env{'course.'.$courseid.'.domain'},
                   5292:                                      'course',@groupitems);
                   5293:     return $coursereply;
                   5294: }
                   5295: 
                   5296: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
                   5297:     my ($grouplist,$courseid) = @_;
1.720     albertel 5298:     my @groups = sort(split(/:/,$grouplist));
1.691     raeburn  5299:     return @groups;
                   5300: }
                   5301: 
1.395     albertel 5302: sub packages_tab_default {
                   5303:     my ($uri,$varname)=@_;
                   5304:     my (undef,$part,$name)=split(/\./,$varname);
                   5305:     my $packages=&metadata($uri,'packages');
                   5306:     foreach my $package (split(/,/,$packages)) {
                   5307: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 5308: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5309: 	    return $packagetab{"$pack_type&$name&default"};
                   5310: 	}
1.585     albertel 5311: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5312: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5313: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5314: 	}
                   5315:     }
                   5316:     return undef;
                   5317: }
                   5318: 
1.334     albertel 5319: sub add_prefix_and_part {
                   5320:     my ($prefix,$part)=@_;
                   5321:     my $keyroot;
                   5322:     if (defined($prefix) && $prefix !~ /^__/) {
                   5323: 	# prefix that has a part already
                   5324: 	$keyroot=$prefix;
                   5325:     } elsif (defined($prefix)) {
                   5326: 	# prefix that is missing a part
                   5327: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5328:     } else {
                   5329: 	# no prefix at all
                   5330: 	if (defined($part)) { $keyroot='_'.$part; }
                   5331:     }
                   5332:     return $keyroot;
                   5333: }
                   5334: 
1.71      www      5335: # ---------------------------------------------------------------- Get metadata
                   5336: 
1.599     albertel 5337: my %metaentry;
1.71      www      5338: sub metadata {
1.176     www      5339:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5340:     $uri=&declutter($uri);
1.288     albertel 5341:     # if it is a non metadata possible uri return quickly
1.529     albertel 5342:     if (($uri eq '') || 
                   5343: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5344: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5345:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5346: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5347: 	return undef;
1.288     albertel 5348:     }
1.73      www      5349:     my $filename=$uri;
                   5350:     $uri=~s/\.meta$//;
1.172     www      5351: #
                   5352: # Is the metadata already cached?
1.177     www      5353: # Look at timestamp of caching
1.172     www      5354: # Everything is cached by the main uri, libraries are never directly cached
                   5355: #
1.428     albertel 5356:     if (!defined($liburi)) {
1.599     albertel 5357: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5358: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5359:     }
                   5360:     {
1.172     www      5361: #
                   5362: # Is this a recursive call for a library?
                   5363: #
1.599     albertel 5364: #	if (! exists($metacache{$uri})) {
                   5365: #	    $metacache{$uri}={};
                   5366: #	}
1.171     www      5367:         if ($liburi) {
                   5368: 	    $liburi=&declutter($liburi);
                   5369:             $filename=$liburi;
1.401     bowersj2 5370:         } else {
1.599     albertel 5371: 	    &devalidate_cache_new('meta',$uri);
                   5372: 	    undef(%metaentry);
1.401     bowersj2 5373: 	}
1.140     www      5374:         my %metathesekeys=();
1.73      www      5375:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5376: 	my $metastring;
1.609     banghart 5377: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 5378: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5379: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5380: 	    $metastring=&getfile($file);
1.489     albertel 5381: 	}
1.208     albertel 5382:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5383:         my $token;
1.140     www      5384:         undef %metathesekeys;
1.71      www      5385:         while ($token=$parser->get_token) {
1.339     albertel 5386: 	    if ($token->[0] eq 'S') {
                   5387: 		if (defined($token->[2]->{'package'})) {
1.172     www      5388: #
                   5389: # This is a package - get package info
                   5390: #
1.339     albertel 5391: 		    my $package=$token->[2]->{'package'};
                   5392: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5393: 		    if (defined($token->[2]->{'id'})) { 
                   5394: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5395: 		    }
1.599     albertel 5396: 		    if ($metaentry{':packages'}) {
                   5397: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5398: 		    } else {
1.599     albertel 5399: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5400: 		    }
1.613     albertel 5401: 		    foreach (sort keys %packagetab) {
1.432     albertel 5402: 			my $part=$keyroot;
                   5403: 			$part=~s/^\_//;
                   5404: 			if ($_=~/^\Q$package\E\&/ || 
                   5405: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 5406: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 5407: 			    # ignore package.tab specified default values
                   5408:                             # here &package_tab_default() will fetch those
                   5409: 			    if ($subp eq 'default') { next; }
1.339     albertel 5410: 			    my $value=$packagetab{$_};
1.432     albertel 5411: 			    my $unikey;
                   5412: 			    if ($pack =~ /_0$/) {
                   5413: 				$unikey='parameter_0_'.$name;
                   5414: 				$part=0;
                   5415: 			    } else {
                   5416: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5417: 			    }
1.339     albertel 5418: 			    if ($subp eq 'display') {
                   5419: 				$value.=' [Part: '.$part.']';
                   5420: 			    }
1.599     albertel 5421: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5422: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5423: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5424: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5425: 			    }
1.599     albertel 5426: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5427: 				$metaentry{':'.$unikey}=
                   5428: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5429: 			    }
1.339     albertel 5430: 			}
                   5431: 		    }
                   5432: 		} else {
1.172     www      5433: #
                   5434: # This is not a package - some other kind of start tag
1.339     albertel 5435: #
                   5436: 		    my $entry=$token->[1];
                   5437: 		    my $unikey;
                   5438: 		    if ($entry eq 'import') {
                   5439: 			$unikey='';
                   5440: 		    } else {
                   5441: 			$unikey=$entry;
                   5442: 		    }
                   5443: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5444: 
                   5445: 		    if (defined($token->[2]->{'id'})) { 
                   5446: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5447: 		    }
1.175     www      5448: 
1.339     albertel 5449: 		    if ($entry eq 'import') {
1.175     www      5450: #
                   5451: # Importing a library here
1.339     albertel 5452: #
                   5453: 			if ($depthcount<20) {
                   5454: 			    my $location=$parser->get_text('/import');
                   5455: 			    my $dir=$filename;
                   5456: 			    $dir=~s|[^/]*$||;
                   5457: 			    $location=&filelocation($dir,$location);
                   5458: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5459: 							       $location,$unikey,
                   5460: 							       $depthcount+1)))) {
1.599     albertel 5461: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 5462: 				$metathesekeys{$_}=1;
                   5463: 			    }
                   5464: 			}
                   5465: 		    } else { 
                   5466: 			
                   5467: 			if (defined($token->[2]->{'name'})) { 
                   5468: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5469: 			}
                   5470: 			$metathesekeys{$unikey}=1;
                   5471: 			foreach (@{$token->[3]}) {
1.599     albertel 5472: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 5473: 			}
                   5474: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5475: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5476: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5477: 		 # only ws inside the tag, and not in default, so use default
                   5478: 		 # as value
1.599     albertel 5479: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5480: 			} else {
1.321     albertel 5481: 		  # either something interesting inside the tag or default
                   5482:                   # uninteresting
1.599     albertel 5483: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5484: 			}
1.172     www      5485: # end of not-a-package not-a-library import
1.339     albertel 5486: 		    }
1.172     www      5487: # end of not-a-package start tag
1.339     albertel 5488: 		}
1.172     www      5489: # the next is the end of "start tag"
1.339     albertel 5490: 	    }
                   5491: 	}
1.483     albertel 5492: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   5493: 	foreach my $key (sort(keys(%packagetab))) {
                   5494: 	    #no specific packages #how's our extension
                   5495: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5496: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5497: 					 \%metathesekeys);
                   5498: 	}
1.599     albertel 5499: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 5500: 	    foreach my $key (sort(keys(%packagetab))) {
                   5501: 		#no specific packages well let's get default then
                   5502: 		if ($key!~/^default&/) { next; }
1.488     albertel 5503: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5504: 					     \%metathesekeys);
                   5505: 	    }
                   5506: 	}
1.338     www      5507: # are there custom rights to evaluate
1.599     albertel 5508: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5509: 
1.338     www      5510:     #
                   5511:     # Importing a rights file here
1.339     albertel 5512:     #
                   5513: 	    unless ($depthcount) {
1.599     albertel 5514: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5515: 		my $dir=$filename;
                   5516: 		$dir=~s|[^/]*$||;
                   5517: 		$location=&filelocation($dir,$location);
                   5518: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5519: 						   $location,'_rights',
                   5520: 						   $depthcount+1)))) {
1.599     albertel 5521: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 5522: 		    $metathesekeys{$_}=1;
                   5523: 		}
                   5524: 	    }
                   5525: 	}
1.599     albertel 5526: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   5527: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5528: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 5529: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      5530: # this is the end of "was not already recently cached
1.71      www      5531:     }
1.599     albertel 5532:     return $metaentry{':'.$what};
1.261     albertel 5533: }
                   5534: 
1.488     albertel 5535: sub metadata_create_package_def {
1.483     albertel 5536:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5537:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5538:     if ($subp eq 'default') { next; }
                   5539:     
1.599     albertel 5540:     if (defined($metaentry{':packages'})) {
                   5541: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5542:     } else {
1.599     albertel 5543: 	$metaentry{':packages'}=$package;
1.483     albertel 5544:     }
                   5545:     my $value=$packagetab{$key};
                   5546:     my $unikey;
                   5547:     $unikey='parameter_0_'.$name;
1.599     albertel 5548:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5549:     $$metathesekeys{$unikey}=1;
1.599     albertel 5550:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5551: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5552:     }
1.599     albertel 5553:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5554: 	$metaentry{':'.$unikey}=
                   5555: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5556:     }
                   5557: }
                   5558: 
1.261     albertel 5559: sub metadata_generate_part0 {
                   5560:     my ($metadata,$metacache,$uri) = @_;
                   5561:     my %allnames;
                   5562:     foreach my $metakey (sort keys %$metadata) {
                   5563: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5564: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5565: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5566: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5567: 	    $allnames{$name}=$part;
                   5568: 	  }
                   5569: 	}
                   5570:     }
                   5571:     foreach my $name (keys(%allnames)) {
                   5572:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5573:       my $key=":parameter_0_$name";
1.261     albertel 5574:       $$metacache{"$key.part"}='0';
                   5575:       $$metacache{"$key.name"}=$name;
1.428     albertel 5576:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5577: 					   $allnames{$name}.'_'.$name.
                   5578: 					   '.type'};
1.428     albertel 5579:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5580: 			     '.display'};
1.644     www      5581:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5582:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5583:       $$metacache{"$key.display"}=$olddis;
                   5584:     }
1.71      www      5585: }
                   5586: 
1.301     www      5587: # ------------------------------------------------- Get the title of a resource
                   5588: 
                   5589: sub gettitle {
                   5590:     my $urlsymb=shift;
                   5591:     my $symb=&symbread($urlsymb);
1.534     albertel 5592:     if ($symb) {
1.620     albertel 5593: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5594: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5595: 	if (defined($cached)) { 
                   5596: 	    return $result;
                   5597: 	}
1.534     albertel 5598: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5599: 	my $title='';
                   5600: 	my %bighash;
1.620     albertel 5601: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5602: 		&GDBM_READER(),0640)) {
                   5603: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5604: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5605: 	    untie %bighash;
                   5606: 	}
                   5607: 	$title=~s/\&colon\;/\:/gs;
                   5608: 	if ($title) {
1.599     albertel 5609: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5610: 	}
                   5611: 	$urlsymb=$url;
                   5612:     }
                   5613:     my $title=&metadata($urlsymb,'title');
                   5614:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5615:     return $title;
1.301     www      5616: }
1.613     albertel 5617: 
1.614     albertel 5618: sub get_slot {
                   5619:     my ($which,$cnum,$cdom)=@_;
                   5620:     if (!$cnum || !$cdom) {
                   5621: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5622: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5623: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5624:     }
1.703     albertel 5625:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   5626:     my %slotinfo;
                   5627:     if (exists($remembered{$key})) {
                   5628: 	$slotinfo{$which} = $remembered{$key};
                   5629:     } else {
                   5630: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5631: 	&Apache::lonhomework::showhash(%slotinfo);
                   5632: 	my ($tmp)=keys(%slotinfo);
                   5633: 	if ($tmp=~/^error:/) { return (); }
                   5634: 	$remembered{$key} = $slotinfo{$which};
                   5635:     }
1.616     albertel 5636:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5637: 	return %{$slotinfo{$which}};
                   5638:     }
                   5639:     return $slotinfo{$which};
1.614     albertel 5640: }
1.31      www      5641: # ------------------------------------------------- Update symbolic store links
                   5642: 
                   5643: sub symblist {
                   5644:     my ($mapname,%newhash)=@_;
1.438     www      5645:     $mapname=&deversion(&declutter($mapname));
1.31      www      5646:     my %hash;
1.620     albertel 5647:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5648:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5649:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 5650: 	    foreach my $url (keys %newhash) {
                   5651: 		next if ($url eq 'last_known'
                   5652: 			 && $env{'form.no_update_last_known'});
                   5653: 		$hash{declutter($url)}=&encode_symb($mapname,
                   5654: 						    $newhash{$url}->[1],
                   5655: 						    $newhash{$url}->[0]);
1.191     harris41 5656:             }
1.31      www      5657:             if (untie(%hash)) {
                   5658: 		return 'ok';
                   5659:             }
                   5660:         }
                   5661:     }
                   5662:     return 'error';
1.212     www      5663: }
                   5664: 
                   5665: # --------------------------------------------------------------- Verify a symb
                   5666: 
                   5667: sub symbverify {
1.510     www      5668:     my ($symb,$thisurl)=@_;
                   5669:     my $thisfn=$thisurl;
                   5670: # wrapper not part of symbs
                   5671:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 5672:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      5673:     $thisfn=&declutter($thisfn);
1.215     www      5674: # direct jump to resource in page or to a sequence - will construct own symbs
                   5675:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5676: # check URL part
1.409     www      5677:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5678: 
1.431     www      5679:     unless ($url eq $thisfn) { return 0; }
1.213     www      5680: 
1.216     www      5681:     $symb=&symbclean($symb);
1.510     www      5682:     $thisurl=&deversion($thisurl);
1.439     www      5683:     $thisfn=&deversion($thisfn);
1.213     www      5684: 
                   5685:     my %bighash;
                   5686:     my $okay=0;
1.431     www      5687: 
1.620     albertel 5688:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5689:                             &GDBM_READER(),0640)) {
1.510     www      5690:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5691:         unless ($ids) { 
1.510     www      5692:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5693:         }
                   5694:         if ($ids) {
                   5695: # ------------------------------------------------------------------- Has ID(s)
                   5696: 	    foreach (split(/\,/,$ids)) {
1.644     www      5697: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5698:                if (
                   5699:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5700:    eq $symb) { 
1.620     albertel 5701: 		   if (($env{'request.role.adv'}) ||
                   5702: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5703: 		       $okay=1; 
                   5704: 		   }
                   5705: 	       }
1.216     www      5706: 	   }
                   5707:         }
1.213     www      5708: 	untie(%bighash);
                   5709:     }
                   5710:     return $okay;
1.31      www      5711: }
                   5712: 
1.210     www      5713: # --------------------------------------------------------------- Clean-up symb
                   5714: 
                   5715: sub symbclean {
                   5716:     my $symb=shift;
1.568     albertel 5717:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5718: # remove version from map
                   5719:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      5720: 
1.210     www      5721: # remove version from URL
                   5722:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      5723: 
1.507     www      5724: # remove wrapper
                   5725: 
1.510     www      5726:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 5727:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      5728:     return $symb;
1.409     www      5729: }
                   5730: 
                   5731: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 5732: 
                   5733: sub encode_symb {
                   5734:     my ($map,$resid,$url)=@_;
                   5735:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   5736: }
1.409     www      5737: 
                   5738: sub decode_symb {
1.568     albertel 5739:     my $symb=shift;
                   5740:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   5741:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      5742:     return (&fixversion($map),$resid,&fixversion($url));
                   5743: }
                   5744: 
                   5745: sub fixversion {
                   5746:     my $fn=shift;
1.609     banghart 5747:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      5748:     my %bighash;
                   5749:     my $uri=&clutter($fn);
1.620     albertel 5750:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      5751: # is this cached?
1.599     albertel 5752:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      5753:     if (defined($cached)) { return $result; }
                   5754: # unfortunately not cached, or expired
1.620     albertel 5755:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      5756: 	    &GDBM_READER(),0640)) {
                   5757:  	if ($bighash{'version_'.$uri}) {
                   5758:  	    my $version=$bighash{'version_'.$uri};
1.444     www      5759:  	    unless (($version eq 'mostrecent') || 
                   5760: 		    ($version==&getversion($uri))) {
1.440     www      5761:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   5762:  	    }
                   5763:  	}
                   5764:  	untie %bighash;
1.413     www      5765:     }
1.599     albertel 5766:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      5767: }
                   5768: 
                   5769: sub deversion {
                   5770:     my $url=shift;
                   5771:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   5772:     return $url;
1.210     www      5773: }
                   5774: 
1.31      www      5775: # ------------------------------------------------------ Return symb list entry
                   5776: 
                   5777: sub symbread {
1.249     www      5778:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 5779:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 5780:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      5781: # no filename provided? try from environment
1.44      www      5782:     unless ($thisfn) {
1.620     albertel 5783:         if ($env{'request.symb'}) {
                   5784: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 5785: 	}
1.620     albertel 5786: 	$thisfn=$env{'request.filename'};
1.44      www      5787:     }
1.569     albertel 5788:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      5789: # is that filename actually a symb? Verify, clean, and return
                   5790:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 5791: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 5792: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 5793: 	}
1.242     www      5794:     }
1.44      www      5795:     $thisfn=declutter($thisfn);
1.31      www      5796:     my %hash;
1.37      www      5797:     my %bighash;
                   5798:     my $syval='';
1.620     albertel 5799:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  5800:         my $targetfn = $thisfn;
1.609     banghart 5801:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  5802:             $targetfn = 'adm/wrapper/'.$thisfn;
                   5803:         }
1.687     albertel 5804: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   5805: 	    $targetfn=$1;
                   5806: 	}
1.620     albertel 5807:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5808:                       &GDBM_READER(),0640)) {
1.481     raeburn  5809: 	    $syval=$hash{$targetfn};
1.37      www      5810:             untie(%hash);
                   5811:         }
                   5812: # ---------------------------------------------------------- There was an entry
                   5813:         if ($syval) {
1.601     albertel 5814: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 5815: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 5816: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 5817: 		    #return $env{$cache_str}='';
1.601     albertel 5818: 		#}    
                   5819: 		#$syval.=$1;
                   5820: 	    #}
1.37      www      5821:         } else {
                   5822: # ------------------------------------------------------- Was not in symb table
1.620     albertel 5823:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5824:                             &GDBM_READER(),0640)) {
1.37      www      5825: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      5826:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      5827:               unless ($ids) { 
                   5828:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      5829:               }
                   5830:               unless ($ids) {
                   5831: # alias?
                   5832: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      5833:               }
1.37      www      5834:               if ($ids) {
                   5835: # ------------------------------------------------------------------- Has ID(s)
                   5836:                  my @possibilities=split(/\,/,$ids);
1.39      www      5837:                  if ($#possibilities==0) {
                   5838: # ----------------------------------------------- There is only one possibility
1.37      www      5839: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 5840: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5841: 						    $resid,$thisfn);
1.249     www      5842:                  } elsif (!$donotrecurse) {
1.39      www      5843: # ------------------------------------------ There is more than one possibility
                   5844:                      my $realpossible=0;
1.191     harris41 5845:                      foreach (@possibilities) {
1.39      www      5846: 			 my $file=$bighash{'src_'.$_};
                   5847:                          if (&allowed('bre',$file)) {
                   5848:          		    my ($mapid,$resid)=split(/\./,$_);
                   5849:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   5850: 				$realpossible++;
1.626     albertel 5851:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5852: 						    $resid,$thisfn);
1.39      www      5853:                             }
                   5854: 			 }
1.191     harris41 5855:                      }
1.39      www      5856: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      5857:                  } else {
                   5858:                      $syval='';
1.37      www      5859:                  }
                   5860: 	      }
                   5861:               untie(%bighash)
1.481     raeburn  5862:            }
1.31      www      5863:         }
1.62      www      5864:         if ($syval) {
1.620     albertel 5865: 	    return $env{$cache_str}=$syval;
1.62      www      5866:         }
1.31      www      5867:     }
1.44      www      5868:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 5869:     return $env{$cache_str}='';
1.31      www      5870: }
                   5871: 
                   5872: # ---------------------------------------------------------- Return random seed
                   5873: 
1.32      www      5874: sub numval {
                   5875:     my $txt=shift;
                   5876:     $txt=~tr/A-J/0-9/;
                   5877:     $txt=~tr/a-j/0-9/;
                   5878:     $txt=~tr/K-T/0-9/;
                   5879:     $txt=~tr/k-t/0-9/;
                   5880:     $txt=~tr/U-Z/0-5/;
                   5881:     $txt=~tr/u-z/0-5/;
                   5882:     $txt=~s/\D//g;
1.564     albertel 5883:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      5884:     return int($txt);
1.368     albertel 5885: }
                   5886: 
1.484     albertel 5887: sub numval2 {
                   5888:     my $txt=shift;
                   5889:     $txt=~tr/A-J/0-9/;
                   5890:     $txt=~tr/a-j/0-9/;
                   5891:     $txt=~tr/K-T/0-9/;
                   5892:     $txt=~tr/k-t/0-9/;
                   5893:     $txt=~tr/U-Z/0-5/;
                   5894:     $txt=~tr/u-z/0-5/;
                   5895:     $txt=~s/\D//g;
                   5896:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5897:     my $total;
                   5898:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5899:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5900:     return int($total);
                   5901: }
                   5902: 
1.575     albertel 5903: sub numval3 {
                   5904:     use integer;
                   5905:     my $txt=shift;
                   5906:     $txt=~tr/A-J/0-9/;
                   5907:     $txt=~tr/a-j/0-9/;
                   5908:     $txt=~tr/K-T/0-9/;
                   5909:     $txt=~tr/k-t/0-9/;
                   5910:     $txt=~tr/U-Z/0-5/;
                   5911:     $txt=~tr/u-z/0-5/;
                   5912:     $txt=~s/\D//g;
                   5913:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5914:     my $total;
                   5915:     foreach my $val (@txts) { $total+=$val; }
                   5916:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5917:     return $total;
                   5918: }
                   5919: 
1.675     albertel 5920: sub digest {
                   5921:     my ($data)=@_;
                   5922:     my $digest=&Digest::MD5::md5($data);
                   5923:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   5924:     my ($e,$f);
                   5925:     {
                   5926:         use integer;
                   5927:         $e=($a+$b);
                   5928:         $f=($c+$d);
                   5929:         if ($_64bit) {
                   5930:             $e=(($e<<32)>>32);
                   5931:             $f=(($f<<32)>>32);
                   5932:         }
                   5933:     }
                   5934:     if (wantarray) {
                   5935: 	return ($e,$f);
                   5936:     } else {
                   5937: 	my $g;
                   5938: 	{
                   5939: 	    use integer;
                   5940: 	    $g=($e+$f);
                   5941: 	    if ($_64bit) {
                   5942: 		$g=(($g<<32)>>32);
                   5943: 	    }
                   5944: 	}
                   5945: 	return $g;
                   5946:     }
                   5947: }
                   5948: 
1.368     albertel 5949: sub latest_rnd_algorithm_id {
1.675     albertel 5950:     return '64bit5';
1.366     albertel 5951: }
1.32      www      5952: 
1.503     albertel 5953: sub get_rand_alg {
                   5954:     my ($courseid)=@_;
                   5955:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   5956:     if ($courseid) {
1.620     albertel 5957: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 5958:     }
                   5959:     return &latest_rnd_algorithm_id();
                   5960: }
                   5961: 
1.562     albertel 5962: sub validCODE {
                   5963:     my ($CODE)=@_;
                   5964:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5965:     return 0;
                   5966: }
                   5967: 
1.491     albertel 5968: sub getCODE {
1.620     albertel 5969:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 5970:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   5971: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   5972: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5973: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5974:     }
                   5975:     return undef;
                   5976: }
                   5977: 
1.31      www      5978: sub rndseed {
1.155     albertel 5979:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5980: 
                   5981:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5982:     if (!$symb) {
1.366     albertel 5983: 	unless ($symb=$wsymb) { return time; }
                   5984:     }
                   5985:     if (!$courseid) { $courseid=$wcourseid; }
                   5986:     if (!$domain) { $domain=$wdomain; }
                   5987:     if (!$username) { $username=$wusername }
1.503     albertel 5988:     my $which=&get_rand_alg();
1.491     albertel 5989:     if (defined(&getCODE())) {
1.675     albertel 5990: 	if ($which eq '64bit5') {
                   5991: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   5992: 	} elsif ($which eq '64bit4') {
1.575     albertel 5993: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5994: 	} else {
                   5995: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5996: 	}
1.675     albertel 5997:     } elsif ($which eq '64bit5') {
                   5998: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 5999:     } elsif ($which eq '64bit4') {
                   6000: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6001:     } elsif ($which eq '64bit3') {
                   6002: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6003:     } elsif ($which eq '64bit2') {
                   6004: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6005:     } elsif ($which eq '64bit') {
                   6006: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6007:     }
                   6008:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6009: }
                   6010: 
                   6011: sub rndseed_32bit {
                   6012:     my ($symb,$courseid,$domain,$username)=@_;
                   6013:     {
                   6014: 	use integer;
                   6015: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6016: 	my $symbseed=numval($symb) << 22;
                   6017: 	my $namechck=unpack("%32C*",$username) << 17;
                   6018: 	my $nameseed=numval($username) << 12;
                   6019: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6020: 	my $courseseed=unpack("%32C*",$courseid);
                   6021: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6022: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6023: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6024: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6025: 	return $num;
                   6026:     }
                   6027: }
                   6028: 
                   6029: sub rndseed_64bit {
                   6030:     my ($symb,$courseid,$domain,$username)=@_;
                   6031:     {
                   6032: 	use integer;
                   6033: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6034: 	my $symbseed=numval($symb) << 10;
                   6035: 	my $namechck=unpack("%32S*",$username);
                   6036: 	
                   6037: 	my $nameseed=numval($username) << 21;
                   6038: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6039: 	my $courseseed=unpack("%32S*",$courseid);
                   6040: 	
                   6041: 	my $num1=$symbchck+$symbseed+$namechck;
                   6042: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6043: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6044: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6046: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6047: 	return "$num1,$num2";
1.155     albertel 6048:     }
1.366     albertel 6049: }
                   6050: 
1.443     albertel 6051: sub rndseed_64bit2 {
                   6052:     my ($symb,$courseid,$domain,$username)=@_;
                   6053:     {
                   6054: 	use integer;
                   6055: 	# strings need to be an even # of cahracters long, it it is odd the
                   6056:         # last characters gets thrown away
                   6057: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6058: 	my $symbseed=numval($symb) << 10;
                   6059: 	my $namechck=unpack("%32S*",$username.' ');
                   6060: 	
                   6061: 	my $nameseed=numval($username) << 21;
1.501     albertel 6062: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6063: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6064: 	
                   6065: 	my $num1=$symbchck+$symbseed+$namechck;
                   6066: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6067: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6068: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6069: 	return "$num1,$num2";
                   6070:     }
                   6071: }
                   6072: 
                   6073: sub rndseed_64bit3 {
                   6074:     my ($symb,$courseid,$domain,$username)=@_;
                   6075:     {
                   6076: 	use integer;
                   6077: 	# strings need to be an even # of cahracters long, it it is odd the
                   6078:         # last characters gets thrown away
                   6079: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6080: 	my $symbseed=numval2($symb) << 10;
                   6081: 	my $namechck=unpack("%32S*",$username.' ');
                   6082: 	
                   6083: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6084: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6085: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6086: 	
                   6087: 	my $num1=$symbchck+$symbseed+$namechck;
                   6088: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6089: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6090: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6091: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6092: 	
1.503     albertel 6093: 	return "$num1:$num2";
1.443     albertel 6094:     }
                   6095: }
                   6096: 
1.575     albertel 6097: sub rndseed_64bit4 {
                   6098:     my ($symb,$courseid,$domain,$username)=@_;
                   6099:     {
                   6100: 	use integer;
                   6101: 	# strings need to be an even # of cahracters long, it it is odd the
                   6102:         # last characters gets thrown away
                   6103: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6104: 	my $symbseed=numval3($symb) << 10;
                   6105: 	my $namechck=unpack("%32S*",$username.' ');
                   6106: 	
                   6107: 	my $nameseed=numval3($username) << 21;
                   6108: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6109: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6110: 	
                   6111: 	my $num1=$symbchck+$symbseed+$namechck;
                   6112: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6113: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6114: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6115: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6116: 	
                   6117: 	return "$num1:$num2";
                   6118:     }
                   6119: }
                   6120: 
1.675     albertel 6121: sub rndseed_64bit5 {
                   6122:     my ($symb,$courseid,$domain,$username)=@_;
                   6123:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6124:     return "$num1:$num2";
                   6125: }
                   6126: 
1.366     albertel 6127: sub rndseed_CODE_64bit {
                   6128:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6129:     {
1.366     albertel 6130: 	use integer;
1.443     albertel 6131: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6132: 	my $symbseed=numval2($symb);
1.491     albertel 6133: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6134: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6135: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6136: 	my $num1=$symbseed+$CODEchck;
                   6137: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6138: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6139: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6140: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6141: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6142: 	return "$num1:$num2";
1.366     albertel 6143:     }
                   6144: }
                   6145: 
1.575     albertel 6146: sub rndseed_CODE_64bit4 {
                   6147:     my ($symb,$courseid,$domain,$username)=@_;
                   6148:     {
                   6149: 	use integer;
                   6150: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6151: 	my $symbseed=numval3($symb);
                   6152: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6153: 	my $CODEseed=numval3(&getCODE());
                   6154: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6155: 	my $num1=$symbseed+$CODEchck;
                   6156: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6157: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6158: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6159: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6160: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6161: 	return "$num1:$num2";
                   6162:     }
                   6163: }
                   6164: 
1.675     albertel 6165: sub rndseed_CODE_64bit5 {
                   6166:     my ($symb,$courseid,$domain,$username)=@_;
                   6167:     my $code = &getCODE();
                   6168:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6169:     return "$num1:$num2";
                   6170: }
                   6171: 
1.366     albertel 6172: sub setup_random_from_rndseed {
                   6173:     my ($rndseed)=@_;
1.503     albertel 6174:     if ($rndseed =~/([,:])/) {
                   6175: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6176: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6177:     } else {
                   6178: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6179:     }
1.36      albertel 6180: }
                   6181: 
1.474     albertel 6182: sub latest_receipt_algorithm_id {
                   6183:     return 'receipt2';
                   6184: }
                   6185: 
1.480     www      6186: sub recunique {
                   6187:     my $fucourseid=shift;
                   6188:     my $unique;
1.620     albertel 6189:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6190: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6191:     } else {
                   6192: 	$unique=$perlvar{'lonReceipt'};
                   6193:     }
                   6194:     return unpack("%32C*",$unique);
                   6195: }
                   6196: 
                   6197: sub recprefix {
                   6198:     my $fucourseid=shift;
                   6199:     my $prefix;
1.620     albertel 6200:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6201: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6202:     } else {
                   6203: 	$prefix=$perlvar{'lonHostID'};
                   6204:     }
                   6205:     return unpack("%32C*",$prefix);
                   6206: }
                   6207: 
1.76      www      6208: sub ireceipt {
1.474     albertel 6209:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6210:     my $cuname=unpack("%32C*",$funame);
                   6211:     my $cudom=unpack("%32C*",$fudom);
                   6212:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6213:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6214:     my $cunique=&recunique($fucourseid);
1.474     albertel 6215:     my $cpart=unpack("%32S*",$part);
1.480     www      6216:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6217:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6218: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6219: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6220: 			       " and ".($cpart%$cudom));
                   6221: 			       
                   6222: 	$return.= ($cunique%$cuname+
                   6223: 		   $cunique%$cudom+
                   6224: 		   $cusymb%$cuname+
                   6225: 		   $cusymb%$cudom+
                   6226: 		   $cucourseid%$cuname+
                   6227: 		   $cucourseid%$cudom+
                   6228: 		   $cpart%$cuname+
                   6229: 		   $cpart%$cudom);
                   6230:     } else {
                   6231: 	$return.= ($cunique%$cuname+
                   6232: 		   $cunique%$cudom+
                   6233: 		   $cusymb%$cuname+
                   6234: 		   $cusymb%$cudom+
                   6235: 		   $cucourseid%$cuname+
                   6236: 		   $cucourseid%$cudom);
                   6237:     }
                   6238:     return $return;
1.76      www      6239: }
                   6240: 
                   6241: sub receipt {
1.474     albertel 6242:     my ($part)=@_;
                   6243:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6244:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6245: }
1.260     ng       6246: 
1.36      albertel 6247: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6248: # returns either the contents of the file or 
                   6249: # -1 if the file doesn't exist
1.481     raeburn  6250: #
                   6251: # if the target is a file that was uploaded via DOCS, 
                   6252: # a check will be made to see if a current copy exists on the local server,
                   6253: # if it does this will be served, otherwise a copy will be retrieved from
                   6254: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6255: # the local server.   
1.472     albertel 6256: 
1.36      albertel 6257: sub getfile {
1.538     albertel 6258:     my ($file) = @_;
1.609     banghart 6259:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6260:     &repcopy($file);
                   6261:     return &readfile($file);
                   6262: }
                   6263: 
                   6264: sub repcopy_userfile {
                   6265:     my ($file)=@_;
1.609     banghart 6266:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6267:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6268:     my ($cdom,$cnum,$filename) = 
                   6269: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6270:     my ($info,$rtncode);
                   6271:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6272:     if (-e "$file") {
                   6273: 	my @fileinfo = stat($file);
                   6274: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6275: 	if ($lwpresp ne 'ok') {
                   6276: 	    if ($rtncode eq '404') {
1.538     albertel 6277: 		unlink($file);
1.482     albertel 6278: 	    }
1.517     albertel 6279: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6280: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6281: 	    #my $response=$ua->request($request);
                   6282: 	    #if ($response->is_success()) {
                   6283: 	#	return $response->content;
                   6284: 	#    } else {
                   6285: 	#	return -1;
                   6286: 	#    }
1.482     albertel 6287: 	    return -1;
                   6288: 	}
                   6289: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6290: 	    return 'ok';
1.482     albertel 6291: 	}
                   6292: 	$info = '';
1.538     albertel 6293: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6294: 	if ($lwpresp ne 'ok') {
                   6295: 	    return -1;
                   6296: 	}
                   6297:     } else {
1.538     albertel 6298: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6299: 	if ($lwpresp ne 'ok') {
1.517     albertel 6300: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6301: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6302: 	    my $response=$ua->request($request);
                   6303: 	    if ($response->is_success()) {
1.538     albertel 6304: 		$info=$response->content;
1.517     albertel 6305: 	    } else {
                   6306: 		return -1;
                   6307: 	    }
1.482     albertel 6308: 	}
                   6309: 	my @parts = ($cdom,$cnum); 
                   6310: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6311: 	    push @parts, split(/\//,$1);
1.518     albertel 6312: 	}
1.538     albertel 6313: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6314: 	foreach my $part (@parts) {
                   6315: 	    $path .= '/'.$part;
                   6316: 	    if (!-e $path) {
                   6317: 		mkdir($path,0770);
                   6318: 	    }
                   6319: 	}
                   6320:     }
1.538     albertel 6321:     open(FILE,">$file");
1.482     albertel 6322:     print FILE $info;
                   6323:     close(FILE);
1.607     raeburn  6324:     return 'ok';
1.481     raeburn  6325: }
                   6326: 
1.517     albertel 6327: sub tokenwrapper {
                   6328:     my $uri=shift;
1.552     albertel 6329:     $uri=~s|^http\://([^/]+)||;
                   6330:     $uri=~s|^/||;
1.620     albertel 6331:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6332:     my $token=$1;
1.552     albertel 6333:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6334:     if ($udom && $uname && $file) {
                   6335: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6336:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6337:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6338:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6339:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6340:     } else {
                   6341:         return '/adm/notfound.html';
                   6342:     }
                   6343: }
                   6344: 
1.481     raeburn  6345: sub getuploaded {
                   6346:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6347:     $uri=~s/^\///;
                   6348:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6349:     my $ua=new LWP::UserAgent;
                   6350:     my $request=new HTTP::Request($reqtype,$uri);
                   6351:     my $response=$ua->request($request);
                   6352:     $$rtncode = $response->code;
1.482     albertel 6353:     if (! $response->is_success()) {
                   6354: 	return 'failed';
                   6355:     }      
                   6356:     if ($reqtype eq 'HEAD') {
1.486     www      6357: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6358:     } elsif ($reqtype eq 'GET') {
                   6359: 	$$info = $response->content;
1.472     albertel 6360:     }
1.482     albertel 6361:     return 'ok';
1.36      albertel 6362: }
                   6363: 
1.481     raeburn  6364: sub readfile {
                   6365:     my $file = shift;
                   6366:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6367:     my $fh;
                   6368:     open($fh,"<$file");
                   6369:     my $a='';
                   6370:     while (<$fh>) { $a .=$_; }
                   6371:     return $a;
                   6372: }
                   6373: 
1.36      albertel 6374: sub filelocation {
1.590     banghart 6375:     my ($dir,$file) = @_;
                   6376:     my $location;
                   6377:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6378: 
                   6379:     if ($file =~ m-^/adm/-) {
                   6380: 	$file=~s-^/adm/wrapper/-/-;
                   6381: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6382:     }
1.590     banghart 6383:     if ($file=~m:^/~:) { # is a contruction space reference
                   6384:         $location = $file;
                   6385:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6386:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6387: 	# is a correct contruction space reference
                   6388:         $location = $file;
1.609     banghart 6389:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6390:         my ($udom,$uname,$filename)=
1.609     banghart 6391:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6392:         my $home=&homeserver($uname,$udom);
                   6393:         my $is_me=0;
                   6394:         my @ids=&current_machine_ids();
                   6395:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6396:         if ($is_me) {
                   6397:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   6398:   	      '/userfiles/'.$filename;
                   6399:         } else {
                   6400:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6401:   	      $udom.'/'.$uname.'/'.$filename;
                   6402:         }
                   6403:     } else {
                   6404:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6405:         $file=~s:^/res/:/:;
                   6406:         if ( !( $file =~ m:^/:) ) {
                   6407:             $location = $dir. '/'.$file;
                   6408:         } else {
                   6409:             $location = '/home/httpd/html/res'.$file;
                   6410:         }
1.59      albertel 6411:     }
1.590     banghart 6412:     $location=~s://+:/:g; # remove duplicate /
                   6413:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6414:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6415:     return $location;
1.46      www      6416: }
1.36      albertel 6417: 
1.46      www      6418: sub hreflocation {
                   6419:     my ($dir,$file)=@_;
1.460     albertel 6420:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6421: 	$file=filelocation($dir,$file);
1.700     albertel 6422:     } elsif ($file=~m-^/adm/-) {
                   6423: 	$file=~s-^/adm/wrapper/-/-;
                   6424: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6425:     }
                   6426:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6427: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6428:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6429: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6430:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6431: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6432: 	    -/uploaded/$1/$2/-x;
1.46      www      6433:     }
1.462     albertel 6434:     return $file;
1.465     albertel 6435: }
                   6436: 
                   6437: sub current_machine_domains {
                   6438:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6439:     my @domains;
                   6440:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6441: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6442: 	if ($hostname eq $name) {
                   6443: 	    push(@domains,$hostdom{$id});
                   6444: 	}
                   6445:     }
                   6446:     return @domains;
                   6447: }
                   6448: 
                   6449: sub current_machine_ids {
                   6450:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6451:     my @ids;
                   6452:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6453: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6454: 	if ($hostname eq $name) {
                   6455: 	    push(@ids,$id);
                   6456: 	}
                   6457:     }
                   6458:     return @ids;
1.31      www      6459: }
                   6460: 
                   6461: # ------------------------------------------------------------- Declutters URLs
                   6462: 
                   6463: sub declutter {
                   6464:     my $thisfn=shift;
1.569     albertel 6465:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6466:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6467:     $thisfn=~s/^\///;
1.697     albertel 6468:     $thisfn=~s|^adm/wrapper/||;
                   6469:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      6470:     $thisfn=~s/^res\///;
1.235     www      6471:     $thisfn=~s/\?.+$//;
1.268     www      6472:     return $thisfn;
                   6473: }
                   6474: 
                   6475: # ------------------------------------------------------------- Clutter up URLs
                   6476: 
                   6477: sub clutter {
                   6478:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6479:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6480:        $thisfn='/res'.$thisfn; 
                   6481:     }
1.694     albertel 6482:     if ($thisfn !~m|/adm|) {
1.695     albertel 6483: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 6484: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 6485: 	} else {
                   6486: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   6487: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 6488: 	    if ($embstyle eq 'ssi'
                   6489: 		|| ($embstyle eq 'hdn')
                   6490: 		|| ($embstyle eq 'rat')
                   6491: 		|| ($embstyle eq 'prv')
                   6492: 		|| ($embstyle eq 'ign')) {
                   6493: 		#do nothing with these
                   6494: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 6495: 		|| ($embstyle eq 'emb')
                   6496: 		|| ($embstyle eq 'wrp')) {
                   6497: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 6498: 	    } elsif ($embstyle eq 'unk'
                   6499: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 6500: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 6501: 	    } else {
1.718     www      6502: #		&logthis("Got a blank emb style");
1.695     albertel 6503: 	    }
1.694     albertel 6504: 	}
                   6505:     }
1.31      www      6506:     return $thisfn;
1.12      www      6507: }
                   6508: 
1.557     albertel 6509: sub freeze_escape {
                   6510:     my ($value)=@_;
                   6511:     if (ref($value)) {
                   6512: 	$value=&nfreeze($value);
                   6513: 	return '__FROZEN__'.&escape($value);
                   6514:     }
                   6515:     return &escape($value);
                   6516: }
                   6517: 
1.12      www      6518: # -------------------------------------------------------- Escape Special Chars
                   6519: 
                   6520: sub escape {
                   6521:     my $str=shift;
                   6522:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   6523:     return $str;
                   6524: }
                   6525: 
                   6526: # ----------------------------------------------------- Un-Escape Special Chars
                   6527: 
                   6528: sub unescape {
                   6529:     my $str=shift;
                   6530:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   6531:     return $str;
                   6532: }
1.11      www      6533: 
1.557     albertel 6534: sub thaw_unescape {
                   6535:     my ($value)=@_;
                   6536:     if ($value =~ /^__FROZEN__/) {
                   6537: 	substr($value,0,10,undef);
                   6538: 	$value=&unescape($value);
                   6539: 	return &thaw($value);
                   6540:     }
                   6541:     return &unescape($value);
                   6542: }
                   6543: 
1.436     albertel 6544: sub correct_line_ends {
                   6545:     my ($result)=@_;
                   6546:     $$result =~s/\r\n/\n/mg;
                   6547:     $$result =~s/\r/\n/mg;
1.415     albertel 6548: }
1.1       albertel 6549: # ================================================================ Main Program
                   6550: 
1.184     www      6551: sub goodbye {
1.204     albertel 6552:    &logthis("Starting Shut down");
1.443     albertel 6553: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6554:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6555: #converted
1.599     albertel 6556: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6557:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6558: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6559: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6560: #1.1 only
1.599     albertel 6561: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6562: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6563: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6564: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6565:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6566:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6567:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6568:    &flushcourselogs();
                   6569:    &logthis("Shutting down");
                   6570: }
                   6571: 
1.179     www      6572: BEGIN {
1.228     harris41 6573: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6574:     unless ($readit) {
1.217     harris41 6575: {
1.581     matthew  6576:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6577:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6578: 
                   6579:     while (my $configline=<$config>) {
1.484     albertel 6580:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6581: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6582:            chomp($varvalue);
1.1       albertel 6583:            $perlvar{$varname}=$varvalue;
                   6584:         }
                   6585:     }
1.448     albertel 6586:     close($config);
1.1       albertel 6587: }
1.227     harris41 6588: {
1.448     albertel 6589:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6590: 
                   6591:     while (my $configline=<$config>) {
                   6592:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6593: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6594:            chomp($varvalue);
                   6595:            $perlvar{$varname}=$varvalue;
                   6596:         }
                   6597:     }
1.448     albertel 6598:     close($config);
1.227     harris41 6599: }
1.1       albertel 6600: 
1.327     albertel 6601: # ------------------------------------------------------------ Read domain file
                   6602: {
                   6603:     %domaindescription = ();
                   6604:     %domain_auth_def = ();
                   6605:     %domain_auth_arg_def = ();
1.448     albertel 6606:     my $fh;
                   6607:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6608:        while (<$fh>) {
1.390     matthew  6609:            next if (/^(\#|\s*$)/);
                   6610: #           next if /^\#/;
1.327     albertel 6611:            chomp;
1.403     www      6612:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  6613: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      6614: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6615:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6616: 	   $domaindescription{$domain}=$domain_description;
                   6617: 	   $domain_lang_def{$domain}=$def_lang;
                   6618: 	   $domain_city{$domain}=$city;
                   6619: 	   $domain_longi{$domain}=$longi;
                   6620: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  6621:            $domain_primary{$domain}=$primary;
1.403     www      6622: 
1.448     albertel 6623:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6624: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6625: 	}
1.327     albertel 6626:     }
1.448     albertel 6627:     close ($fh);
1.327     albertel 6628: }
                   6629: 
                   6630: 
1.1       albertel 6631: # ------------------------------------------------------------- Read hosts file
                   6632: {
1.448     albertel 6633:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6634: 
                   6635:     while (my $configline=<$config>) {
1.303     matthew  6636:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6637:        chomp($configline);
1.595     albertel 6638:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6639:        $name=~s/\s//g;
1.595     albertel 6640:        if ($id && $domain && $role && $name) {
1.252     albertel 6641: 	 $hostname{$id}=$name;
                   6642: 	 $hostdom{$id}=$domain;
                   6643: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6644:        }
1.1       albertel 6645:     }
1.448     albertel 6646:     close($config);
1.619     albertel 6647:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 6648:     #&get_iphost();
1.1       albertel 6649: }
                   6650: 
1.598     albertel 6651: sub get_iphost {
                   6652:     if (%iphost) { return %iphost; }
1.653     albertel 6653:     my %name_to_ip;
1.598     albertel 6654:     foreach my $id (keys(%hostname)) {
                   6655: 	my $name=$hostname{$id};
1.653     albertel 6656: 	my $ip;
                   6657: 	if (!exists($name_to_ip{$name})) {
                   6658: 	    $ip = gethostbyname($name);
                   6659: 	    if (!$ip || length($ip) ne 4) {
                   6660: 		&logthis("Skipping host $id name $name no IP found\n");
                   6661: 		next;
                   6662: 	    }
                   6663: 	    $ip=inet_ntoa($ip);
                   6664: 	    $name_to_ip{$name} = $ip;
                   6665: 	} else {
                   6666: 	    $ip = $name_to_ip{$name};
1.598     albertel 6667: 	}
                   6668: 	push(@{$iphost{$ip}},$id);
                   6669:     }
                   6670:     return %iphost;
                   6671: }
                   6672: 
1.1       albertel 6673: # ------------------------------------------------------ Read spare server file
                   6674: {
1.448     albertel 6675:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 6676: 
                   6677:     while (my $configline=<$config>) {
                   6678:        chomp($configline);
1.284     matthew  6679:        if ($configline) {
1.1       albertel 6680:           $spareid{$configline}=1;
                   6681:        }
                   6682:     }
1.448     albertel 6683:     close($config);
1.1       albertel 6684: }
1.11      www      6685: # ------------------------------------------------------------ Read permissions
                   6686: {
1.448     albertel 6687:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      6688: 
                   6689:     while (my $configline=<$config>) {
1.448     albertel 6690: 	chomp($configline);
                   6691: 	if ($configline) {
                   6692: 	    my ($role,$perm)=split(/ /,$configline);
                   6693: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   6694: 	}
1.11      www      6695:     }
1.448     albertel 6696:     close($config);
1.11      www      6697: }
                   6698: 
                   6699: # -------------------------------------------- Read plain texts for permissions
                   6700: {
1.448     albertel 6701:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      6702: 
                   6703:     while (my $configline=<$config>) {
1.448     albertel 6704: 	chomp($configline);
                   6705: 	if ($configline) {
                   6706: 	    my ($short,$plain)=split(/:/,$configline);
                   6707: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   6708: 	}
1.135     www      6709:     }
1.448     albertel 6710:     close($config);
1.135     www      6711: }
                   6712: 
                   6713: # ---------------------------------------------------------- Read package table
                   6714: {
1.448     albertel 6715:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      6716: 
                   6717:     while (my $configline=<$config>) {
1.483     albertel 6718: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 6719: 	chomp($configline);
                   6720: 	my ($short,$plain)=split(/:/,$configline);
                   6721: 	my ($pack,$name)=split(/\&/,$short);
                   6722: 	if ($plain ne '') {
                   6723: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   6724: 	    $packagetab{$short}=$plain; 
                   6725: 	}
1.11      www      6726:     }
1.448     albertel 6727:     close($config);
1.329     matthew  6728: }
                   6729: 
                   6730: # ------------- set up temporary directory
                   6731: {
                   6732:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   6733: 
1.11      www      6734: }
                   6735: 
1.599     albertel 6736: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      6737: 
1.281     www      6738: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      6739: $dumpcount=0;
1.22      www      6740: 
1.163     harris41 6741: &logtouch();
1.672     albertel 6742: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      6743: $readit=1;
1.564     albertel 6744:     {
                   6745: 	use integer;
                   6746: 	my $test=(2**32)+1;
1.568     albertel 6747: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 6748: 	&logthis(" Detected 64bit platform ($_64bit)");
                   6749:     }
1.195     www      6750: }
1.1       albertel 6751: }
1.179     www      6752: 
1.1       albertel 6753: 1;
1.191     harris41 6754: __END__
                   6755: 
1.243     albertel 6756: =pod
                   6757: 
1.191     harris41 6758: =head1 NAME
                   6759: 
1.243     albertel 6760: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 6761: 
                   6762: =head1 SYNOPSIS
                   6763: 
1.243     albertel 6764: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 6765: 
                   6766:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   6767: 
1.243     albertel 6768: Common parameters:
                   6769: 
                   6770: =over 4
                   6771: 
                   6772: =item *
                   6773: 
                   6774: $uname : an internal username (if $cname expecting a course Id specifically)
                   6775: 
                   6776: =item *
                   6777: 
                   6778: $udom : a domain (if $cdom expecting a course's domain specifically)
                   6779: 
                   6780: =item *
                   6781: 
                   6782: $symb : a resource instance identifier
                   6783: 
                   6784: =item *
                   6785: 
                   6786: $namespace : the name of a .db file that contains the data needed or
                   6787: being set.
                   6788: 
                   6789: =back
                   6790: 
1.394     bowersj2 6791: =head1 OVERVIEW
1.191     harris41 6792: 
1.394     bowersj2 6793: lonnet provides subroutines which interact with the
                   6794: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   6795: about classes, users, and resources.
1.243     albertel 6796: 
                   6797: For many of these objects you can also use this to store data about
                   6798: them or modify them in various ways.
1.191     harris41 6799: 
1.394     bowersj2 6800: =head2 Symbs
1.191     harris41 6801: 
1.394     bowersj2 6802: To identify a specific instance of a resource, LON-CAPA uses symbols
                   6803: or "symbs"X<symb>. These identifiers are built from the URL of the
                   6804: map, the resource number of the resource in the map, and the URL of
                   6805: the resource itself. The latter is somewhat redundant, but might help
                   6806: if maps change.
                   6807: 
                   6808: An example is
                   6809: 
                   6810:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   6811: 
                   6812: The respective map entry is
                   6813: 
                   6814:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   6815:   title="Problem 2">
                   6816:  </resource>
                   6817: 
                   6818: Symbs are used by the random number generator, as well as to store and
                   6819: restore data specific to a certain instance of for example a problem.
                   6820: 
                   6821: =head2 Storing And Retrieving Data
                   6822: 
                   6823: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   6824: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   6825: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   6826: is is the non-critical message twin of cstore. These functions are for
                   6827: handlers to store a perl hash to a user's permanent data space in an
                   6828: easy manner, and to retrieve it again on another call. It is expected
                   6829: that a handler would use this once at the beginning to retrieve data,
                   6830: and then again once at the end to send only the new data back.
                   6831: 
                   6832: The data is stored in the user's data directory on the user's
                   6833: homeserver under the ID of the course.
                   6834: 
                   6835: The hash that is returned by restore will have all of the previous
                   6836: value for all of the elements of the hash.
                   6837: 
                   6838: Example:
                   6839: 
                   6840:  #creating a hash
                   6841:  my %hash;
                   6842:  $hash{'foo'}='bar';
                   6843: 
                   6844:  #storing it
                   6845:  &Apache::lonnet::cstore(\%hash);
                   6846: 
                   6847:  #changing a value
                   6848:  $hash{'foo'}='notbar';
                   6849: 
                   6850:  #adding a new value
                   6851:  $hash{'bar'}='foo';
                   6852:  &Apache::lonnet::cstore(\%hash);
                   6853: 
                   6854:  #retrieving the hash
                   6855:  my %history=&Apache::lonnet::restore();
                   6856: 
                   6857:  #print the hash
                   6858:  foreach my $key (sort(keys(%history))) {
                   6859:    print("\%history{$key} = $history{$key}");
                   6860:  }
                   6861: 
                   6862: Will print out:
1.191     harris41 6863: 
1.394     bowersj2 6864:  %history{1:foo} = bar
                   6865:  %history{1:keys} = foo:timestamp
                   6866:  %history{1:timestamp} = 990455579
                   6867:  %history{2:bar} = foo
                   6868:  %history{2:foo} = notbar
                   6869:  %history{2:keys} = foo:bar:timestamp
                   6870:  %history{2:timestamp} = 990455580
                   6871:  %history{bar} = foo
                   6872:  %history{foo} = notbar
                   6873:  %history{timestamp} = 990455580
                   6874:  %history{version} = 2
                   6875: 
                   6876: Note that the special hash entries C<keys>, C<version> and
                   6877: C<timestamp> were added to the hash. C<version> will be equal to the
                   6878: total number of versions of the data that have been stored. The
                   6879: C<timestamp> attribute will be the UNIX time the hash was
                   6880: stored. C<keys> is available in every historical section to list which
                   6881: keys were added or changed at a specific historical revision of a
                   6882: hash.
                   6883: 
                   6884: B<Warning>: do not store the hash that restore returns directly. This
                   6885: will cause a mess since it will restore the historical keys as if the
                   6886: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 6887: 
1.394     bowersj2 6888: Calling convention:
1.191     harris41 6889: 
1.394     bowersj2 6890:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   6891:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 6892: 
1.394     bowersj2 6893: For more detailed information, see lonnet specific documentation.
1.191     harris41 6894: 
1.394     bowersj2 6895: =head1 RETURN MESSAGES
1.191     harris41 6896: 
1.394     bowersj2 6897: =over 4
1.191     harris41 6898: 
1.394     bowersj2 6899: =item * B<con_lost>: unable to contact remote host
1.191     harris41 6900: 
1.394     bowersj2 6901: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   6902: when the connection is brought back up
1.191     harris41 6903: 
1.394     bowersj2 6904: =item * B<con_failed>: unable to contact remote host and unable to save message
                   6905: for later delivery
1.191     harris41 6906: 
1.394     bowersj2 6907: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 6908: 
1.394     bowersj2 6909: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 6910: that was requested
1.191     harris41 6911: 
1.243     albertel 6912: =back
1.191     harris41 6913: 
1.243     albertel 6914: =head1 PUBLIC SUBROUTINES
1.191     harris41 6915: 
1.243     albertel 6916: =head2 Session Environment Functions
1.191     harris41 6917: 
1.243     albertel 6918: =over 4
1.191     harris41 6919: 
1.394     bowersj2 6920: =item * 
                   6921: X<appenv()>
                   6922: B<appenv(%hash)>: the value of %hash is written to
                   6923: the user envirnoment file, and will be restored for each access this
1.620     albertel 6924: user makes during this session, also modifies the %env for the current
1.394     bowersj2 6925: process
1.191     harris41 6926: 
                   6927: =item *
1.394     bowersj2 6928: X<delenv()>
                   6929: B<delenv($regexp)>: removes all items from the session
                   6930: environment file that matches the regular expression in $regexp. The
1.620     albertel 6931: values are also delted from the current processes %env.
1.191     harris41 6932: 
1.243     albertel 6933: =back
                   6934: 
                   6935: =head2 User Information
1.191     harris41 6936: 
1.243     albertel 6937: =over 4
1.191     harris41 6938: 
                   6939: =item *
1.394     bowersj2 6940: X<queryauthenticate()>
                   6941: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 6942: authentication scheme
                   6943: 
                   6944: =item *
1.394     bowersj2 6945: X<authenticate()>
                   6946: B<authenticate($uname,$upass,$udom)>: try to
                   6947: authenticate user from domain's lib servers (first use the current
                   6948: one). C<$upass> should be the users password.
1.191     harris41 6949: 
                   6950: =item *
1.394     bowersj2 6951: X<homeserver()>
                   6952: B<homeserver($uname,$udom)>: find the server which has
                   6953: the user's directory and files (there must be only one), this caches
                   6954: the answer, and also caches if there is a borken connection.
1.191     harris41 6955: 
                   6956: =item *
1.394     bowersj2 6957: X<idget()>
                   6958: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   6959: (IDs are a unique resource in a domain, there must be only 1 ID per
                   6960: username, and only 1 username per ID in a specific domain) (returns
                   6961: hash: id=>name,id=>name)
1.191     harris41 6962: 
                   6963: =item *
1.394     bowersj2 6964: X<idrget()>
                   6965: B<idrget($udom,@unames)>: find the IDs behind a list of
                   6966: usernames (returns hash: name=>id,name=>id)
1.191     harris41 6967: 
                   6968: =item *
1.394     bowersj2 6969: X<idput()>
                   6970: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 6971: 
                   6972: =item *
1.394     bowersj2 6973: X<rolesinit()>
                   6974: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 6975: 
                   6976: =item *
1.551     albertel 6977: X<getsection()>
                   6978: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 6979: course $cname, return section name/number or '' for "not in course"
                   6980: and '-1' for "no section"
                   6981: 
                   6982: =item *
1.394     bowersj2 6983: X<userenvironment()>
                   6984: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 6985: passed in @what from the requested user's environment, returns a hash
                   6986: 
                   6987: =back
                   6988: 
                   6989: =head2 User Roles
                   6990: 
                   6991: =over 4
                   6992: 
                   6993: =item *
                   6994: 
                   6995: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   6996: actions
                   6997:  F: full access
                   6998:  U,I,K: authentication modes (cxx only)
                   6999:  '': forbidden
                   7000:  1: user needs to choose course
                   7001:  2: browse allowed
                   7002: 
                   7003: =item *
                   7004: 
                   7005: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7006: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7007: and course level
                   7008: 
                   7009: =item *
                   7010: 
                   7011: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7012: explanation of a user role term
                   7013: 
                   7014: =back
                   7015: 
                   7016: =head2 User Modification
                   7017: 
                   7018: =over 4
                   7019: 
                   7020: =item *
                   7021: 
                   7022: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7023: user for the level given by URL.  Optional start and end dates (leave empty
                   7024: string or zero for "no date")
1.191     harris41 7025: 
                   7026: =item *
                   7027: 
1.243     albertel 7028: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7029: change a users, password, possible return values are: ok,
                   7030: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7031: refused
1.191     harris41 7032: 
                   7033: =item *
                   7034: 
1.243     albertel 7035: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7036: 
                   7037: =item *
                   7038: 
1.243     albertel 7039: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7040: modify user
1.191     harris41 7041: 
                   7042: =item *
                   7043: 
1.286     matthew  7044: modifystudent
                   7045: 
                   7046: modify a students enrollment and identification information.
                   7047: The course id is resolved based on the current users environment.  
                   7048: This means the envoking user must be a course coordinator or otherwise
                   7049: associated with a course.
                   7050: 
1.297     matthew  7051: This call is essentially a wrapper for lonnet::modifyuser and
                   7052: lonnet::modify_student_enrollment
1.286     matthew  7053: 
                   7054: Inputs: 
                   7055: 
                   7056: =over 4
                   7057: 
                   7058: =item B<$udom> Students loncapa domain
                   7059: 
                   7060: =item B<$uname> Students loncapa login name
                   7061: 
                   7062: =item B<$uid> Students id/student number
                   7063: 
                   7064: =item B<$umode> Students authentication mode
                   7065: 
                   7066: =item B<$upass> Students password
                   7067: 
                   7068: =item B<$first> Students first name
                   7069: 
                   7070: =item B<$middle> Students middle name
                   7071: 
                   7072: =item B<$last> Students last name
                   7073: 
                   7074: =item B<$gene> Students generation
                   7075: 
                   7076: =item B<$usec> Students section in course
                   7077: 
                   7078: =item B<$end> Unix time of the roles expiration
                   7079: 
                   7080: =item B<$start> Unix time of the roles start date
                   7081: 
                   7082: =item B<$forceid> If defined, allow $uid to be changed
                   7083: 
                   7084: =item B<$desiredhome> server to use as home server for student
                   7085: 
                   7086: =back
1.297     matthew  7087: 
                   7088: =item *
                   7089: 
                   7090: modify_student_enrollment
                   7091: 
                   7092: Change a students enrollment status in a class.  The environment variable
                   7093: 'role.request.course' must be defined for this function to proceed.
                   7094: 
                   7095: Inputs:
                   7096: 
                   7097: =over 4
                   7098: 
                   7099: =item $udom, students domain
                   7100: 
                   7101: =item $uname, students name
                   7102: 
                   7103: =item $uid, students user id
                   7104: 
                   7105: =item $first, students first name
                   7106: 
                   7107: =item $middle
                   7108: 
                   7109: =item $last
                   7110: 
                   7111: =item $gene
                   7112: 
                   7113: =item $usec
                   7114: 
                   7115: =item $end
                   7116: 
                   7117: =item $start
                   7118: 
                   7119: =back
                   7120: 
1.191     harris41 7121: 
                   7122: =item *
                   7123: 
1.243     albertel 7124: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7125: custom role; give a custom role to a user for the level given by URL.  Specify
                   7126: name and domain of role author, and role name
1.191     harris41 7127: 
                   7128: =item *
                   7129: 
1.243     albertel 7130: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7131: 
                   7132: =item *
                   7133: 
1.243     albertel 7134: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7135: 
                   7136: =back
                   7137: 
                   7138: =head2 Course Infomation
                   7139: 
                   7140: =over 4
1.191     harris41 7141: 
                   7142: =item *
                   7143: 
1.631     albertel 7144: coursedescription($courseid) : returns a hash of information about the
                   7145: specified course id, including all environment settings for the
                   7146: course, the description of the course will be in the hash under the
                   7147: key 'description'
1.191     harris41 7148: 
                   7149: =item *
                   7150: 
1.624     albertel 7151: resdata($name,$domain,$type,@which) : request for current parameter
                   7152: setting for a specific $type, where $type is either 'course' or 'user',
                   7153: @what should be a list of parameters to ask about. This routine caches
                   7154: answers for 5 minutes.
1.243     albertel 7155: 
                   7156: =back
                   7157: 
                   7158: =head2 Course Modification
                   7159: 
                   7160: =over 4
1.191     harris41 7161: 
                   7162: =item *
                   7163: 
1.243     albertel 7164: writecoursepref($courseid,%prefs) : write preferences (environment
                   7165: database) for a course
1.191     harris41 7166: 
                   7167: =item *
                   7168: 
1.243     albertel 7169: createcourse($udom,$description,$url) : make/modify course
                   7170: 
                   7171: =back
                   7172: 
                   7173: =head2 Resource Subroutines
                   7174: 
                   7175: =over 4
1.191     harris41 7176: 
                   7177: =item *
                   7178: 
1.243     albertel 7179: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7180: 
                   7181: =item *
                   7182: 
1.243     albertel 7183: repcopy($filename) : subscribes to the requested file, and attempts to
                   7184: replicate from the owning library server, Might return
1.607     raeburn  7185: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7186: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7187: resource. Expects the local filesystem pathname
                   7188: (/home/httpd/html/res/....)
                   7189: 
                   7190: =back
                   7191: 
                   7192: =head2 Resource Information
                   7193: 
                   7194: =over 4
1.191     harris41 7195: 
                   7196: =item *
                   7197: 
1.243     albertel 7198: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7199: a vairety of different possible values, $varname should be a request
                   7200: string, and the other parameters can be used to specify who and what
                   7201: one is asking about.
                   7202: 
                   7203: Possible values for $varname are environment.lastname (or other item
                   7204: from the envirnment hash), user.name (or someother aspect about the
                   7205: user), resource.0.maxtries (or some other part and parameter of a
                   7206: resource)
1.204     albertel 7207: 
                   7208: =item *
                   7209: 
1.243     albertel 7210: directcondval($number) : get current value of a condition; reads from a state
                   7211: string
1.204     albertel 7212: 
                   7213: =item *
                   7214: 
1.243     albertel 7215: condval($condidx) : value of condition index based on state
1.204     albertel 7216: 
                   7217: =item *
                   7218: 
1.243     albertel 7219: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7220: resource's metadata, $what should be either a specific key, or either
                   7221: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7222: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7223: 
                   7224: this function automatically caches all requests
1.191     harris41 7225: 
                   7226: =item *
                   7227: 
1.243     albertel 7228: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7229: network of library servers; returns file handle of where SQL and regex results
                   7230: will be stored for query
1.191     harris41 7231: 
                   7232: =item *
                   7233: 
1.243     albertel 7234: symbread($filename) : return symbolic list entry (filename argument optional);
                   7235: returns the data handle
1.191     harris41 7236: 
                   7237: =item *
                   7238: 
1.243     albertel 7239: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7240: a possible symb for the URL in $thisfn, and if is an encryypted
                   7241: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7242: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7243: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7244: 
1.191     harris41 7245: 
                   7246: =item *
                   7247: 
1.243     albertel 7248: symbclean($symb) : removes versions numbers from a symb, returns the
                   7249: cleaned symb
1.191     harris41 7250: 
                   7251: =item *
                   7252: 
1.243     albertel 7253: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7254: course map, user must be in a course for it to work.
1.191     harris41 7255: 
                   7256: =item *
                   7257: 
1.243     albertel 7258: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7259: 
                   7260: =item *
                   7261: 
1.243     albertel 7262: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7263: a random seed, all arguments are optional, if they aren't sent it uses the
                   7264: environment to derive them. Note: if symb isn't sent and it can't get one
                   7265: from &symbread it will use the current time as its return value
1.191     harris41 7266: 
                   7267: =item *
                   7268: 
1.243     albertel 7269: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7270: unfakeable, receipt
1.191     harris41 7271: 
                   7272: =item *
                   7273: 
1.620     albertel 7274: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7275: 
                   7276: =item *
                   7277: 
1.243     albertel 7278: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7279: 
                   7280: =item *
                   7281: 
1.243     albertel 7282: 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 7283: 
                   7284: =item *
                   7285: 
1.243     albertel 7286: 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 7287: 
                   7288: =item *
                   7289: 
1.243     albertel 7290: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7291: 
                   7292: =item *
                   7293: 
1.243     albertel 7294: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7295: forcing spreadsheet to reevaluate the resource scores next time.
                   7296: 
                   7297: =back
                   7298: 
                   7299: =head2 Storing/Retreiving Data
                   7300: 
                   7301: =over 4
1.191     harris41 7302: 
                   7303: =item *
                   7304: 
1.243     albertel 7305: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7306: for this url; hashref needs to be given and should be a \%hashname; the
                   7307: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7308: be derived from the env
1.191     harris41 7309: 
                   7310: =item *
                   7311: 
1.243     albertel 7312: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7313: uses critical subroutine
1.191     harris41 7314: 
                   7315: =item *
                   7316: 
1.243     albertel 7317: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7318: all args are optional
1.191     harris41 7319: 
                   7320: =item *
                   7321: 
1.717     albertel 7322: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7323: dumps the complete (or key matching regexp) namespace into a hash
                   7324: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7325: normally &store()ed into
                   7326: 
                   7327: $range should be either an integer '100' (give me the first 100
                   7328:                                            matching records)
                   7329:               or be  two integers sperated by a - with no spaces
                   7330:                  '30-50' (give me the 30th through the 50th matching
                   7331:                           records)
                   7332: 
                   7333: 
                   7334: =item *
                   7335: 
                   7336: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7337: replaces a &store() version of data with a replacement set of data
                   7338: for a particular resource in a namespace passed in the $storehash hash 
                   7339: reference
                   7340: 
                   7341: =item *
                   7342: 
1.243     albertel 7343: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7344: works very similar to store/cstore, but all data is stored in a
                   7345: temporary location and can be reset using tmpreset, $storehash should
                   7346: be a hash reference, returns nothing on success
1.191     harris41 7347: 
                   7348: =item *
                   7349: 
1.243     albertel 7350: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7351: similar to restore, but all data is stored in a temporary location and
                   7352: can be reset using tmpreset. Returns a hash of values on success,
                   7353: error string otherwise.
1.191     harris41 7354: 
                   7355: =item *
                   7356: 
1.243     albertel 7357: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7358: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7359: 
                   7360: =item *
                   7361: 
1.243     albertel 7362: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7363: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7364: 
                   7365: =item *
                   7366: 
1.243     albertel 7367: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7368: namesp ($udom and $uname are optional)
1.191     harris41 7369: 
                   7370: =item *
                   7371: 
1.702     albertel 7372: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7373: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7374: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7375: 
1.702     albertel 7376: $range should be either an integer '100' (give me the first 100
                   7377:                                            matching records)
                   7378:               or be  two integers sperated by a - with no spaces
                   7379:                  '30-50' (give me the 30th through the 50th matching
                   7380:                           records)
1.449     matthew  7381: =item *
                   7382: 
                   7383: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7384: $store can be a scalar, an array reference, or if the amount to be 
                   7385: incremented is > 1, a hash reference.
                   7386: 
                   7387: ($udom and $uname are optional)
1.191     harris41 7388: 
                   7389: =item *
                   7390: 
1.243     albertel 7391: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7392: ($udom and $uname are optional)
1.191     harris41 7393: 
                   7394: =item *
                   7395: 
1.243     albertel 7396: cput($namespace,$storehash,$udom,$uname) : critical put
                   7397: ($udom and $uname are optional)
1.191     harris41 7398: 
                   7399: =item *
                   7400: 
1.243     albertel 7401: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7402: reference filled in from namesp (encrypts the return communication)
                   7403: ($udom and $uname are optional)
1.191     harris41 7404: 
                   7405: =item *
                   7406: 
1.243     albertel 7407: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7408: critical subroutine
                   7409: 
                   7410: =back
                   7411: 
                   7412: =head2 Network Status Functions
                   7413: 
                   7414: =over 4
1.191     harris41 7415: 
                   7416: =item *
                   7417: 
                   7418: dirlist($uri) : return directory list based on URI
                   7419: 
                   7420: =item *
                   7421: 
1.243     albertel 7422: spareserver() : find server with least workload from spare.tab
                   7423: 
                   7424: =back
                   7425: 
                   7426: =head2 Apache Request
                   7427: 
                   7428: =over 4
1.191     harris41 7429: 
                   7430: =item *
                   7431: 
1.243     albertel 7432: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7433: localhost, posts hash
                   7434: 
                   7435: =back
                   7436: 
                   7437: =head2 Data to String to Data
                   7438: 
                   7439: =over 4
1.191     harris41 7440: 
                   7441: =item *
                   7442: 
1.243     albertel 7443: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7444: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7445: 
                   7446: =item *
                   7447: 
1.243     albertel 7448: hashref2str($hashref) : convert a hashref into a string complete with
                   7449: escaping and '=' and '&' separators, supports elements that are
                   7450: arrayrefs and hashrefs
1.191     harris41 7451: 
                   7452: =item *
                   7453: 
1.243     albertel 7454: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7455: with escaping and '&' separators, supports elements that are arrayrefs
                   7456: and hashrefs
1.191     harris41 7457: 
                   7458: =item *
                   7459: 
1.243     albertel 7460: str2hash($string) : convert string to hash using unescaping and
                   7461: splitting on '=' and '&', supports elements that are arrayrefs and
                   7462: hashrefs
1.191     harris41 7463: 
                   7464: =item *
                   7465: 
1.243     albertel 7466: str2array($string) : convert string to hash using unescaping and
                   7467: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7468: 
                   7469: =back
                   7470: 
                   7471: =head2 Logging Routines
                   7472: 
                   7473: =over 4
                   7474: 
                   7475: These routines allow one to make log messages in the lonnet.log and
                   7476: lonnet.perm logfiles.
1.191     harris41 7477: 
                   7478: =item *
                   7479: 
1.243     albertel 7480: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 7481: 
                   7482: =item *
                   7483: 
1.243     albertel 7484: logthis() : append message to the normal lonnet.log file, it gets
                   7485: preiodically rolled over and deleted.
1.191     harris41 7486: 
                   7487: =item *
                   7488: 
1.243     albertel 7489: logperm() : append a permanent message to lonnet.perm.log, this log
                   7490: file never gets deleted by any automated portion of the system, only
                   7491: messages of critical importance should go in here.
                   7492: 
                   7493: =back
                   7494: 
                   7495: =head2 General File Helper Routines
                   7496: 
                   7497: =over 4
1.191     harris41 7498: 
                   7499: =item *
                   7500: 
1.481     raeburn  7501: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7502: (a) files in /uploaded
                   7503:   (i) If a local copy of the file exists - 
                   7504:       compares modification date of local copy with last-modified date for 
                   7505:       definitive version stored on home server for course. If local copy is 
                   7506:       stale, requests a new version from the home server and stores it. 
                   7507:       If the original has been removed from the home server, then local copy 
                   7508:       is unlinked.
                   7509:   (ii) If local copy does not exist -
                   7510:       requests the file from the home server and stores it. 
                   7511:   
                   7512:   If $caller is 'uploadrep':  
                   7513:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7514:     for request for files originally uploaded via DOCS. 
                   7515:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7516:   
                   7517:   Otherwise:
                   7518:      This indicates a call from the content generation phase of the request.
                   7519:      -  returns the entire contents of the file or -1.
                   7520:      
                   7521: (b) files in /res
                   7522:    - returns the entire contents of a file or -1; 
                   7523:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7524: 
1.712     albertel 7525: 
                   7526: =item *
                   7527: 
                   7528: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   7529:                   reference
                   7530: 
                   7531: returns either a stat() list of data about the file or an empty list
                   7532: if the file doesn't exist or couldn't find out about it (connection
                   7533: problems or user unknown)
                   7534: 
1.191     harris41 7535: =item *
                   7536: 
1.243     albertel 7537: filelocation($dir,$file) : returns file system location of a file
                   7538: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7539: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7540: and a file of ../bob will become /a/bob)
1.191     harris41 7541: 
                   7542: =item *
                   7543: 
                   7544: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7545: filelocation except for hrefs
                   7546: 
                   7547: =item *
                   7548: 
                   7549: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7550: 
1.243     albertel 7551: =back
                   7552: 
1.608     albertel 7553: =head2 Usererfile file routines (/uploaded*)
                   7554: 
                   7555: =over 4
                   7556: 
                   7557: =item *
                   7558: 
                   7559: userfileupload(): main rotine for putting a file in a user or course's
                   7560:                   filespace, arguments are,
                   7561: 
1.620     albertel 7562:  formname - required - this is the name of the element in $env where the
1.608     albertel 7563:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7564:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7565:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7566:  coursedoc - if true, store the file in the course of the active role
                   7567:              of the current user
                   7568:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7569:          if undefined, it will be placed in "unknown"
                   7570: 
                   7571:  (This routine calls clean_filename() to remove any dangerous
                   7572:  characters from the filename, and then calls finuserfileupload() to
                   7573:  complete the transaction)
                   7574: 
                   7575:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7576:  and /adm/notfound.html if unsuccessful
                   7577: 
                   7578: =item *
                   7579: 
                   7580: clean_filename(): routine for cleaing a filename up for storage in
                   7581:                  userfile space, argument is:
                   7582: 
                   7583:  filename - proposed filename
                   7584: 
                   7585: returns: the new clean filename
                   7586: 
                   7587: =item *
                   7588: 
                   7589: finishuserfileupload(): routine that creaes and sends the file to
                   7590: userspace, probably shouldn't be called directly
                   7591: 
                   7592:   docuname: username or courseid of destination for the file
                   7593:   docudom: domain of user/course of destination for the file
                   7594:   formname: same as for userfileupload()
                   7595:   fname: filename (inculding subdirectories) for the file
                   7596: 
                   7597:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7598:  and /adm/notfound.html if unsuccessful
                   7599: 
                   7600: =item *
                   7601: 
                   7602: renameuserfile(): renames an existing userfile to a new name
                   7603: 
                   7604:   Args:
                   7605:    docuname: username or courseid of destination for the file
                   7606:    docudom: domain of user/course of destination for the file
                   7607:    old: current file name (including any subdirs under userfiles)
                   7608:    new: desired file name (including any subdirs under userfiles)
                   7609: 
                   7610: =item *
                   7611: 
                   7612: mkdiruserfile(): creates a directory is a userfiles dir
                   7613: 
                   7614:   Args:
                   7615:    docuname: username or courseid of destination for the file
                   7616:    docudom: domain of user/course of destination for the file
                   7617:    dir: dir to create (including any subdirs under userfiles)
                   7618: 
                   7619: =item *
                   7620: 
                   7621: removeuserfile(): removes a file that exists in userfiles
                   7622: 
                   7623:   Args:
                   7624:    docuname: username or courseid of destination for the file
                   7625:    docudom: domain of user/course of destination for the file
                   7626:    fname: filname to delete (including any subdirs under userfiles)
                   7627: 
                   7628: =item *
                   7629: 
                   7630: removeuploadedurl(): convience function for removeuserfile()
                   7631: 
                   7632:   Args:
                   7633:    url:  a full /uploaded/... url to delete
                   7634: 
                   7635: =back
                   7636: 
1.243     albertel 7637: =head2 HTTP Helper Routines
                   7638: 
                   7639: =over 4
                   7640: 
1.191     harris41 7641: =item *
                   7642: 
                   7643: escape() : unpack non-word characters into CGI-compatible hex codes
                   7644: 
                   7645: =item *
                   7646: 
                   7647: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   7648: 
1.243     albertel 7649: =back
                   7650: 
                   7651: =head1 PRIVATE SUBROUTINES
                   7652: 
                   7653: =head2 Underlying communication routines (Shouldn't call)
                   7654: 
                   7655: =over 4
                   7656: 
                   7657: =item *
                   7658: 
                   7659: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   7660: 
                   7661: =item *
                   7662: 
                   7663: reply() : uses subreply to send a message to remote machine, logs all failures
                   7664: 
                   7665: =item *
                   7666: 
                   7667: critical() : passes a critical message to another server; if cannot
                   7668: get through then place message in connection buffer directory and
                   7669: returns con_delayed, if incapable of saving message, returns
                   7670: con_failed
                   7671: 
                   7672: =item *
                   7673: 
                   7674: reconlonc() : tries to reconnect lonc client processes.
                   7675: 
                   7676: =back
                   7677: 
                   7678: =head2 Resource Access Logging
                   7679: 
                   7680: =over 4
                   7681: 
                   7682: =item *
                   7683: 
                   7684: flushcourselogs() : flush (save) buffer logs and access logs
                   7685: 
                   7686: =item *
                   7687: 
                   7688: courselog($what) : save message for course in hash
                   7689: 
                   7690: =item *
                   7691: 
                   7692: courseacclog($what) : save message for course using &courselog().  Perform
                   7693: special processing for specific resource types (problems, exams, quizzes, etc).
                   7694: 
1.191     harris41 7695: =item *
                   7696: 
                   7697: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   7698: as a PerlChildExitHandler
1.243     albertel 7699: 
                   7700: =back
                   7701: 
                   7702: =head2 Other
                   7703: 
                   7704: =over 4
                   7705: 
                   7706: =item *
                   7707: 
                   7708: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 7709: 
                   7710: =back
                   7711: 
                   7712: =cut

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