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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.740   ! www         4: # $Id: lonnet.pm,v 1.739 2006/05/18 01:08:54 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.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;
1.740   ! www        55: use lib '/home/httpd/lib/perl';
        !            56: use LONCAPA;
        !            57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.374     www       284: # ------------------------------------------- Transfer profile into environment
                    285: 
                    286: sub transfer_profile_to_env {
                    287:     my ($lonidsdir,$handle)=@_;
1.720     albertel  288:     if (!defined($lonidsdir)) {
                    289: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    290:     }
                    291:     if (!defined($handle)) {
                    292:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    293:     }
                    294: 
1.374     www       295:     my @profile;
                    296:     {
1.448     albertel  297: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       298: 	flock($idf,LOCK_SH);
                    299: 	@profile=<$idf>;
1.448     albertel  300: 	close($idf);
1.374     www       301:     }
                    302:     my $envi;
1.433     matthew   303:     my %Remove;
1.374     www       304:     for ($envi=0;$envi<=$#profile;$envi++) {
                    305: 	chomp($profile[$envi]);
1.690     albertel  306: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  307: 	$envname=&unescape($envname);
                    308: 	$envvalue=&unescape($envvalue);
1.619     albertel  309: 	$env{$envname} = $envvalue;
1.433     matthew   310:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    311:             if ($time < time-300) {
                    312:                 $Remove{$key}++;
                    313:             }
                    314:         }
                    315:     }
1.619     albertel  316:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   317:     foreach my $expired_key (keys(%Remove)) {
                    318:         &delenv($expired_key);
1.374     www       319:     }
1.1       albertel  320: }
                    321: 
1.5       www       322: # ---------------------------------------------------------- Append Environment
                    323: 
                    324: sub appenv {
1.6       www       325:     my %newenv=@_;
1.692     albertel  326:     foreach my $key (keys(%newenv)) {
                    327: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  328:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  329:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       330:                 .'</font>');
1.692     albertel  331: 	    delete($newenv{$key});
1.35      www       332:         } else {
1.692     albertel  333:             $env{$key}=$newenv{$key};
1.35      www       334:         }
1.191     harris41  335:     }
1.95      www       336: 
                    337:     my $lockfh;
1.620     albertel  338:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  339: 	return 'error: '.$!;
1.95      www       340:     }
                    341:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  342:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       343:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  344:          close($lockfh);
1.95      www       345:          return 'error: '.$!;
                    346:     }
                    347: 
1.6       www       348:     my @oldenv;
                    349:     {
1.448     albertel  350: 	my $fh;
1.620     albertel  351: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  352: 	    return 'error: '.$!;
                    353: 	}
                    354: 	@oldenv=<$fh>;
                    355: 	close($fh);
1.6       www       356:     }
                    357:     for (my $i=0; $i<=$#oldenv; $i++) {
                    358:         chomp($oldenv[$i]);
1.9       www       359:         if ($oldenv[$i] ne '') {
1.690     albertel  360: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.726     albertel  361: 	    $name=&unescape($name);
                    362: 	    $value=&unescape($value);
1.448     albertel  363: 	    unless (defined($newenv{$name})) {
                    364: 		$newenv{$name}=$value;
                    365: 	    }
1.9       www       366:         }
1.6       www       367:     }
                    368:     {
1.448     albertel  369: 	my $fh;
1.620     albertel  370: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  371: 	    return 'error';
                    372: 	}
                    373: 	my $newname;
                    374: 	foreach $newname (keys %newenv) {
1.726     albertel  375: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
1.448     albertel  376: 	}
                    377: 	close($fh);
1.56      www       378:     }
1.448     albertel  379: 	
                    380:     close($lockfh);
1.56      www       381:     return 'ok';
                    382: }
                    383: # ----------------------------------------------------- Delete from Environment
                    384: 
                    385: sub delenv {
                    386:     my $delthis=shift;
                    387:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  388:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       389:                 "Attempt to delete from environment ".$delthis);
                    390:         return 'error';
                    391:     }
                    392:     my @oldenv;
                    393:     {
1.448     albertel  394: 	my $fh;
1.620     albertel  395: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  396: 	    return 'error';
                    397: 	}
                    398: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  399: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  400: 		     'Could not obtain shared lock in delenv: '.$!);
                    401: 	    close($fh);
                    402: 	    return 'error: '.$!;
                    403: 	}
                    404: 	@oldenv=<$fh>;
                    405: 	close($fh);
1.56      www       406:     }
                    407:     {
1.448     albertel  408: 	my $fh;
1.620     albertel  409: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  410: 	    return 'error';
                    411: 	}
                    412: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  413: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  414: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    415: 	    close($fh);
                    416: 	    return 'error: '.$!;
                    417: 	}
1.692     albertel  418: 	foreach my $cur_key (@oldenv) {
1.726     albertel  419: 	    my $unescaped_cur_key = &unescape($cur_key);
                    420: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    421:                 my ($key) = split('=',$cur_key,2);
                    422: 		$key = &unescape($key);
1.619     albertel  423:                 delete($env{$key});
1.473     matthew   424:             } else {
1.692     albertel  425:                 print $fh $cur_key; 
1.473     matthew   426:             }
1.448     albertel  427: 	}
                    428: 	close($fh);
1.5       www       429:     }
                    430:     return 'ok';
1.369     albertel  431: }
                    432: 
                    433: # ------------------------------------------ Find out current server userload
                    434: # there is a copy in lond
                    435: sub userload {
                    436:     my $numusers=0;
                    437:     {
                    438: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    439: 	my $filename;
                    440: 	my $curtime=time;
                    441: 	while ($filename=readdir(LONIDS)) {
                    442: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  443: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  444: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  445: 	}
                    446: 	closedir(LONIDS);
                    447:     }
                    448:     my $userloadpercent=0;
                    449:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    450:     if ($maxuserload) {
1.371     albertel  451: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  452:     }
1.372     albertel  453:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  454:     return $userloadpercent;
1.283     www       455: }
                    456: 
                    457: # ------------------------------------------ Fight off request when overloaded
                    458: 
                    459: sub overloaderror {
                    460:     my ($r,$checkserver)=@_;
                    461:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    462:     my $loadavg;
                    463:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  464:        open(my $loadfile,'/proc/loadavg');
1.283     www       465:        $loadavg=<$loadfile>;
                    466:        $loadavg =~ s/\s.*//g;
1.285     matthew   467:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  468:        close($loadfile);
1.283     www       469:     } else {
                    470:        $loadavg=&reply('load',$checkserver);
                    471:     }
1.285     matthew   472:     my $overload=$loadavg-100;
1.283     www       473:     if ($overload>0) {
1.285     matthew   474: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       475:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       476:         return 413;
1.283     www       477:     }    
                    478:     return '';
1.5       www       479: }
1.1       albertel  480: 
                    481: # ------------------------------ Find server with least workload from spare.tab
1.11      www       482: 
1.1       albertel  483: sub spareserver {
1.670     albertel  484:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  485:     my $tryserver;
                    486:     my $spareserver='';
1.370     albertel  487:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    488:     my $lowestserver=$loadpercent > $userloadpercent?
                    489: 	             $loadpercent :  $userloadpercent;
1.670     albertel  490:     foreach $tryserver (keys(%spareid)) {
                    491: 	my $loadans=&reply('load',$tryserver);
                    492: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  493: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    494: 	    next; #didn't get a number from the server
                    495: 	}
                    496: 	my $answer;
                    497: 	if ($loadans =~ /\d/) {
                    498: 	    if ($userloadans =~ /\d/) {
                    499: 		#both are numbers, pick the bigger one
                    500: 		$answer=$loadans > $userloadans?
                    501: 		    $loadans :  $userloadans;
                    502: 	    } else {
                    503: 		$answer = $loadans;
                    504: 	    }
                    505: 	} else {
                    506: 	    $answer = $userloadans;
                    507: 	}
                    508: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  509: 	    if ($want_server_name) {
                    510: 		$spareserver=$tryserver;
                    511: 	    } else {
                    512: 		$spareserver="http://$hostname{$tryserver}";
                    513: 	    }
1.411     albertel  514: 	    $lowestserver=$answer;
                    515: 	}
1.370     albertel  516:     }
1.1       albertel  517:     return $spareserver;
1.202     matthew   518: }
                    519: 
                    520: # --------------------------------------------- Try to change a user's password
                    521: 
                    522: sub changepass {
                    523:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    524:     $currentpass = &escape($currentpass);
                    525:     $newpass     = &escape($newpass);
                    526:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    527: 		       $server);
                    528:     if (! $answer) {
                    529: 	&logthis("No reply on password change request to $server ".
                    530: 		 "by $uname in domain $udom.");
                    531:     } elsif ($answer =~ "^ok") {
                    532:         &logthis("$uname in $udom successfully changed their password ".
                    533: 		 "on $server.");
                    534:     } elsif ($answer =~ "^pwchange_failure") {
                    535: 	&logthis("$uname in $udom was unable to change their password ".
                    536: 		 "on $server.  The action was blocked by either lcpasswd ".
                    537: 		 "or pwchange");
                    538:     } elsif ($answer =~ "^non_authorized") {
                    539:         &logthis("$uname in $udom did not get their password correct when ".
                    540: 		 "attempting to change it on $server.");
                    541:     } elsif ($answer =~ "^auth_mode_error") {
                    542:         &logthis("$uname in $udom attempted to change their password despite ".
                    543: 		 "not being locally or internally authenticated on $server.");
                    544:     } elsif ($answer =~ "^unknown_user") {
                    545:         &logthis("$uname in $udom attempted to change their password ".
                    546: 		 "on $server but were unable to because $server is not ".
                    547: 		 "their home server.");
                    548:     } elsif ($answer =~ "^refused") {
                    549: 	&logthis("$server refused to change $uname in $udom password because ".
                    550: 		 "it was sent an unencrypted request to change the password.");
                    551:     }
                    552:     return $answer;
1.1       albertel  553: }
                    554: 
1.169     harris41  555: # ----------------------- Try to determine user's current authentication scheme
                    556: 
                    557: sub queryauthenticate {
                    558:     my ($uname,$udom)=@_;
1.456     albertel  559:     my $uhome=&homeserver($uname,$udom);
                    560:     if (!$uhome) {
                    561: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    562: 	return 'no_host';
                    563:     }
                    564:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    565:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    566: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  567:     }
1.456     albertel  568:     return $answer;
1.169     harris41  569: }
                    570: 
1.1       albertel  571: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       572: 
1.1       albertel  573: sub authenticate {
                    574:     my ($uname,$upass,$udom)=@_;
1.12      www       575:     $upass=escape($upass);
1.199     www       576:     $uname=~s/\W//g;
1.471     albertel  577:     my $uhome=&homeserver($uname,$udom);
                    578:     if (!$uhome) {
                    579: 	&logthis("User $uname at $udom is unknown in authenticate");
                    580: 	return 'no_host';
1.1       albertel  581:     }
1.471     albertel  582:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    583:     if ($answer eq 'authorized') {
                    584: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    585: 	return $uhome; 
                    586:     }
                    587:     if ($answer eq 'non_authorized') {
                    588: 	&logthis("User $uname at $udom rejected by $uhome");
                    589: 	return 'no_host'; 
1.9       www       590:     }
1.471     albertel  591:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  592:     return 'no_host';
                    593: }
                    594: 
                    595: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       596: 
1.599     albertel  597: my %homecache;
1.1       albertel  598: sub homeserver {
1.230     stredwic  599:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  600:     my $index="$uname:$udom";
1.426     albertel  601: 
1.599     albertel  602:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  603:     my $tryserver;
                    604:     foreach $tryserver (keys %libserv) {
1.230     stredwic  605:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  606: 		 exists($badServerCache{$tryserver}));
1.1       albertel  607: 	if ($hostdom{$tryserver} eq $udom) {
                    608:            my $answer=reply("home:$udom:$uname",$tryserver);
                    609:            if ($answer eq 'found') { 
1.599     albertel  610: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  611:            } elsif ($answer eq 'no_host') {
                    612: 	       $badServerCache{$tryserver}=1;
1.221     matthew   613:            }
1.1       albertel  614:        }
                    615:     }    
                    616:     return 'no_host';
1.70      www       617: }
                    618: 
                    619: # ------------------------------------- Find the usernames behind a list of IDs
                    620: 
                    621: sub idget {
                    622:     my ($udom,@ids)=@_;
                    623:     my %returnhash=();
                    624:     
                    625:     my $tryserver;
                    626:     foreach $tryserver (keys %libserv) {
                    627:        if ($hostdom{$tryserver} eq $udom) {
                    628: 	  my $idlist=join('&',@ids);
                    629:           $idlist=~tr/A-Z/a-z/; 
                    630: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    631:           my @answer=();
1.76      www       632:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       633: 	      @answer=split(/\&/,$reply);
                    634:           }                    ;
                    635:           my $i;
                    636:           for ($i=0;$i<=$#ids;$i++) {
                    637:               if ($answer[$i]) {
                    638: 		  $returnhash{$ids[$i]}=$answer[$i];
                    639:               } 
                    640:           }
                    641:        }
                    642:     }    
                    643:     return %returnhash;
                    644: }
                    645: 
                    646: # ------------------------------------- Find the IDs behind a list of usernames
                    647: 
                    648: sub idrget {
                    649:     my ($udom,@unames)=@_;
                    650:     my %returnhash=();
1.191     harris41  651:     foreach (@unames) {
1.70      www       652:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  653:     }
1.70      www       654:     return %returnhash;
                    655: }
                    656: 
                    657: # ------------------------------- Store away a list of names and associated IDs
                    658: 
                    659: sub idput {
                    660:     my ($udom,%ids)=@_;
                    661:     my %servers=();
1.191     harris41  662:     foreach (keys %ids) {
1.487     albertel  663: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       664:         my $uhom=&homeserver($_,$udom);
                    665:         if ($uhom ne 'no_host') {
                    666:             my $id=&escape($ids{$_});
                    667:             $id=~tr/A-Z/a-z/;
                    668:             my $unam=&escape($_);
                    669: 	    if ($servers{$uhom}) {
                    670: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    671:             } else {
                    672:                 $servers{$uhom}=$id.'='.$unam;
                    673:             }
                    674:         }
1.191     harris41  675:     }
                    676:     foreach (keys %servers) {
1.70      www       677:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  678:     }
1.344     www       679: }
                    680: 
                    681: # --------------------------------------------------- Assign a key to a student
                    682: 
                    683: sub assign_access_key {
1.364     www       684: #
                    685: # a valid key looks like uname:udom#comments
                    686: # comments are being appended
                    687: #
1.498     www       688:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    689:     $kdom=
1.620     albertel  690:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       691:     $knum=
1.620     albertel  692:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       693:     $cdom=
1.620     albertel  694:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       695:     $cnum=
1.620     albertel  696:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    697:     $udom=$env{'user.name'} unless (defined($udom));
                    698:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       699:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       700:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  701:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       702:                                                   # assigned to this person
                    703:                                                   # - this should not happen,
1.345     www       704:                                                   # unless something went wrong
                    705:                                                   # the first time around
                    706: # ready to assign
1.364     www       707:         $logentry=$1.'; '.$logentry;
1.496     www       708:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       709:                                                  $kdom,$knum) eq 'ok') {
1.345     www       710: # key now belongs to user
1.346     www       711: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       712:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    713:                 &appenv('environment.'.$envkey => $ckey);
                    714:                 return 'ok';
                    715:             } else {
                    716:                 return 
                    717:   'error: Count not permanently assign key, will need to be re-entered later.';
                    718: 	    }
                    719:         } else {
                    720:             return 'error: Could not assign key, try again later.';
                    721:         }
1.364     www       722:     } elsif (!$existing{$ckey}) {
1.345     www       723: # the key does not exist
                    724: 	return 'error: The key does not exist';
                    725:     } else {
                    726: # the key is somebody else's
                    727: 	return 'error: The key is already in use';
                    728:     }
1.344     www       729: }
                    730: 
1.364     www       731: # ------------------------------------------ put an additional comment on a key
                    732: 
                    733: sub comment_access_key {
                    734: #
                    735: # a valid key looks like uname:udom#comments
                    736: # comments are being appended
                    737: #
                    738:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    739:     $cdom=
1.620     albertel  740:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       741:     $cnum=
1.620     albertel  742:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       743:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    744:     if ($existing{$ckey}) {
                    745:         $existing{$ckey}.='; '.$logentry;
                    746: # ready to assign
1.367     www       747:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       748:                                                  $cdom,$cnum) eq 'ok') {
                    749: 	    return 'ok';
                    750:         } else {
                    751: 	    return 'error: Count not store comment.';
                    752:         }
                    753:     } else {
                    754: # the key does not exist
                    755: 	return 'error: The key does not exist';
                    756:     }
                    757: }
                    758: 
1.344     www       759: # ------------------------------------------------------ Generate a set of keys
                    760: 
                    761: sub generate_access_keys {
1.364     www       762:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       763:     $cdom=
1.620     albertel  764:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       765:     $cnum=
1.620     albertel  766:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       767:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       768:     unless (($cdom) && ($cnum)) { return 0; }
                    769:     if ($number>10000) { return 0; }
                    770:     sleep(2); # make sure don't get same seed twice
                    771:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    772:     my $total=0;
                    773:     for (my $i=1;$i<=$number;$i++) {
                    774:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    775:                   sprintf("%lx",int(100000*rand)).'-'.
                    776:                   sprintf("%lx",int(100000*rand));
                    777:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    778:        $newkey=~s/0/h/g; # and also 0 and O
                    779:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    780:        if ($existing{$newkey}) {
                    781:            $i--;
                    782:        } else {
1.364     www       783: 	  if (&put('accesskeys',
                    784:               { $newkey => '# generated '.localtime().
1.620     albertel  785:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       786:                            '; '.$logentry },
                    787: 		   $cdom,$cnum) eq 'ok') {
1.344     www       788:               $total++;
                    789: 	  }
                    790:        }
                    791:     }
1.620     albertel  792:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       793:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    794:     return $total;
                    795: }
                    796: 
                    797: # ------------------------------------------------------- Validate an accesskey
                    798: 
                    799: sub validate_access_key {
                    800:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    801:     $cdom=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       803:     $cnum=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    805:     $udom=$env{'user.domain'} unless (defined($udom));
                    806:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       807:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  808:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       809: }
                    810: 
                    811: # ------------------------------------- Find the section of student in a course
1.652     albertel  812: sub devalidate_getsection_cache {
                    813:     my ($udom,$unam,$courseid)=@_;
                    814:     $courseid=~s/\_/\//g;
                    815:     $courseid=~s/^(\w)/\/$1/;
                    816:     my $hashid="$udom:$unam:$courseid";
                    817:     &devalidate_cache_new('getsection',$hashid);
                    818: }
1.298     matthew   819: 
                    820: sub getsection {
                    821:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  822:     my $cachetime=1800;
1.298     matthew   823:     $courseid=~s/\_/\//g;
                    824:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  825: 
                    826:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  827:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  828:     if (defined($cached)) { return $result; }
                    829: 
1.298     matthew   830:     my %Pending; 
                    831:     my %Expired;
                    832:     #
                    833:     # Each role can either have not started yet (pending), be active, 
                    834:     #    or have expired.
                    835:     #
                    836:     # If there is an active role, we are done.
                    837:     #
                    838:     # If there is more than one role which has not started yet, 
                    839:     #     choose the one which will start sooner
                    840:     # If there is one role which has not started yet, return it.
                    841:     #
                    842:     # If there is more than one expired role, choose the one which ended last.
                    843:     # If there is a role which has expired, return it.
                    844:     #
                    845:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    846:                         &homeserver($unam,$udom)))) {
                    847:         my ($key,$value)=split(/\=/,$_);
                    848:         $key=&unescape($key);
1.479     albertel  849:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   850:         my $section=$1;
                    851:         if ($key eq $courseid.'_st') { $section=''; }
                    852:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    853:         my $now=time;
1.548     albertel  854:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   855:             $Expired{$end}=$section;
                    856:             next;
                    857:         }
1.548     albertel  858:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   859:             $Pending{$start}=$section;
                    860:             next;
                    861:         }
1.599     albertel  862:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   863:     }
                    864:     #
                    865:     # Presumedly there will be few matching roles from the above
                    866:     # loop and the sorting time will be negligible.
                    867:     if (scalar(keys(%Pending))) {
                    868:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  869:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   870:     } 
                    871:     if (scalar(keys(%Expired))) {
                    872:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    873:         my $time = pop(@sorted);
1.599     albertel  874:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   875:     }
1.599     albertel  876:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   877: }
1.70      www       878: 
1.599     albertel  879: sub save_cache {
                    880:     &purge_remembered();
1.722     albertel  881:     #&Apache::loncommon::validate_page();
1.620     albertel  882:     undef(%env);
1.599     albertel  883: }
1.452     albertel  884: 
1.599     albertel  885: my $to_remember=-1;
                    886: my %remembered;
                    887: my %accessed;
                    888: my $kicks=0;
                    889: my $hits=0;
                    890: sub devalidate_cache_new {
                    891:     my ($name,$id,$debug) = @_;
                    892:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    893:     $id=&escape($name.':'.$id);
                    894:     $memcache->delete($id);
                    895:     delete($remembered{$id});
                    896:     delete($accessed{$id});
                    897: }
                    898: 
                    899: sub is_cached_new {
                    900:     my ($name,$id,$debug) = @_;
                    901:     $id=&escape($name.':'.$id);
                    902:     if (exists($remembered{$id})) {
                    903: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    904: 	$accessed{$id}=[&gettimeofday()];
                    905: 	$hits++;
                    906: 	return ($remembered{$id},1);
                    907:     }
                    908:     my $value = $memcache->get($id);
                    909:     if (!(defined($value))) {
                    910: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  911: 	return (undef,undef);
1.416     albertel  912:     }
1.599     albertel  913:     if ($value eq '__undef__') {
                    914: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    915: 	$value=undef;
                    916:     }
                    917:     &make_room($id,$value,$debug);
                    918:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    919:     return ($value,1);
                    920: }
                    921: 
                    922: sub do_cache_new {
                    923:     my ($name,$id,$value,$time,$debug) = @_;
                    924:     $id=&escape($name.':'.$id);
                    925:     my $setvalue=$value;
                    926:     if (!defined($setvalue)) {
                    927: 	$setvalue='__undef__';
                    928:     }
1.623     albertel  929:     if (!defined($time) ) {
                    930: 	$time=600;
                    931:     }
1.599     albertel  932:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  933:     $memcache->set($id,$setvalue,$time);
                    934:     # need to make a copy of $value
                    935:     #&make_room($id,$value,$debug);
1.599     albertel  936:     return $value;
                    937: }
                    938: 
                    939: sub make_room {
                    940:     my ($id,$value,$debug)=@_;
                    941:     $remembered{$id}=$value;
                    942:     if ($to_remember<0) { return; }
                    943:     $accessed{$id}=[&gettimeofday()];
                    944:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    945:     my $to_kick;
                    946:     my $max_time=0;
                    947:     foreach my $other (keys(%accessed)) {
                    948: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    949: 	    $to_kick=$other;
                    950: 	    $max_time=&tv_interval($accessed{$other});
                    951: 	}
                    952:     }
                    953:     delete($remembered{$to_kick});
                    954:     delete($accessed{$to_kick});
                    955:     $kicks++;
                    956:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  957:     return;
                    958: }
                    959: 
1.599     albertel  960: sub purge_remembered {
1.604     albertel  961:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    962:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  963:     undef(%remembered);
                    964:     undef(%accessed);
1.428     albertel  965: }
1.70      www       966: # ------------------------------------- Read an entry from a user's environment
                    967: 
                    968: sub userenvironment {
                    969:     my ($udom,$unam,@what)=@_;
                    970:     my %returnhash=();
                    971:     my @answer=split(/\&/,
                    972:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    973:                       &homeserver($unam,$udom)));
                    974:     my $i;
                    975:     for ($i=0;$i<=$#what;$i++) {
                    976: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    977:     }
                    978:     return %returnhash;
1.1       albertel  979: }
                    980: 
1.617     albertel  981: # ---------------------------------------------------------- Get a studentphoto
                    982: sub studentphoto {
                    983:     my ($udom,$unam,$ext) = @_;
                    984:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   985:     if (defined($env{'request.course.id'})) {
1.708     raeburn   986:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   987:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    988:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    989:             } else {
                    990:                 my ($result,$perm_reqd)=
1.707     albertel  991: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   992:                 if ($result eq 'ok') {
                    993:                     if (!($perm_reqd eq 'yes')) {
                    994:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    995:                     }
                    996:                 }
                    997:             }
                    998:         }
                    999:     } else {
                   1000:         my ($result,$perm_reqd) = 
1.707     albertel 1001: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1002:         if ($result eq 'ok') {
                   1003:             if (!($perm_reqd eq 'yes')) {
                   1004:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1005:             }
                   1006:         }
                   1007:     }
                   1008:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1009: }
                   1010: 
                   1011: sub retrievestudentphoto {
                   1012:     my ($udom,$unam,$ext,$type) = @_;
                   1013:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1014:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1015:     if ($ret eq 'ok') {
                   1016:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1017:         if ($type eq 'thumbnail') {
                   1018:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1019:         }
                   1020:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1021:         return $tokenurl;
                   1022:     } else {
                   1023:         if ($type eq 'thumbnail') {
                   1024:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1025:         } else { 
                   1026:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1027:         }
1.617     albertel 1028:     }
                   1029: }
                   1030: 
1.263     www      1031: # -------------------------------------------------------------------- New chat
                   1032: 
                   1033: sub chatsend {
1.724     raeburn  1034:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1035:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1036:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1037:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1038:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1039: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1040: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1041: }
                   1042: 
                   1043: # ------------------------------------------ Find current version of a resource
                   1044: 
                   1045: sub getversion {
                   1046:     my $fname=&clutter(shift);
                   1047:     unless ($fname=~/^\/res\//) { return -1; }
                   1048:     return &currentversion(&filelocation('',$fname));
                   1049: }
                   1050: 
                   1051: sub currentversion {
                   1052:     my $fname=shift;
1.599     albertel 1053:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1054:     if (defined($cached)) { return $result; }
1.292     www      1055:     my $author=$fname;
                   1056:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1057:     my ($udom,$uname)=split(/\//,$author);
                   1058:     my $home=homeserver($uname,$udom);
                   1059:     if ($home eq 'no_host') { 
                   1060:         return -1; 
                   1061:     }
                   1062:     my $answer=reply("currentversion:$fname",$home);
                   1063:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1064: 	return -1;
                   1065:     }
1.599     albertel 1066:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1067: }
                   1068: 
1.1       albertel 1069: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1070: 
1.1       albertel 1071: sub subscribe {
                   1072:     my $fname=shift;
1.312     www      1073:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1074:     $fname=~s/[\n\r]//g;
1.1       albertel 1075:     my $author=$fname;
                   1076:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1077:     my ($udom,$uname)=split(/\//,$author);
                   1078:     my $home=homeserver($uname,$udom);
1.335     albertel 1079:     if ($home eq 'no_host') {
                   1080:         return 'not_found';
1.1       albertel 1081:     }
                   1082:     my $answer=reply("sub:$fname",$home);
1.64      www      1083:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1084: 	$answer.=' by '.$home;
                   1085:     }
1.1       albertel 1086:     return $answer;
                   1087: }
                   1088:     
1.8       www      1089: # -------------------------------------------------------------- Replicate file
                   1090: 
                   1091: sub repcopy {
                   1092:     my $filename=shift;
1.23      www      1093:     $filename=~s/\/+/\//g;
1.607     raeburn  1094:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1095:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1096:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1097: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1098: 	return &repcopy_userfile($filename);
                   1099:     }
1.532     albertel 1100:     $filename=~s/[\n\r]//g;
1.8       www      1101:     my $transname="$filename.in.transfer";
1.607     raeburn  1102:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1103:     my $remoteurl=subscribe($filename);
1.64      www      1104:     if ($remoteurl =~ /^con_lost by/) {
                   1105: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1106:            return 'unavailable';
1.8       www      1107:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1108: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1109: 	   return 'not_found';
1.64      www      1110:     } elsif ($remoteurl =~ /^rejected by/) {
                   1111: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1112:            return 'forbidden';
1.20      www      1113:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1114:            return 'ok';
1.8       www      1115:     } else {
1.290     www      1116:         my $author=$filename;
                   1117:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1118:         my ($udom,$uname)=split(/\//,$author);
                   1119:         my $home=homeserver($uname,$udom);
                   1120:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1121:            my @parts=split(/\//,$filename);
                   1122:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1123:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1124:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1125: 	       return 'bad_request';
1.8       www      1126:            }
                   1127:            my $count;
                   1128:            for ($count=5;$count<$#parts;$count++) {
                   1129:                $path.="/$parts[$count]";
                   1130:                if ((-e $path)!=1) {
                   1131: 		   mkdir($path,0777);
                   1132:                }
                   1133:            }
                   1134:            my $ua=new LWP::UserAgent;
                   1135:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1136:            my $response=$ua->request($request,$transname);
                   1137:            if ($response->is_error()) {
                   1138: 	       unlink($transname);
                   1139:                my $message=$response->status_line;
1.672     albertel 1140:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1141:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1142:                return 'unavailable';
1.8       www      1143:            } else {
1.16      www      1144: 	       if ($remoteurl!~/\.meta$/) {
                   1145:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1146:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1147:                   if ($mresponse->is_error()) {
                   1148: 		      unlink($filename.'.meta');
                   1149:                       &logthis(
1.672     albertel 1150:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1151:                   }
                   1152: 	       }
1.8       www      1153:                rename($transname,$filename);
1.607     raeburn  1154:                return 'ok';
1.8       www      1155:            }
1.290     www      1156:        }
1.8       www      1157:     }
1.330     www      1158: }
                   1159: 
                   1160: # ------------------------------------------------ Get server side include body
                   1161: sub ssi_body {
1.381     albertel 1162:     my ($filelink,%form)=@_;
1.606     matthew  1163:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1164:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1165:     }
1.330     www      1166:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1167:                                      &ssi($filelink,%form));
1.565     albertel 1168:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1169:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1170:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1171:     return $output;
1.8       www      1172: }
                   1173: 
1.15      www      1174: # --------------------------------------------------------- Server Side Include
                   1175: 
                   1176: sub ssi {
                   1177: 
1.23      www      1178:     my ($fn,%form)=@_;
1.15      www      1179: 
                   1180:     my $ua=new LWP::UserAgent;
1.23      www      1181:     
                   1182:     my $request;
1.711     albertel 1183: 
                   1184:     $form{'no_update_last_known'}=1;
                   1185: 
1.23      www      1186:     if (%form) {
                   1187:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1188:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1189:     } else {
                   1190:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1191:     }
                   1192: 
1.15      www      1193:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1194:     my $response=$ua->request($request);
                   1195: 
1.324     www      1196:     return $response->content;
                   1197: }
                   1198: 
                   1199: sub externalssi {
                   1200:     my ($url)=@_;
                   1201:     my $ua=new LWP::UserAgent;
                   1202:     my $request=new HTTP::Request('GET',$url);
                   1203:     my $response=$ua->request($request);
1.15      www      1204:     return $response->content;
                   1205: }
1.254     www      1206: 
1.492     albertel 1207: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1208: 
                   1209: sub allowuploaded {
                   1210:     my ($srcurl,$url)=@_;
                   1211:     $url=&clutter(&declutter($url));
                   1212:     my $dir=$url;
                   1213:     $dir=~s/\/[^\/]+$//;
                   1214:     my %httpref=();
                   1215:     my $httpurl=&hreflocation('',$url);
                   1216:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1217:     &Apache::lonnet::appenv(%httpref);
1.254     www      1218: }
1.477     raeburn  1219: 
1.478     albertel 1220: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1221: # input: action, courseID, current domain, intended
1.637     raeburn  1222: #        path to file, source of file, instruction to parse file for objects,
                   1223: #        ref to hash for embedded objects,
                   1224: #        ref to hash for codebase of java objects.
                   1225: #
1.485     raeburn  1226: # output: url to file (if action was uploaddoc), 
                   1227: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1228: #
1.478     albertel 1229: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1230: # course.
1.477     raeburn  1231: #
1.478     albertel 1232: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1233: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1234: #          course's home server.
1.477     raeburn  1235: #
1.478     albertel 1236: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1237: #          be copied from $source (current location) to 
                   1238: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1239: #         and will then be copied to
                   1240: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1241: #         course's home server.
1.485     raeburn  1242: #
1.481     raeburn  1243: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1244: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1245: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1246: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1247: #         in course's home server.
1.637     raeburn  1248: #
1.477     raeburn  1249: 
                   1250: sub process_coursefile {
1.638     albertel 1251:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1252:     my $fetchresult;
1.638     albertel 1253:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1254:     if ($action eq 'propagate') {
1.638     albertel 1255:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1256: 			     $home);
1.481     raeburn  1257:     } else {
1.477     raeburn  1258:         my $fpath = '';
                   1259:         my $fname = $file;
1.478     albertel 1260:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1261:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1262:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1263:         if ($action eq 'copy') {
                   1264:             if ($source eq '') {
                   1265:                 $fetchresult = 'no source file';
                   1266:                 return $fetchresult;
                   1267:             } else {
                   1268:                 my $destination = $filepath.'/'.$fname;
                   1269:                 rename($source,$destination);
                   1270:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1271:                                  $home);
1.481     raeburn  1272:             }
                   1273:         } elsif ($action eq 'uploaddoc') {
                   1274:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1275:             print $fh $env{'form.'.$source};
1.481     raeburn  1276:             close($fh);
1.637     raeburn  1277:             if ($parser eq 'parse') {
                   1278:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1279:                 unless ($parse_result eq 'ok') {
                   1280:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1281:                 }
                   1282:             }
1.477     raeburn  1283:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1284:                                  $home);
1.481     raeburn  1285:             if ($fetchresult eq 'ok') {
                   1286:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1287:             } else {
                   1288:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1289:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1290:                 return '/adm/notfound.html';
                   1291:             }
1.477     raeburn  1292:         }
                   1293:     }
1.485     raeburn  1294:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1295:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1296:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1297:     }
                   1298:     return $fetchresult;
                   1299: }
                   1300: 
1.637     raeburn  1301: sub build_filepath {
                   1302:     my ($fpath) = @_;
                   1303:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1304:     unless ($fpath eq '') {
                   1305:         my @parts=split('/',$fpath);
                   1306:         foreach my $part (@parts) {
                   1307:             $filepath.= '/'.$part;
                   1308:             if ((-e $filepath)!=1) {
                   1309:                 mkdir($filepath,0777);
                   1310:             }
                   1311:         }
                   1312:     }
                   1313:     return $filepath;
                   1314: }
                   1315: 
                   1316: sub store_edited_file {
1.638     albertel 1317:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1318:     my $file = $primary_url;
                   1319:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1320:     my $fpath = '';
                   1321:     my $fname = $file;
                   1322:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1323:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1324:     my $filepath = &build_filepath($fpath);
                   1325:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1326:     print $fh $content;
                   1327:     close($fh);
1.638     albertel 1328:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1329:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1330: 			  $home);
1.637     raeburn  1331:     if ($$fetchresult eq 'ok') {
                   1332:         return '/uploaded/'.$fpath.'/'.$fname;
                   1333:     } else {
1.638     albertel 1334:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1335: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1336:         return '/adm/notfound.html';
                   1337:     }
                   1338: }
                   1339: 
1.531     albertel 1340: sub clean_filename {
                   1341:     my ($fname)=@_;
1.315     www      1342: # Replace Windows backslashes by forward slashes
1.257     www      1343:     $fname=~s/\\/\//g;
1.315     www      1344: # Get rid of everything but the actual filename
1.257     www      1345:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1346: # Replace spaces by underscores
                   1347:     $fname=~s/\s+/\_/g;
                   1348: # Replace all other weird characters by nothing
1.317     www      1349:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1350: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1351: # numbers
                   1352:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1353:     return $fname;
                   1354: }
                   1355: 
1.608     albertel 1356: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1357: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1358: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1359: #        $coursedoc - if true up to the current course
                   1360: #                     if false
                   1361: #        $subdir - directory in userfile to store the file into
                   1362: #        $parser, $allfiles, $codebase - unknown
                   1363: #
                   1364: # output: url of file in userspace, or error: <message> 
                   1365: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1366: 
                   1367: 
1.531     albertel 1368: sub userfileupload {
1.719     banghart 1369:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1370:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1371:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1372:     $fname=&clean_filename($fname);
1.315     www      1373: # See if there is anything left
1.257     www      1374:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1375:     chop($env{'form.'.$formname});
1.523     raeburn  1376:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1377:         my $now = time;
                   1378:         my $filepath = 'tmp/helprequests/'.$now;
                   1379:         my @parts=split(/\//,$filepath);
                   1380:         my $fullpath = $perlvar{'lonDaemons'};
                   1381:         for (my $i=0;$i<@parts;$i++) {
                   1382:             $fullpath .= '/'.$parts[$i];
                   1383:             if ((-e $fullpath)!=1) {
                   1384:                 mkdir($fullpath,0777);
                   1385:             }
                   1386:         }
                   1387:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1388:         print $fh $env{'form.'.$formname};
1.523     raeburn  1389:         close($fh);
                   1390:         return $fullpath.'/'.$fname; 
                   1391:     }
1.719     banghart 1392:     
1.258     www      1393: # Create the directory if not present
1.493     albertel 1394:     $fname="$subdir/$fname";
1.259     www      1395:     if ($coursedoc) {
1.638     albertel 1396: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1397: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1398:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1399:             return &finishuserfileupload($docuname,$docudom,
                   1400: 					 $formname,$fname,$parser,$allfiles,
                   1401: 					 $codebase);
1.481     raeburn  1402:         } else {
1.620     albertel 1403:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1404:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1405: 				       $fname,$formname,$parser,
                   1406: 				       $allfiles,$codebase);
1.481     raeburn  1407:         }
1.719     banghart 1408:     } elsif (defined($destuname)) {
                   1409:         my $docuname=$destuname;
                   1410:         my $docudom=$destudom;
                   1411: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1412: 				     $fname,$parser,$allfiles,$codebase);
                   1413:         
1.259     www      1414:     } else {
1.638     albertel 1415:         my $docuname=$env{'user.name'};
                   1416:         my $docudom=$env{'user.domain'};
1.714     raeburn  1417:         if (exists($env{'form.group'})) {
                   1418:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1419:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1420:         }
1.638     albertel 1421: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1422: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1423:     }
1.271     www      1424: }
                   1425: 
                   1426: sub finishuserfileupload {
1.638     albertel 1427:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1428:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1429:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1430:     my ($fnamepath,$file);
                   1431:     $file=$fname;
                   1432:     if ($fname=~m|/|) {
                   1433:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1434: 	$path.=$fnamepath.'/';
                   1435:     }
1.259     www      1436:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1437:     my $count;
                   1438:     for ($count=4;$count<=$#parts;$count++) {
                   1439:         $filepath.="/$parts[$count]";
                   1440:         if ((-e $filepath)!=1) {
                   1441: 	    mkdir($filepath,0777);
                   1442:         }
                   1443:     }
                   1444: # Save the file
                   1445:     {
1.701     albertel 1446: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1447: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1448: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1449: 	    return '/adm/notfound.html';
                   1450: 	}
                   1451: 	if (!print FH ($env{'form.'.$formname})) {
                   1452: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1453: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1454: 	    return '/adm/notfound.html';
                   1455: 	}
1.570     albertel 1456: 	close(FH);
1.258     www      1457:     }
1.637     raeburn  1458:     if ($parser eq 'parse') {
1.638     albertel 1459:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1460: 						   $codebase);
1.637     raeburn  1461:         unless ($parse_result eq 'ok') {
1.638     albertel 1462:             &logthis('Failed to parse '.$filepath.$file.
                   1463: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1464:         }
                   1465:     }
1.259     www      1466: # Notify homeserver to grep it
                   1467: #
1.638     albertel 1468:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1469:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1470:     if ($fetchresult eq 'ok') {
1.259     www      1471: #
1.258     www      1472: # Return the URL to it
1.494     albertel 1473:         return '/uploaded/'.$path.$file;
1.263     www      1474:     } else {
1.494     albertel 1475:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1476: 		 ': '.$fetchresult);
1.263     www      1477:         return '/adm/notfound.html';
                   1478:     }    
1.493     albertel 1479: }
                   1480: 
1.637     raeburn  1481: sub extract_embedded_items {
1.648     raeburn  1482:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1483:     my @state = ();
                   1484:     my %javafiles = (
                   1485:                       codebase => '',
                   1486:                       code => '',
                   1487:                       archive => ''
                   1488:                     );
                   1489:     my %mediafiles = (
                   1490:                       src => '',
                   1491:                       movie => '',
                   1492:                      );
1.648     raeburn  1493:     my $p;
                   1494:     if ($content) {
                   1495:         $p = HTML::LCParser->new($content);
                   1496:     } else {
                   1497:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1498:     }
1.641     albertel 1499:     while (my $t=$p->get_token()) {
1.640     albertel 1500: 	if ($t->[0] eq 'S') {
                   1501: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1502: 	    push (@state, $tagname);
1.648     raeburn  1503:             if (lc($tagname) eq 'allow') {
                   1504:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1505:             }
1.640     albertel 1506: 	    if (lc($tagname) eq 'img') {
                   1507: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1508: 	    }
1.645     raeburn  1509:             if (lc($tagname) eq 'script') {
                   1510:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1511:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1512:                 } else {
                   1513:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1514:                 }
                   1515:             }
                   1516:             if (lc($tagname) eq 'link') {
                   1517:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1518:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1519:                 }
                   1520:             }
1.640     albertel 1521: 	    if (lc($tagname) eq 'object' ||
                   1522: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1523: 		foreach my $item (keys(%javafiles)) {
                   1524: 		    $javafiles{$item} = '';
                   1525: 		}
                   1526: 	    }
                   1527: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1528: 		my $name = lc($attr->{'name'});
                   1529: 		foreach my $item (keys(%javafiles)) {
                   1530: 		    if ($name eq $item) {
                   1531: 			$javafiles{$item} = $attr->{'value'};
                   1532: 			last;
                   1533: 		    }
                   1534: 		}
                   1535: 		foreach my $item (keys(%mediafiles)) {
                   1536: 		    if ($name eq $item) {
                   1537: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1538: 			last;
                   1539: 		    }
                   1540: 		}
                   1541: 	    }
                   1542: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1543: 		foreach my $item (keys(%javafiles)) {
                   1544: 		    if ($attr->{$item}) {
                   1545: 			$javafiles{$item} = $attr->{$item};
                   1546: 			last;
                   1547: 		    }
                   1548: 		}
                   1549: 		foreach my $item (keys(%mediafiles)) {
                   1550: 		    if ($attr->{$item}) {
                   1551: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1552: 			last;
                   1553: 		    }
                   1554: 		}
                   1555: 	    }
                   1556: 	} elsif ($t->[0] eq 'E') {
                   1557: 	    my ($tagname) = ($t->[1]);
                   1558: 	    if ($javafiles{'codebase'} ne '') {
                   1559: 		$javafiles{'codebase'} .= '/';
                   1560: 	    }  
                   1561: 	    if (lc($tagname) eq 'applet' ||
                   1562: 		lc($tagname) eq 'object' ||
                   1563: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1564: 		) {
                   1565: 		foreach my $item (keys(%javafiles)) {
                   1566: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1567: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1568: 			&add_filetype($allfiles,$file,$item);
                   1569: 		    }
                   1570: 		}
                   1571: 	    } 
                   1572: 	    pop @state;
                   1573: 	}
                   1574:     }
1.637     raeburn  1575:     return 'ok';
                   1576: }
                   1577: 
1.639     albertel 1578: sub add_filetype {
                   1579:     my ($allfiles,$file,$type)=@_;
                   1580:     if (exists($allfiles->{$file})) {
                   1581: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1582: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1583: 	}
                   1584:     } else {
                   1585: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1586:     }
                   1587: }
                   1588: 
1.493     albertel 1589: sub removeuploadedurl {
                   1590:     my ($url)=@_;
                   1591:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1592:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1593: }
                   1594: 
                   1595: sub removeuserfile {
                   1596:     my ($docuname,$docudom,$fname)=@_;
                   1597:     my $home=&homeserver($docuname,$docudom);
                   1598:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1599: }
1.15      www      1600: 
1.530     albertel 1601: sub mkdiruserfile {
                   1602:     my ($docuname,$docudom,$dir)=@_;
                   1603:     my $home=&homeserver($docuname,$docudom);
                   1604:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1605: }
                   1606: 
1.531     albertel 1607: sub renameuserfile {
                   1608:     my ($docuname,$docudom,$old,$new)=@_;
                   1609:     my $home=&homeserver($docuname,$docudom);
                   1610:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1611: 		  &escape("$new"),$home);
                   1612: }
                   1613: 
1.14      www      1614: # ------------------------------------------------------------------------- Log
                   1615: 
                   1616: sub log {
                   1617:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1618:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1619: }
                   1620: 
                   1621: # ------------------------------------------------------------------ Course Log
1.352     www      1622: #
                   1623: # This routine flushes several buffers of non-mission-critical nature
                   1624: #
1.157     www      1625: 
                   1626: sub flushcourselogs {
1.352     www      1627:     &logthis('Flushing log buffers');
                   1628: #
                   1629: # course logs
                   1630: # This is a log of all transactions in a course, which can be used
                   1631: # for data mining purposes
                   1632: #
                   1633: # It also collects the courseid database, which lists last transaction
                   1634: # times and course titles for all courseids
                   1635: #
                   1636:     my %courseidbuffer=();
1.191     harris41 1637:     foreach (keys %courselogs) {
1.157     www      1638:         my $crsid=$_;
1.352     www      1639:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1640: 		          &escape($courselogs{$crsid}),
                   1641: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1642: 	    delete $courselogs{$crsid};
                   1643:         } else {
                   1644:             &logthis('Failed to flush log buffer for '.$crsid);
                   1645:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1646:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1647:                         " exceeded maximum size, deleting.</font>");
                   1648:                delete $courselogs{$crsid};
                   1649:             }
1.352     www      1650:         }
                   1651:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1652:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1653: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1654:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352     www      1655:         } else {
                   1656:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1657: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1658:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
                   1659:         }
1.191     harris41 1660:     }
1.352     www      1661: #
                   1662: # Write course id database (reverse lookup) to homeserver of courses 
                   1663: # Is used in pickcourse
                   1664: #
                   1665:     foreach (keys %courseidbuffer) {
1.353     www      1666:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1667:     }
                   1668: #
                   1669: # File accesses
                   1670: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1671: #
1.449     matthew  1672:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1673:         if ($entry =~ /___count$/) {
                   1674:             my ($dom,$name);
                   1675:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1676:             if (! defined($dom) || $dom eq '' || 
                   1677:                 ! defined($name) || $name eq '') {
1.620     albertel 1678:                 my $cid = $env{'request.course.id'};
                   1679:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1680:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1681:             }
1.450     matthew  1682:             my $value = $accesshash{$entry};
                   1683:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1684:             my %temphash=($url => $value);
1.449     matthew  1685:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1686:             if ($result eq 'ok') {
                   1687:                 delete $accesshash{$entry};
                   1688:             } elsif ($result eq 'unknown_cmd') {
                   1689:                 # Target server has old code running on it.
1.450     matthew  1690:                 my %temphash=($entry => $value);
1.449     matthew  1691:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1692:                     delete $accesshash{$entry};
                   1693:                 }
                   1694:             }
                   1695:         } else {
1.458     matthew  1696:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1697:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1698:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1699:                 delete $accesshash{$entry};
                   1700:             }
1.185     www      1701:         }
1.191     harris41 1702:     }
1.352     www      1703: #
                   1704: # Roles
                   1705: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1706: #
1.349     www      1707:     foreach (keys %userrolehash) {
                   1708:         my $entry=$_;
1.351     www      1709:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1710: 	    split(/\:/,$entry);
                   1711:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1712:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1713:                 $rudom,$runame) eq 'ok') {
                   1714: 	    delete $userrolehash{$entry};
                   1715:         }
                   1716:     }
1.662     raeburn  1717: #
                   1718: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1719: #
                   1720:     my %domrolebuffer = ();
                   1721:     foreach my $entry (keys %domainrolehash) {
                   1722:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1723:         if ($domrolebuffer{$rudom}) {
                   1724:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1725:                       '='.&escape($domainrolehash{$entry});
                   1726:         } else {
                   1727:             $domrolebuffer{$rudom}.=&escape($entry).
                   1728:                       '='.&escape($domainrolehash{$entry});
                   1729:         }
                   1730:         delete $domainrolehash{$entry};
                   1731:     }
                   1732:     foreach my $dom (keys(%domrolebuffer)) {
                   1733:         foreach my $tryserver (keys %libserv) {
                   1734:             if ($hostdom{$tryserver} eq $dom) {
                   1735:                 unless (&reply('domroleput:'.$dom.':'.
                   1736:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1737:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1738:                 }
                   1739:             }
                   1740:         }
                   1741:     }
1.186     www      1742:     $dumpcount++;
1.157     www      1743: }
                   1744: 
                   1745: sub courselog {
                   1746:     my $what=shift;
1.158     www      1747:     $what=time.':'.$what;
1.620     albertel 1748:     unless ($env{'request.course.id'}) { return ''; }
                   1749:     $coursedombuf{$env{'request.course.id'}}=
                   1750:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1751:     $coursenumbuf{$env{'request.course.id'}}=
                   1752:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1753:     $coursehombuf{$env{'request.course.id'}}=
                   1754:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1755:     $coursedescrbuf{$env{'request.course.id'}}=
                   1756:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1757:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1758:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1759:     $courseownerbuf{$env{'request.course.id'}}=
                   1760:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   1761:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1762: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1763:     } else {
1.620     albertel 1764: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1765:     }
1.620     albertel 1766:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1767: 	&flushcourselogs();
                   1768:     }
1.158     www      1769: }
                   1770: 
                   1771: sub courseacclog {
                   1772:     my $fnsymb=shift;
1.620     albertel 1773:     unless ($env{'request.course.id'}) { return ''; }
                   1774:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1775:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1776:         $what.=':POST';
1.583     matthew  1777:         # FIXME: Probably ought to escape things....
1.620     albertel 1778: 	foreach (keys %env) {
1.158     www      1779:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1780: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1781:             }
1.191     harris41 1782:         }
1.583     matthew  1783:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1784:         # FIXME: We should not be depending on a form parameter that someone
                   1785:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1786:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1787:             $what.= ':POST';
                   1788:             # FIXME: Probably ought to escape things....
                   1789:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1790:                                  'crsdiscuss') {
1.620     albertel 1791:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1792:             }
                   1793:         }
1.158     www      1794:     }
                   1795:     &courselog($what);
1.149     www      1796: }
                   1797: 
1.185     www      1798: sub countacc {
                   1799:     my $url=&declutter(shift);
1.458     matthew  1800:     return if (! defined($url) || $url eq '');
1.620     albertel 1801:     unless ($env{'request.course.id'}) { return ''; }
                   1802:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1803:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1804:     $accesshash{$key}++;
1.185     www      1805: }
1.349     www      1806: 
1.361     www      1807: sub linklog {
                   1808:     my ($from,$to)=@_;
                   1809:     $from=&declutter($from);
                   1810:     $to=&declutter($to);
                   1811:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1812:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1813: }
                   1814:   
1.349     www      1815: sub userrolelog {
                   1816:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1817:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1818:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1819:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1820:         ($trole=~/^ta/)) {
1.350     www      1821:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1822:        $userrolehash
                   1823:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1824:                     =$tend.':'.$tstart;
1.662     raeburn  1825:     }
                   1826:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1827:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1828:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1829:         ($trole=~/^sc/)) {
                   1830:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1831:        $domainrolehash
                   1832:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1833:                     = $tend.':'.$tstart;
                   1834:     }
1.351     www      1835: }
                   1836: 
                   1837: sub get_course_adv_roles {
                   1838:     my $cid=shift;
1.620     albertel 1839:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1840:     my %coursehash=&coursedescription($cid);
1.470     www      1841:     my %nothide=();
                   1842:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1843: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1844:     }
1.351     www      1845:     my %returnhash=();
                   1846:     my %dumphash=
                   1847:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1848:     my $now=time;
                   1849:     foreach (keys %dumphash) {
                   1850: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1851:         if (($tstart) && ($tstart<0)) { next; }
                   1852:         if (($tend) && ($tend<$now)) { next; }
                   1853:         if (($tstart) && ($now<$tstart)) { next; }
                   1854:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1855: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1856: 	if ((&privileged($username,$domain)) && 
                   1857: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1858: 	if ($role eq 'cr') { next; }
1.351     www      1859:         my $key=&plaintext($role);
1.656     albertel 1860: 	if ($role =~ /^cr/) {
                   1861: 	    $key=(split('/',$role))[3];
                   1862: 	}
1.351     www      1863:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1864:         if ($returnhash{$key}) {
                   1865: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1866:         } else {
                   1867:             $returnhash{$key}=$username.':'.$domain;
                   1868:         }
1.400     www      1869:      }
                   1870:     return %returnhash;
                   1871: }
                   1872: 
                   1873: sub get_my_roles {
                   1874:     my ($uname,$udom)=@_;
1.620     albertel 1875:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1876:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1877:     my %dumphash=
                   1878:             &dump('nohist_userroles',$udom,$uname);
                   1879:     my %returnhash=();
                   1880:     my $now=time;
                   1881:     foreach (keys %dumphash) {
                   1882: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1883:         if (($tstart) && ($tstart<0)) { next; }
                   1884:         if (($tend) && ($tend<$now)) { next; }
                   1885:         if (($tstart) && ($now<$tstart)) { next; }
                   1886:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1887: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1888:      }
                   1889:     return %returnhash;
1.399     www      1890: }
                   1891: 
                   1892: # ----------------------------------------------------- Frontpage Announcements
                   1893: #
                   1894: #
                   1895: 
                   1896: sub postannounce {
                   1897:     my ($server,$text)=@_;
                   1898:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1899:     unless ($text=~/\w/) { $text=''; }
                   1900:     return &reply('setannounce:'.&escape($text),$server);
                   1901: }
                   1902: 
                   1903: sub getannounce {
1.448     albertel 1904: 
                   1905:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1906: 	my $announcement='';
                   1907: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1908: 	close($fh);
1.399     www      1909: 	if ($announcement=~/\w/) { 
                   1910: 	    return 
                   1911:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1912:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1913: 	} else {
                   1914: 	    return '';
                   1915: 	}
                   1916:     } else {
                   1917: 	return '';
                   1918:     }
1.351     www      1919: }
1.353     www      1920: 
                   1921: # ---------------------------------------------------------- Course ID routines
                   1922: # Deal with domain's nohist_courseid.db files
                   1923: #
                   1924: 
                   1925: sub courseidput {
                   1926:     my ($domain,$what,$coursehome)=@_;
                   1927:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1928: }
                   1929: 
                   1930: sub courseiddump {
1.622     raeburn  1931:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353     www      1932:     my %returnhash=();
1.355     www      1933:     unless ($domfilter) { $domfilter=''; }
1.353     www      1934:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1935:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1936: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1937: 	        foreach (
                   1938:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1939: 			       $sincefilter.':'.&escape($descfilter).':'.
1.622     raeburn  1940:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354     www      1941:                                $tryserver))) {
1.506     raeburn  1942: 		    my ($key,$value)=split(/\=/,$_);
                   1943:                     if (($key) && ($value)) {
1.516     raeburn  1944: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1945:                     }
1.353     www      1946:                 }
                   1947:             }
                   1948:         }
                   1949:     }
                   1950:     return %returnhash;
                   1951: }
                   1952: 
1.658     raeburn  1953: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1954: 
                   1955: sub dcmailput {
1.685     raeburn  1956:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1957:     my $status = &Apache::lonnet::critical(
1.740   ! www      1958:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
        !          1959:        &escape($message),$server);
1.662     raeburn  1960:     return $status;
                   1961: }
                   1962: 
1.658     raeburn  1963: sub dcmaildump {
                   1964:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1965:     my %returnhash=();
                   1966:     if (exists($domain_primary{$dom})) {
                   1967:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1968:                                                          &escape($enddate).':';
                   1969: 	my @esc_senders=map { &escape($_)} @$senders;
                   1970: 	$cmd.=&escape(join('&',@esc_senders));
                   1971: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1972:             my ($key,$value) = split(/\=/,$_);
                   1973:             if (($key) && ($value)) {
                   1974:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  1975:             }
                   1976:         }
                   1977:     }
                   1978:     return %returnhash;
                   1979: }
1.662     raeburn  1980: # ---------------------------------------------------------- Domain roles
                   1981: 
                   1982: sub get_domain_roles {
                   1983:     my ($dom,$roles,$startdate,$enddate)=@_;
                   1984:     if (undef($startdate) || $startdate eq '') {
                   1985:         $startdate = '.';
                   1986:     }
                   1987:     if (undef($enddate) || $enddate eq '') {
                   1988:         $enddate = '.';
                   1989:     }
                   1990:     my $rolelist = join(':',@{$roles});
                   1991:     my %personnel = ();
                   1992:     foreach my $tryserver (keys(%libserv)) {
                   1993:         if ($hostdom{$tryserver} eq $dom) {
                   1994:             %{$personnel{$tryserver}}=();
                   1995:             foreach (
                   1996:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   1997:                    &escape($startdate).':'.&escape($enddate).':'.
                   1998:                    &escape($rolelist), $tryserver))) {
                   1999:                 my($key,$value) = split(/\=/,$_);
                   2000:                 if (($key) && ($value)) {
                   2001:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2002:                 }
                   2003:             }
                   2004:         }
                   2005:     }
                   2006:     return %personnel;
                   2007: }
1.658     raeburn  2008: 
1.149     www      2009: # ----------------------------------------------------------- Check out an item
                   2010: 
1.504     albertel 2011: sub get_first_access {
                   2012:     my ($type,$argsymb)=@_;
                   2013:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2014:     if ($argsymb) { $symb=$argsymb; }
                   2015:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2016:     if ($type eq 'map') {
                   2017: 	$res=&symbread($map);
                   2018:     } else {
                   2019: 	$res=$symb;
                   2020:     }
                   2021:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2022:     return $times{"$courseid\0$res"};
1.504     albertel 2023: }
                   2024: 
                   2025: sub set_first_access {
                   2026:     my ($type)=@_;
                   2027:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2028:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2029:     if ($type eq 'map') {
                   2030: 	$res=&symbread($map);
                   2031:     } else {
                   2032: 	$res=$symb;
                   2033:     }
                   2034:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2035:     if (!$firstaccess) {
1.588     albertel 2036: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2037:     }
                   2038:     return 'already_set';
1.504     albertel 2039: }
                   2040: 
1.149     www      2041: sub checkout {
                   2042:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2043:     my $now=time;
                   2044:     my $lonhost=$perlvar{'lonHostID'};
                   2045:     my $infostr=&escape(
1.234     www      2046:                  'CHECKOUTTOKEN&'.
1.149     www      2047:                  $tuname.'&'.
                   2048:                  $tudom.'&'.
                   2049:                  $tcrsid.'&'.
                   2050:                  $symb.'&'.
                   2051: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2052:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2053:     if ($token=~/^error\:/) { 
1.672     albertel 2054:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2055:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2056:                  "</font>");
                   2057:         return ''; 
                   2058:     }
                   2059: 
1.149     www      2060:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2061:     $token=~tr/a-z/A-Z/;
                   2062: 
1.153     www      2063:     my %infohash=('resource.0.outtoken' => $token,
                   2064:                   'resource.0.checkouttime' => $now,
                   2065:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2066: 
                   2067:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2068:        return '';
1.151     www      2069:     } else {
1.672     albertel 2070:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2071:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2072:                  "</font>");
1.149     www      2073:     }    
                   2074: 
                   2075:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2076:                          &escape('Checkout '.$infostr.' - '.
                   2077:                                                  $token)) ne 'ok') {
                   2078: 	return '';
1.151     www      2079:     } else {
1.672     albertel 2080:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2081:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2082:                  "</font>");
1.149     www      2083:     }
1.151     www      2084:     return $token;
1.149     www      2085: }
                   2086: 
                   2087: # ------------------------------------------------------------ Check in an item
                   2088: 
                   2089: sub checkin {
                   2090:     my $token=shift;
1.150     www      2091:     my $now=time;
                   2092:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2093:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2094:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2095:     $dtoken=~s/\W/\_/g;
1.234     www      2096:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2097:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2098: 
1.154     www      2099:     unless (($tuname) && ($tudom)) {
                   2100:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2101:         return '';
                   2102:     }
                   2103:     
                   2104:     unless (&allowed('mgr',$tcrsid)) {
                   2105:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2106:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2107:         return '';
                   2108:     }
                   2109: 
1.153     www      2110:     my %infohash=('resource.0.intoken' => $token,
                   2111:                   'resource.0.checkintime' => $now,
                   2112:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2113: 
                   2114:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2115:        return '';
                   2116:     }    
                   2117: 
                   2118:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2119:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2120: 	return '';
                   2121:     }
                   2122: 
                   2123:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2124: }
                   2125: 
                   2126: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2127: 
                   2128: sub expirespread {
                   2129:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2130:     my $cid=$env{'request.course.id'}; 
1.110     www      2131:     if ($cid) {
                   2132:        my $now=time;
                   2133:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2134:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2135:                             $env{'course.'.$cid.'.num'}.
1.110     www      2136: 	        	    ':nohist_expirationdates:'.
                   2137:                             &escape($key).'='.$now,
1.620     albertel 2138:                             $env{'course.'.$cid.'.home'})
1.110     www      2139:     }
                   2140:     return 'ok';
1.14      www      2141: }
                   2142: 
1.109     www      2143: # ----------------------------------------------------- Devalidate Spreadsheets
                   2144: 
                   2145: sub devalidate {
1.325     www      2146:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2147:     my $cid=$env{'request.course.id'}; 
1.109     www      2148:     if ($cid) {
1.391     matthew  2149:         # delete the stored spreadsheets for
                   2150:         # - the student level sheet of this user in course's homespace
                   2151:         # - the assessment level sheet for this resource 
                   2152:         #   for this user in user's homespace
1.553     albertel 2153: 	# - current conditional state info
1.325     www      2154: 	my $key=$uname.':'.$udom.':';
1.109     www      2155:         my $status=
1.299     matthew  2156: 	    &del('nohist_calculatedsheets',
1.391     matthew  2157: 		 [$key.'studentcalc:'],
1.620     albertel 2158: 		 $env{'course.'.$cid.'.domain'},
                   2159: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2160: 		.' '.
                   2161: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2162: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2163:         unless ($status eq 'ok ok') {
                   2164:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2165:                     $uname.' at '.$udom.' for '.
1.109     www      2166: 		    $symb.': '.$status);
1.133     albertel 2167:         }
1.553     albertel 2168: 	&delenv('user.state.'.$cid);
1.109     www      2169:     }
                   2170: }
                   2171: 
1.265     albertel 2172: sub get_scalar {
                   2173:     my ($string,$end) = @_;
                   2174:     my $value;
                   2175:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2176: 	$value = $1;
                   2177:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2178: 	$value = $1;
                   2179:     }
                   2180:     return &unescape($value);
                   2181: }
                   2182: 
                   2183: sub array2str {
                   2184:   my (@array) = @_;
                   2185:   my $result=&arrayref2str(\@array);
                   2186:   $result=~s/^__ARRAY_REF__//;
                   2187:   $result=~s/__END_ARRAY_REF__$//;
                   2188:   return $result;
                   2189: }
                   2190: 
1.204     albertel 2191: sub arrayref2str {
                   2192:   my ($arrayref) = @_;
1.265     albertel 2193:   my $result='__ARRAY_REF__';
1.204     albertel 2194:   foreach my $elem (@$arrayref) {
1.265     albertel 2195:     if(ref($elem) eq 'ARRAY') {
                   2196:       $result.=&arrayref2str($elem).'&';
                   2197:     } elsif(ref($elem) eq 'HASH') {
                   2198:       $result.=&hashref2str($elem).'&';
                   2199:     } elsif(ref($elem)) {
                   2200:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2201:     } else {
                   2202:       $result.=&escape($elem).'&';
                   2203:     }
                   2204:   }
                   2205:   $result=~s/\&$//;
1.265     albertel 2206:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2207:   return $result;
                   2208: }
                   2209: 
1.168     albertel 2210: sub hash2str {
1.204     albertel 2211:   my (%hash) = @_;
                   2212:   my $result=&hashref2str(\%hash);
1.265     albertel 2213:   $result=~s/^__HASH_REF__//;
                   2214:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2215:   return $result;
                   2216: }
                   2217: 
                   2218: sub hashref2str {
                   2219:   my ($hashref)=@_;
1.265     albertel 2220:   my $result='__HASH_REF__';
1.495     albertel 2221:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2222:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2223:       $result.=&arrayref2str($_).'=';
1.204     albertel 2224:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2225:       $result.=&hashref2str($_).'=';
1.204     albertel 2226:     } elsif (ref($_)) {
1.265     albertel 2227:       $result.='=';
                   2228:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2229:     } else {
1.265     albertel 2230: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2231:     }
                   2232: 
1.265     albertel 2233:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2234:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2235:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2236:       $result.=&hashref2str($hashref->{$_}).'&';
                   2237:     } elsif(ref($hashref->{$_})) {
                   2238:        $result.='&';
                   2239:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2240:     } else {
1.265     albertel 2241:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2242:     }
                   2243:   }
1.168     albertel 2244:   $result=~s/\&$//;
1.265     albertel 2245:   $result .= '__END_HASH_REF__';
1.168     albertel 2246:   return $result;
                   2247: }
                   2248: 
                   2249: sub str2hash {
1.265     albertel 2250:     my ($string)=@_;
                   2251:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2252:     return %$hash;
                   2253: }
                   2254: 
                   2255: sub str2hashref {
1.168     albertel 2256:   my ($string) = @_;
1.265     albertel 2257: 
                   2258:   my %hash;
                   2259: 
                   2260:   if($string !~ /^__HASH_REF__/) {
                   2261:       if (! ($string eq '' || !defined($string))) {
                   2262: 	  $hash{'error'}='Not hash reference';
                   2263:       }
                   2264:       return (\%hash, $string);
                   2265:   }
                   2266: 
                   2267:   $string =~ s/^__HASH_REF__//;
                   2268: 
                   2269:   while($string !~ /^__END_HASH_REF__/) {
                   2270:       #key
                   2271:       my $key='';
                   2272:       if($string =~ /^__HASH_REF__/) {
                   2273:           ($key, $string)=&str2hashref($string);
                   2274:           if(defined($key->{'error'})) {
                   2275:               $hash{'error'}='Bad data';
                   2276:               return (\%hash, $string);
                   2277:           }
                   2278:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2279:           ($key, $string)=&str2arrayref($string);
                   2280:           if($key->[0] eq 'Array reference error') {
                   2281:               $hash{'error'}='Bad data';
                   2282:               return (\%hash, $string);
                   2283:           }
                   2284:       } else {
                   2285:           $string =~ s/^(.*?)=//;
1.267     albertel 2286: 	  $key=&unescape($1);
1.265     albertel 2287:       }
                   2288:       $string =~ s/^=//;
                   2289: 
                   2290:       #value
                   2291:       my $value='';
                   2292:       if($string =~ /^__HASH_REF__/) {
                   2293:           ($value, $string)=&str2hashref($string);
                   2294:           if(defined($value->{'error'})) {
                   2295:               $hash{'error'}='Bad data';
                   2296:               return (\%hash, $string);
                   2297:           }
                   2298:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2299:           ($value, $string)=&str2arrayref($string);
                   2300:           if($value->[0] eq 'Array reference error') {
                   2301:               $hash{'error'}='Bad data';
                   2302:               return (\%hash, $string);
                   2303:           }
                   2304:       } else {
                   2305: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2306:       }
                   2307:       $string =~ s/^&//;
                   2308: 
                   2309:       $hash{$key}=$value;
1.204     albertel 2310:   }
1.265     albertel 2311: 
                   2312:   $string =~ s/^__END_HASH_REF__//;
                   2313: 
                   2314:   return (\%hash, $string);
1.204     albertel 2315: }
                   2316: 
                   2317: sub str2array {
1.265     albertel 2318:     my ($string)=@_;
                   2319:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2320:     return @$array;
                   2321: }
                   2322: 
                   2323: sub str2arrayref {
1.204     albertel 2324:   my ($string) = @_;
1.265     albertel 2325:   my @array;
                   2326: 
                   2327:   if($string !~ /^__ARRAY_REF__/) {
                   2328:       if (! ($string eq '' || !defined($string))) {
                   2329: 	  $array[0]='Array reference error';
                   2330:       }
                   2331:       return (\@array, $string);
                   2332:   }
                   2333: 
                   2334:   $string =~ s/^__ARRAY_REF__//;
                   2335: 
                   2336:   while($string !~ /^__END_ARRAY_REF__/) {
                   2337:       my $value='';
                   2338:       if($string =~ /^__HASH_REF__/) {
                   2339:           ($value, $string)=&str2hashref($string);
                   2340:           if(defined($value->{'error'})) {
                   2341:               $array[0] ='Array reference error';
                   2342:               return (\@array, $string);
                   2343:           }
                   2344:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2345:           ($value, $string)=&str2arrayref($string);
                   2346:           if($value->[0] eq 'Array reference error') {
                   2347:               $array[0] ='Array reference error';
                   2348:               return (\@array, $string);
                   2349:           }
                   2350:       } else {
                   2351: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2352:       }
                   2353:       $string =~ s/^&//;
                   2354: 
                   2355:       push(@array, $value);
1.191     harris41 2356:   }
1.265     albertel 2357: 
                   2358:   $string =~ s/^__END_ARRAY_REF__//;
                   2359: 
                   2360:   return (\@array, $string);
1.168     albertel 2361: }
                   2362: 
1.167     albertel 2363: # -------------------------------------------------------------------Temp Store
                   2364: 
1.168     albertel 2365: sub tmpreset {
                   2366:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2367:   if (!$symb) {
                   2368:     $symb=&symbread();
1.620     albertel 2369:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2370:   }
                   2371:   $symb=escape($symb);
                   2372: 
1.620     albertel 2373:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2374:   $namespace=~s/\//\_/g;
                   2375:   $namespace=~s/\W//g;
                   2376: 
1.620     albertel 2377:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2378:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2379:   if ($domain eq 'public' && $stuname eq 'public') {
                   2380:       $stuname=$ENV{'REMOTE_ADDR'};
                   2381:   }
1.168     albertel 2382:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2383:   my %hash;
                   2384:   if (tie(%hash,'GDBM_File',
                   2385: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2386: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2387:     foreach my $key (keys %hash) {
1.180     albertel 2388:       if ($key=~ /:$symb/) {
1.168     albertel 2389: 	delete($hash{$key});
                   2390:       }
                   2391:     }
                   2392:   }
                   2393: }
                   2394: 
1.167     albertel 2395: sub tmpstore {
1.168     albertel 2396:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2397: 
                   2398:   if (!$symb) {
                   2399:     $symb=&symbread();
1.620     albertel 2400:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2401:   }
                   2402:   $symb=escape($symb);
                   2403: 
                   2404:   if (!$namespace) {
                   2405:     # I don't think we would ever want to store this for a course.
                   2406:     # it seems this will only be used if we don't have a course.
1.620     albertel 2407:     #$namespace=$env{'request.course.id'};
1.168     albertel 2408:     #if (!$namespace) {
1.620     albertel 2409:       $namespace=$env{'request.state'};
1.168     albertel 2410:     #}
                   2411:   }
                   2412:   $namespace=~s/\//\_/g;
                   2413:   $namespace=~s/\W//g;
1.620     albertel 2414:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2415:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2416:   if ($domain eq 'public' && $stuname eq 'public') {
                   2417:       $stuname=$ENV{'REMOTE_ADDR'};
                   2418:   }
1.168     albertel 2419:   my $now=time;
                   2420:   my %hash;
                   2421:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2422:   if (tie(%hash,'GDBM_File',
                   2423: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2424: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2425:     $hash{"version:$symb"}++;
                   2426:     my $version=$hash{"version:$symb"};
                   2427:     my $allkeys=''; 
                   2428:     foreach my $key (keys(%$storehash)) {
                   2429:       $allkeys.=$key.':';
1.591     albertel 2430:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2431:     }
                   2432:     $hash{"$version:$symb:timestamp"}=$now;
                   2433:     $allkeys.='timestamp';
                   2434:     $hash{"$version:keys:$symb"}=$allkeys;
                   2435:     if (untie(%hash)) {
                   2436:       return 'ok';
                   2437:     } else {
                   2438:       return "error:$!";
                   2439:     }
                   2440:   } else {
                   2441:     return "error:$!";
                   2442:   }
                   2443: }
1.167     albertel 2444: 
1.168     albertel 2445: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2446: 
1.168     albertel 2447: sub tmprestore {
                   2448:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2449: 
1.168     albertel 2450:   if (!$symb) {
                   2451:     $symb=&symbread();
1.620     albertel 2452:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2453:   }
                   2454:   $symb=escape($symb);
                   2455: 
1.620     albertel 2456:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2457: 
1.620     albertel 2458:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2459:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2460:   if ($domain eq 'public' && $stuname eq 'public') {
                   2461:       $stuname=$ENV{'REMOTE_ADDR'};
                   2462:   }
1.168     albertel 2463:   my %returnhash;
                   2464:   $namespace=~s/\//\_/g;
                   2465:   $namespace=~s/\W//g;
                   2466:   my %hash;
                   2467:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2468:   if (tie(%hash,'GDBM_File',
                   2469: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2470: 	  &GDBM_READER(),0640)) {
1.168     albertel 2471:     my $version=$hash{"version:$symb"};
                   2472:     $returnhash{'version'}=$version;
                   2473:     my $scope;
                   2474:     for ($scope=1;$scope<=$version;$scope++) {
                   2475:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2476:       my @keys=split(/:/,$vkeys);
                   2477:       my $key;
                   2478:       $returnhash{"$scope:keys"}=$vkeys;
                   2479:       foreach $key (@keys) {
1.591     albertel 2480: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2481: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2482:       }
                   2483:     }
1.168     albertel 2484:     if (!(untie(%hash))) {
                   2485:       return "error:$!";
                   2486:     }
                   2487:   } else {
                   2488:     return "error:$!";
                   2489:   }
                   2490:   return %returnhash;
1.167     albertel 2491: }
                   2492: 
1.9       www      2493: # ----------------------------------------------------------------------- Store
                   2494: 
                   2495: sub store {
1.124     www      2496:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2497:     my $home='';
                   2498: 
1.168     albertel 2499:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2500: 
1.213     www      2501:     $symb=&symbclean($symb);
1.122     albertel 2502:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2503: 
1.620     albertel 2504:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2505:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2506: 
                   2507:     &devalidate($symb,$stuname,$domain);
1.109     www      2508: 
                   2509:     $symb=escape($symb);
1.187     www      2510:     if (!$namespace) { 
1.620     albertel 2511:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2512:           return ''; 
                   2513:        } 
                   2514:     }
1.620     albertel 2515:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2516: 
                   2517:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2518:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2519: 
1.12      www      2520:     my $namevalue='';
1.191     harris41 2521:     foreach (keys %$storehash) {
1.591     albertel 2522:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2523:     }
1.12      www      2524:     $namevalue=~s/\&$//;
1.187     www      2525:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2526:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2527: }
                   2528: 
1.47      www      2529: # -------------------------------------------------------------- Critical Store
                   2530: 
                   2531: sub cstore {
1.124     www      2532:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2533:     my $home='';
                   2534: 
1.168     albertel 2535:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2536: 
1.213     www      2537:     $symb=&symbclean($symb);
1.122     albertel 2538:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2539: 
1.620     albertel 2540:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2541:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2542: 
                   2543:     &devalidate($symb,$stuname,$domain);
1.109     www      2544: 
                   2545:     $symb=escape($symb);
1.187     www      2546:     if (!$namespace) { 
1.620     albertel 2547:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2548:           return ''; 
                   2549:        } 
                   2550:     }
1.620     albertel 2551:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2552: 
                   2553:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2554:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2555: 
1.47      www      2556:     my $namevalue='';
1.191     harris41 2557:     foreach (keys %$storehash) {
1.591     albertel 2558:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2559:     }
1.47      www      2560:     $namevalue=~s/\&$//;
1.187     www      2561:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2562:     return critical
                   2563:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2564: }
                   2565: 
1.9       www      2566: # --------------------------------------------------------------------- Restore
                   2567: 
                   2568: sub restore {
1.124     www      2569:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2570:     my $home='';
                   2571: 
1.168     albertel 2572:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2573: 
1.122     albertel 2574:     if (!$symb) {
                   2575:       unless ($symb=escape(&symbread())) { return ''; }
                   2576:     } else {
1.213     www      2577:       $symb=&escape(&symbclean($symb));
1.122     albertel 2578:     }
1.188     www      2579:     if (!$namespace) { 
1.620     albertel 2580:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2581:           return ''; 
                   2582:        } 
                   2583:     }
1.620     albertel 2584:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2585:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2586:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2587:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2588: 
1.12      www      2589:     my %returnhash=();
1.191     harris41 2590:     foreach (split(/\&/,$answer)) {
1.12      www      2591: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2592:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2593:     }
1.75      www      2594:     my $version;
                   2595:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2596:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2597:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2598:        }
1.75      www      2599:     }
1.13      www      2600:     return %returnhash;
1.34      www      2601: }
                   2602: 
                   2603: # ---------------------------------------------------------- Course Description
                   2604: 
                   2605: sub coursedescription {
1.731     albertel 2606:     my ($courseid,$args)=@_;
1.34      www      2607:     $courseid=~s/^\///;
1.49      www      2608:     $courseid=~s/\_/\//g;
1.34      www      2609:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2610:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2611:     my $normalid=$cdomain.'_'.$cnum;
                   2612:     # need to always cache even if we get errors otherwise we keep 
                   2613:     # trying and trying and trying to get the course description.
                   2614:     my %envhash=();
                   2615:     my %returnhash=();
1.731     albertel 2616:     
                   2617:     my $expiretime=600;
                   2618:     if ($env{'request.course.id'} eq $normalid) {
                   2619: 	$expiretime=120;
                   2620:     }
                   2621: 
                   2622:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2623:     if (!$args->{'freshen_cache'}
                   2624: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2625: 	foreach my $key (keys(%env)) {
                   2626: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2627: 	    my ($setting) = $1;
                   2628: 	    $returnhash{$setting} = $env{$key};
                   2629: 	}
                   2630: 	return %returnhash;
                   2631:     }
                   2632: 
                   2633:     # get the data agin
                   2634:     if (!$args->{'one_time'}) {
                   2635: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2636:     }
1.34      www      2637:     if ($chome ne 'no_host') {
1.302     albertel 2638:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2639:        if (!exists($returnhash{'con_lost'})) {
                   2640:            $returnhash{'home'}= $chome;
                   2641: 	   $returnhash{'domain'} = $cdomain;
                   2642: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2643:            while (my ($name,$value) = each %returnhash) {
1.53      www      2644:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2645:            }
1.270     www      2646:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2647:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2648: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2649:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2650:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2651:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2652:        }
                   2653:     }
1.731     albertel 2654:     if (!$args->{'one_time'}) {
                   2655: 	&appenv(%envhash);
                   2656:     }
1.302     albertel 2657:     return %returnhash;
1.461     www      2658: }
                   2659: 
                   2660: # -------------------------------------------------See if a user is privileged
                   2661: 
                   2662: sub privileged {
                   2663:     my ($username,$domain)=@_;
                   2664:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2665: 			&homeserver($username,$domain));
                   2666:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2667:     my $now=time;
                   2668:     if ($rolesdump ne '') {
                   2669:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2670: 	    if ($_!~/^rolesdef_/) {
1.461     www      2671: 		my ($area,$role)=split(/=/,$_);
                   2672: 		$area=~s/\_\w\w$//;
                   2673: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2674: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2675: 		    my $active=1;
                   2676: 		    if ($tend) {
                   2677: 			if ($tend<$now) { $active=0; }
                   2678: 		    }
                   2679: 		    if ($tstart) {
                   2680: 			if ($tstart>$now) { $active=0; }
                   2681: 		    }
                   2682: 		    if ($active) { return 1; }
                   2683: 		}
                   2684: 	    }
                   2685: 	}
                   2686:     }
                   2687:     return 0;
1.9       www      2688: }
1.1       albertel 2689: 
1.103     harris41 2690: # -------------------------------------------------------- Get user privileges
1.11      www      2691: 
                   2692: sub rolesinit {
                   2693:     my ($domain,$username,$authhost)=@_;
                   2694:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2695:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2696:     my %allroles=();
1.678     raeburn  2697:     my %allgroups=();   
1.11      www      2698:     my $now=time;
1.21      www      2699:     my $userroles="user.login.time=$now\n";
1.678     raeburn  2700:     my $group_privs;
1.11      www      2701: 
                   2702:     if ($rolesdump ne '') {
1.191     harris41 2703:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2704: 	  if ($_!~/^rolesdef_/) {
1.11      www      2705:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2706: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2707:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2708: 	    if ($role=~/^cr/) { 
1.655     albertel 2709: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2710: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2711: 		    ($tend,$tstart)=split('_',$trest);
                   2712: 		} else {
                   2713: 		    $trole=$role;
                   2714: 		}
1.678     raeburn  2715:             } elsif ($role =~ m|^gr/|) {
                   2716:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2717:                 ($trole,$group_privs) = split(/\//,$trole);
                   2718:                 $group_privs = &unescape($group_privs);
1.587     albertel 2719: 	    } else {
                   2720: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2721: 	    }
1.576     albertel 2722:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567     raeburn  2723:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2724:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2725:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2726: 		my $spec=$trole.'.'.$area;
                   2727: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2728: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2729:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2730:                 } elsif ($trole eq 'gr') {
                   2731:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2732: 		} else {
1.567     raeburn  2733:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2734: 		}
1.12      www      2735:             }
1.662     raeburn  2736:           }
1.191     harris41 2737:         }
1.678     raeburn  2738:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
1.128     www      2739:         $userroles.='user.adv='.$adv."\n".
                   2740: 	            'user.author='.$author."\n";
1.620     albertel 2741:         $env{'user.adv'}=$adv;
1.11      www      2742:     }
                   2743:     return $userroles;  
                   2744: }
                   2745: 
1.567     raeburn  2746: sub set_arearole {
                   2747:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2748: # log the associated role with the area
                   2749:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   2750:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
                   2751: }
                   2752: 
                   2753: sub custom_roleprivs {
                   2754:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2755:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2756:     my $homsvr=homeserver($rauthor,$rdomain);
                   2757:     if ($hostname{$homsvr} ne '') {
                   2758:         my ($rdummy,$roledef)=
                   2759:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2760:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2761:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2762:             if (defined($syspriv)) {
                   2763:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2764:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2765:             }
                   2766:             if ($tdomain ne '') {
                   2767:                 if (defined($dompriv)) {
                   2768:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2769:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2770:                 }
                   2771:                 if (($trest ne '') && (defined($coursepriv))) {
                   2772:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2773:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2774:                 }
                   2775:             }
                   2776:         }
                   2777:     }
                   2778: }
                   2779: 
1.678     raeburn  2780: sub group_roleprivs {
                   2781:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2782:     my $access = 1;
                   2783:     my $now = time;
                   2784:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2785:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2786:     if ($access) {
                   2787:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2788:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2789:     }
                   2790: }
1.567     raeburn  2791: 
                   2792: sub standard_roleprivs {
                   2793:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2794:     if (defined($pr{$trole.':s'})) {
                   2795:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2796:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2797:     }
                   2798:     if ($tdomain ne '') {
                   2799:         if (defined($pr{$trole.':d'})) {
                   2800:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2801:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2802:         }
                   2803:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2804:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2805:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2806:         }
                   2807:     }
                   2808: }
                   2809: 
                   2810: sub set_userprivs {
1.678     raeburn  2811:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2812:     my $author=0;
                   2813:     my $adv=0;
1.678     raeburn  2814:     my %grouproles = ();
                   2815:     if (keys(%{$allgroups}) > 0) {
                   2816:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2817:             my ($trole,$area,$sec,$extendedarea);
                   2818:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2819:                 $trole = $1;
                   2820:                 $area = $2;
1.681     raeburn  2821:                 $sec = $3;
                   2822:                 $extendedarea = $area.$sec;
                   2823:                 if (exists($$allgroups{$area})) {
                   2824:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2825:                         my $spec = $trole.'.'.$extendedarea;
                   2826:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2827:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2828:                     }
                   2829:                 }
                   2830:             }
                   2831:         }
                   2832:     }
                   2833:     foreach (keys(%grouproles)) {
                   2834:         $$allroles{$_} = $grouproles{$_};
                   2835:     }
1.567     raeburn  2836:     foreach (keys %{$allroles}) {
                   2837:         my %thesepriv=();
                   2838:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2839:         foreach (split(/:/,$$allroles{$_})) {
                   2840:             if ($_ ne '') {
                   2841:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2842:                 if ($restrictions eq '') {
                   2843:                     $thesepriv{$privilege}='F';
                   2844:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2845:                     $thesepriv{$privilege}.=$restrictions;
                   2846:                 }
                   2847:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2848:             }
                   2849:         }
                   2850:         my $thesestr='';
                   2851:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
                   2852:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
                   2853:     }
                   2854:     return ($author,$adv);
                   2855: }
                   2856: 
1.12      www      2857: # --------------------------------------------------------------- get interface
                   2858: 
                   2859: sub get {
1.131     albertel 2860:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2861:    my $items='';
1.191     harris41 2862:    foreach (@$storearr) {
1.12      www      2863:        $items.=escape($_).'&';
1.191     harris41 2864:    }
1.12      www      2865:    $items=~s/\&$//;
1.620     albertel 2866:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2867:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2868:    my $uhome=&homeserver($uname,$udomain);
                   2869: 
1.133     albertel 2870:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2871:    my @pairs=split(/\&/,$rep);
1.273     albertel 2872:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2873:      return @pairs;
                   2874:    }
1.15      www      2875:    my %returnhash=();
1.42      www      2876:    my $i=0;
1.191     harris41 2877:    foreach (@$storearr) {
1.557     albertel 2878:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2879:       $i++;
1.191     harris41 2880:    }
1.15      www      2881:    return %returnhash;
1.27      www      2882: }
                   2883: 
                   2884: # --------------------------------------------------------------- del interface
                   2885: 
                   2886: sub del {
1.133     albertel 2887:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2888:    my $items='';
1.191     harris41 2889:    foreach (@$storearr) {
1.27      www      2890:        $items.=escape($_).'&';
1.191     harris41 2891:    }
1.27      www      2892:    $items=~s/\&$//;
1.620     albertel 2893:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2894:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2895:    my $uhome=&homeserver($uname,$udomain);
                   2896: 
                   2897:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2898: }
                   2899: 
                   2900: # -------------------------------------------------------------- dump interface
                   2901: 
                   2902: sub dump {
1.702     albertel 2903:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.620     albertel 2904:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2905:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2906:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2907:    if ($regexp) {
                   2908:        $regexp=&escape($regexp);
                   2909:    } else {
                   2910:        $regexp='.';
                   2911:    }
1.702     albertel 2912:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.12      www      2913:    my @pairs=split(/\&/,$rep);
                   2914:    my %returnhash=();
1.191     harris41 2915:    foreach (@pairs) {
1.702     albertel 2916:       my ($key,$value)=split(/=/,$_,2);
1.557     albertel 2917:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2918:    }
                   2919:    return %returnhash;
1.407     www      2920: }
                   2921: 
1.717     albertel 2922: # --------------------------------------------------------- dumpstore interface
                   2923: 
                   2924: sub dumpstore {
                   2925:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2926:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2927: }
                   2928: 
1.407     www      2929: # -------------------------------------------------------------- keys interface
                   2930: 
                   2931: sub getkeys {
                   2932:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2933:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2934:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2935:    my $uhome=&homeserver($uname,$udomain);
                   2936:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2937:    my @keyarray=();
                   2938:    foreach (split(/\&/,$rep)) {
                   2939:       push (@keyarray,&unescape($_));
                   2940:    }
                   2941:    return @keyarray;
1.318     matthew  2942: }
                   2943: 
1.319     matthew  2944: # --------------------------------------------------------------- currentdump
                   2945: sub currentdump {
1.328     matthew  2946:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2947:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2948:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2949:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2950:    my $uhome = &homeserver($sname,$sdom);
                   2951:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2952:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2953:    #
1.318     matthew  2954:    my %returnhash=();
1.319     matthew  2955:    #
                   2956:    if ($rep eq "unknown_cmd") { 
                   2957:        # an old lond will not know currentdump
                   2958:        # Do a dump and make it look like a currentdump
1.326     matthew  2959:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2960:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2961:        my %hash = @tmp;
                   2962:        @tmp=();
1.424     matthew  2963:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2964:    } else {
                   2965:        my @pairs=split(/\&/,$rep);
                   2966:        foreach (@pairs) {
                   2967:            my ($key,$value)=split(/=/,$_);
                   2968:            my ($symb,$param) = split(/:/,$key);
                   2969:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2970:                                                         &thaw_unescape($value);
1.319     matthew  2971:        }
1.191     harris41 2972:    }
1.12      www      2973:    return %returnhash;
1.424     matthew  2974: }
                   2975: 
                   2976: sub convert_dump_to_currentdump{
                   2977:     my %hash = %{shift()};
                   2978:     my %returnhash;
                   2979:     # Code ripped from lond, essentially.  The only difference
                   2980:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2981:     # we might run in to problems with parameter names =~ /^v\./
                   2982:     while (my ($key,$value) = each(%hash)) {
                   2983:         my ($v,$symb,$param) = split(/:/,$key);
                   2984:         next if ($v eq 'version' || $symb eq 'keys');
                   2985:         next if (exists($returnhash{$symb}) &&
                   2986:                  exists($returnhash{$symb}->{$param}) &&
                   2987:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2988:         $returnhash{$symb}->{$param}=$value;
                   2989:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2990:     }
                   2991:     #
                   2992:     # Remove all of the keys in the hashes which keep track of
                   2993:     # the version of the parameter.
                   2994:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2995:         # use a foreach because we are going to delete from the hash.
                   2996:         foreach my $key (keys(%$param_hash)) {
                   2997:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2998:         }
                   2999:     }
                   3000:     return \%returnhash;
1.12      www      3001: }
                   3002: 
1.627     albertel 3003: # ------------------------------------------------------ critical inc interface
                   3004: 
                   3005: sub cinc {
                   3006:     return &inc(@_,'critical');
                   3007: }
                   3008: 
1.449     matthew  3009: # --------------------------------------------------------------- inc interface
                   3010: 
                   3011: sub inc {
1.627     albertel 3012:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3013:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3014:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3015:     my $uhome=&homeserver($uname,$udomain);
                   3016:     my $items='';
                   3017:     if (! ref($store)) {
                   3018:         # got a single value, so use that instead
                   3019:         $items = &escape($store).'=&';
                   3020:     } elsif (ref($store) eq 'SCALAR') {
                   3021:         $items = &escape($$store).'=&';        
                   3022:     } elsif (ref($store) eq 'ARRAY') {
                   3023:         $items = join('=&',map {&escape($_);} @{$store});
                   3024:     } elsif (ref($store) eq 'HASH') {
                   3025:         while (my($key,$value) = each(%{$store})) {
                   3026:             $items.= &escape($key).'='.&escape($value).'&';
                   3027:         }
                   3028:     }
                   3029:     $items=~s/\&$//;
1.627     albertel 3030:     if ($critical) {
                   3031: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3032:     } else {
                   3033: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3034:     }
1.449     matthew  3035: }
                   3036: 
1.12      www      3037: # --------------------------------------------------------------- put interface
                   3038: 
                   3039: sub put {
1.134     albertel 3040:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3041:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3042:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3043:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3044:    my $items='';
1.191     harris41 3045:    foreach (keys %$storehash) {
1.557     albertel 3046:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3047:    }
1.12      www      3048:    $items=~s/\&$//;
1.134     albertel 3049:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3050: }
                   3051: 
1.631     albertel 3052: # ------------------------------------------------------------ newput interface
                   3053: 
                   3054: sub newput {
                   3055:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3056:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3057:    if (!$uname) { $uname=$env{'user.name'}; }
                   3058:    my $uhome=&homeserver($uname,$udomain);
                   3059:    my $items='';
                   3060:    foreach my $key (keys(%$storehash)) {
                   3061:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3062:    }
                   3063:    $items=~s/\&$//;
                   3064:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3065: }
                   3066: 
                   3067: # ---------------------------------------------------------  putstore interface
                   3068: 
1.524     raeburn  3069: sub putstore {
1.715     albertel 3070:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3071:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3072:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3073:    my $uhome=&homeserver($uname,$udomain);
                   3074:    my $items='';
1.715     albertel 3075:    foreach my $key (keys(%$storehash)) {
                   3076:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3077:    }
1.715     albertel 3078:    $items=~s/\&$//;
1.716     albertel 3079:    my $esc_symb=&escape($symb);
                   3080:    my $esc_v=&escape($version);
1.715     albertel 3081:    my $reply =
1.716     albertel 3082:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3083: 	      $uhome);
                   3084:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3085:        # gfall back to way things use to be done
1.715     albertel 3086:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3087: 			    $uname);
1.524     raeburn  3088:    }
1.715     albertel 3089:    return $reply;
                   3090: }
                   3091: 
                   3092: sub old_putstore {
1.716     albertel 3093:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3094:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3095:     if (!$uname) { $uname=$env{'user.name'}; }
                   3096:     my $uhome=&homeserver($uname,$udomain);
                   3097:     my %newstorehash;
                   3098:     foreach (keys %$storehash) {
                   3099: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3100: 	$newstorehash{$key} = $storehash->{$_};
                   3101:     }
                   3102:     my $items='';
                   3103:     my %allitems = ();
                   3104:     foreach (keys %newstorehash) {
                   3105: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3106: 	    my $key = $1.':keys:'.$2;
                   3107: 	    $allitems{$key} .= $3.':';
                   3108: 	}
                   3109: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3110:     }
                   3111:     foreach (keys %allitems) {
                   3112: 	$allitems{$_} =~ s/\:$//;
                   3113: 	$items.= $_.'='.$allitems{$_}.'&';
                   3114:     }
                   3115:     $items=~s/\&$//;
                   3116:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3117: }
                   3118: 
1.47      www      3119: # ------------------------------------------------------ critical put interface
                   3120: 
                   3121: sub cput {
1.134     albertel 3122:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3123:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3124:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3125:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3126:    my $items='';
1.191     harris41 3127:    foreach (keys %$storehash) {
1.715     albertel 3128:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3129:    }
1.47      www      3130:    $items=~s/\&$//;
1.134     albertel 3131:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3132: }
                   3133: 
                   3134: # -------------------------------------------------------------- eget interface
                   3135: 
                   3136: sub eget {
1.133     albertel 3137:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3138:    my $items='';
1.191     harris41 3139:    foreach (@$storearr) {
1.12      www      3140:        $items.=escape($_).'&';
1.191     harris41 3141:    }
1.12      www      3142:    $items=~s/\&$//;
1.620     albertel 3143:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3144:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3145:    my $uhome=&homeserver($uname,$udomain);
                   3146:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3147:    my @pairs=split(/\&/,$rep);
                   3148:    my %returnhash=();
1.42      www      3149:    my $i=0;
1.191     harris41 3150:    foreach (@$storearr) {
1.557     albertel 3151:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3152:       $i++;
1.191     harris41 3153:    }
1.12      www      3154:    return %returnhash;
                   3155: }
                   3156: 
1.667     albertel 3157: # ------------------------------------------------------------ tmpput interface
                   3158: sub tmpput {
                   3159:     my ($storehash,$server)=@_;
                   3160:     my $items='';
                   3161:     foreach (keys(%$storehash)) {
                   3162: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3163:     }
                   3164:     $items=~s/\&$//;
                   3165:     return &reply("tmpput:$items",$server);
                   3166: }
                   3167: 
                   3168: # ------------------------------------------------------------ tmpget interface
                   3169: sub tmpget {
1.688     albertel 3170:     my ($token,$server)=@_;
                   3171:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3172:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3173:     my %returnhash;
                   3174:     foreach my $item (split(/\&/,$rep)) {
                   3175: 	my ($key,$value)=split(/=/,$item);
                   3176: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3177:     }
                   3178:     return %returnhash;
                   3179: }
                   3180: 
1.688     albertel 3181: # ------------------------------------------------------------ tmpget interface
                   3182: sub tmpdel {
                   3183:     my ($token,$server)=@_;
                   3184:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3185:     return &reply("tmpdel:$token",$server);
                   3186: }
                   3187: 
1.341     www      3188: # ---------------------------------------------- Custom access rule evaluation
                   3189: 
                   3190: sub customaccess {
                   3191:     my ($priv,$uri)=@_;
1.620     albertel 3192:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3193:     $urealm=~s/^\W//;
                   3194:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3195:     my $access=0;
                   3196:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3197: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3198:         if ($role) {
                   3199: 	   if ($role ne $urole) { next; }
                   3200:         }
                   3201:         foreach (split(/\s*\,\s*/,$realm)) {
                   3202:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3203:             if ($tdom) {
                   3204: 		if ($tdom ne $udom) { next; }
                   3205:             }
                   3206:             if ($tcrs) {
                   3207: 		if ($tcrs ne $ucrs) { next; }
                   3208:             }
                   3209:             if ($tsec) {
                   3210: 		if ($tsec ne $usec) { next; }
                   3211:             }
                   3212:             $access=($effect eq 'allow');
                   3213:             last;
1.342     www      3214:         }
1.402     bowersj2 3215: 	if ($realm eq '' && $role eq '') {
                   3216:             $access=($effect eq 'allow');
                   3217: 	}
1.341     www      3218:     }
                   3219:     return $access;
                   3220: }
                   3221: 
1.103     harris41 3222: # ------------------------------------------------- Check for a user privilege
1.12      www      3223: 
                   3224: sub allowed {
1.579     albertel 3225:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3226:     my $ver_orguri=$uri;
1.439     www      3227:     $uri=&deversion($uri);
1.152     www      3228:     my $orguri=$uri;
1.52      www      3229:     $uri=&declutter($uri);
1.545     banghart 3230:     
1.620     albertel 3231:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3232: # Free bre access to adm and meta resources
1.529     albertel 3233:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3234: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3235: 	return 'F';
1.159     www      3236:     }
                   3237: 
1.545     banghart 3238: # Free bre access to user's own portfolio contents
1.714     raeburn  3239:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3240:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3241: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3242:         return 'F';
                   3243:     }
                   3244: 
1.714     raeburn  3245: # bre access to group if user has rgf priv for this group and course.
                   3246:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3247:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3248:         if (exists($env{'request.course.id'})) {
                   3249:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3250:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3251:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3252:                 my $courseprivid=$env{'request.course.id'};
                   3253:                 $courseprivid=~s/\_/\//;
                   3254:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3255:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3256:                     return $1; 
                   3257:                 }
                   3258:             }
                   3259:         }
                   3260:     }
                   3261: 
1.159     www      3262: # Free bre to public access
                   3263: 
                   3264:     if ($priv eq 'bre') {
1.238     www      3265:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3266: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3267:            return 'F'; 
                   3268:         }
1.238     www      3269:         if ($copyright eq 'priv') {
                   3270:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3271: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3272: 		return '';
                   3273:             }
                   3274:         }
                   3275:         if ($copyright eq 'domain') {
                   3276:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3277: 	    unless (($env{'user.domain'} eq $1) ||
                   3278:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3279: 		return '';
                   3280:             }
1.262     matthew  3281:         }
1.620     albertel 3282:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3283:             # Library role, so allow browsing of resources in this domain.
                   3284:             return 'F';
1.238     www      3285:         }
1.341     www      3286:         if ($copyright eq 'custom') {
                   3287: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3288:         }
1.14      www      3289:     }
1.264     matthew  3290:     # Domain coordinator is trying to create a course
1.620     albertel 3291:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3292:         # uri is the requested domain in this case.
                   3293:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3294:         # a role of dc for the domain in question.
1.620     albertel 3295:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3296:     }
1.29      www      3297: 
1.52      www      3298:     my $thisallowed='';
                   3299:     my $statecond=0;
                   3300:     my $courseprivid='';
                   3301: 
                   3302: # Course
                   3303: 
1.620     albertel 3304:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3305:        $thisallowed.=$1;
                   3306:     }
1.29      www      3307: 
1.52      www      3308: # Domain
                   3309: 
1.620     albertel 3310:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3311:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3312:        $thisallowed.=$1;
                   3313:     }
1.52      www      3314: 
                   3315: # Course: uri itself is a course
1.66      www      3316:     my $courseuri=$uri;
                   3317:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3318:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3319: 
1.620     albertel 3320:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3321:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3322:        $thisallowed.=$1;
                   3323:     }
1.29      www      3324: 
1.678     raeburn  3325: # Group: uri itself is a group
                   3326:     my $groupuri=$uri;
                   3327:     $groupuri=~s/^([^\/])/\/$1/;
                   3328:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3329:        =~/\Q$priv\E\&([^\:]*)/) {
                   3330:        $thisallowed.=$1;
                   3331:     }
                   3332: 
1.665     albertel 3333: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3334: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3335:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3336: 	$thisallowed='';
1.671     raeburn  3337:         my ($match)=&is_on_map($uri);
                   3338:         if ($match) {
                   3339:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3340:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3341:                 $thisallowed.=$1;
                   3342:             }
                   3343:         } else {
1.705     albertel 3344:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3345:             if ($refuri) {
                   3346:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3347:                     $thisallowed='F';
1.671     raeburn  3348:                 } else {
                   3349:                     $refuri=&declutter($refuri);
                   3350:                     my ($match) = &is_on_map($refuri);
                   3351:                     if ($match) {
                   3352:                         $thisallowed='F';
                   3353:                     }
1.669     raeburn  3354:                 }
1.671     raeburn  3355:             }
                   3356:         }
1.314     www      3357:     }
1.492     albertel 3358: 
1.52      www      3359: # Full access at system, domain or course-wide level? Exit.
1.29      www      3360: 
                   3361:     if ($thisallowed=~/F/) {
                   3362: 	return 'F';
                   3363:     }
                   3364: 
1.52      www      3365: # If this is generating or modifying users, exit with special codes
1.29      www      3366: 
1.643     www      3367:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3368: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3369: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3370: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3371: 	    unless ($auname) { return $thisallowed; }
                   3372: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3373: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3374: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3375: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3376: 	}
1.52      www      3377: 	return $thisallowed;
                   3378:     }
                   3379: #
1.103     harris41 3380: # Gathered so far: system, domain and course wide privileges
1.52      www      3381: #
                   3382: # Course: See if uri or referer is an individual resource that is part of 
                   3383: # the course
                   3384: 
1.620     albertel 3385:     if ($env{'request.course.id'}) {
1.232     www      3386: 
1.620     albertel 3387:        $courseprivid=$env{'request.course.id'};
                   3388:        if ($env{'request.course.sec'}) {
                   3389:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3390:        }
                   3391:        $courseprivid=~s/\_/\//;
                   3392:        my $checkreferer=1;
1.232     www      3393:        my ($match,$cond)=&is_on_map($uri);
                   3394:        if ($match) {
                   3395:            $statecond=$cond;
1.620     albertel 3396:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3397:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3398:                $thisallowed.=$1;
                   3399:                $checkreferer=0;
                   3400:            }
1.29      www      3401:        }
1.83      www      3402:        
1.148     www      3403:        if ($checkreferer) {
1.620     albertel 3404: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3405:             unless ($refuri) {
1.620     albertel 3406:                 foreach (keys %env) {
1.148     www      3407: 		    if ($_=~/^httpref\..*\*/) {
                   3408: 			my $pattern=$_;
1.156     www      3409:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3410:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3411:                         $pattern=~s/\//\\\//g;
1.152     www      3412:                         if ($orguri=~/$pattern/) {
1.620     albertel 3413: 			    $refuri=$env{$_};
1.148     www      3414:                         }
                   3415:                     }
1.191     harris41 3416:                 }
1.148     www      3417:             }
1.232     www      3418: 
1.148     www      3419:          if ($refuri) { 
1.152     www      3420: 	  $refuri=&declutter($refuri);
1.232     www      3421:           my ($match,$cond)=&is_on_map($refuri);
                   3422:             if ($match) {
                   3423:               my $refstatecond=$cond;
1.620     albertel 3424:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3425:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3426:                   $thisallowed.=$1;
1.53      www      3427:                   $uri=$refuri;
                   3428:                   $statecond=$refstatecond;
1.52      www      3429:               }
                   3430:           }
1.148     www      3431:         }
1.29      www      3432:        }
1.52      www      3433:    }
1.29      www      3434: 
1.52      www      3435: #
1.103     harris41 3436: # Gathered now: all privileges that could apply, and condition number
1.52      www      3437: # 
                   3438: #
                   3439: # Full or no access?
                   3440: #
1.29      www      3441: 
1.52      www      3442:     if ($thisallowed=~/F/) {
                   3443: 	return 'F';
                   3444:     }
1.29      www      3445: 
1.52      www      3446:     unless ($thisallowed) {
                   3447:         return '';
                   3448:     }
1.29      www      3449: 
1.52      www      3450: # Restrictions exist, deal with them
                   3451: #
                   3452: #   C:according to course preferences
                   3453: #   R:according to resource settings
                   3454: #   L:unless locked
                   3455: #   X:according to user session state
                   3456: #
                   3457: 
                   3458: # Possibly locked functionality, check all courses
1.54      www      3459: # Locks might take effect only after 10 minutes cache expiration for other
                   3460: # courses, and 2 minutes for current course
1.52      www      3461: 
                   3462:     my $envkey;
                   3463:     if ($thisallowed=~/L/) {
1.620     albertel 3464:         foreach $envkey (keys %env) {
1.54      www      3465:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3466:                my $courseid=$2;
                   3467:                my $roleid=$1.'.'.$2;
1.92      www      3468:                $courseid=~s/^\///;
1.54      www      3469:                my $expiretime=600;
1.620     albertel 3470:                if ($env{'request.role'} eq $roleid) {
1.54      www      3471: 		  $expiretime=120;
                   3472:                }
                   3473: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3474:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3475:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3476: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3477:                }
1.620     albertel 3478:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3479:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3480: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3481:                        &log($env{'user.domain'},$env{'user.name'},
                   3482:                             $env{'user.home'},
1.57      www      3483:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3484:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3485:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3486: 		       return '';
                   3487:                    }
                   3488:                }
1.620     albertel 3489:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3490:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3491: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3492:                        &log($env{'user.domain'},$env{'user.name'},
                   3493:                             $env{'user.home'},
1.57      www      3494:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3495:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3496:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3497: 		       return '';
                   3498:                    }
                   3499:                }
                   3500: 	   }
1.29      www      3501:        }
1.52      www      3502:     }
                   3503:    
                   3504: #
                   3505: # Rest of the restrictions depend on selected course
                   3506: #
                   3507: 
1.620     albertel 3508:     unless ($env{'request.course.id'}) {
1.52      www      3509:        return '1';
                   3510:     }
1.29      www      3511: 
1.52      www      3512: #
                   3513: # Now user is definitely in a course
                   3514: #
1.53      www      3515: 
                   3516: 
                   3517: # Course preferences
                   3518: 
                   3519:    if ($thisallowed=~/C/) {
1.620     albertel 3520:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3521:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3522:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3523: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3524: 	   if ($priv ne 'pch') { 
                   3525: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3526: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3527: 			$env{'request.course.id'});
                   3528: 	   }
1.237     www      3529:            return '';
                   3530:        }
                   3531: 
1.620     albertel 3532:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3533: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3534: 	   if ($priv ne 'pch') { 
                   3535: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3536: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3537: 			$env{'request.course.id'});
                   3538: 	   }
1.54      www      3539:            return '';
                   3540:        }
1.53      www      3541:    }
                   3542: 
                   3543: # Resource preferences
                   3544: 
                   3545:    if ($thisallowed=~/R/) {
1.620     albertel 3546:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3547:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3548: 	   if ($priv ne 'pch') { 
                   3549: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3550: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3551: 	   }
                   3552: 	   return '';
1.54      www      3553:        }
1.53      www      3554:    }
1.30      www      3555: 
1.246     www      3556: # Restricted by state or randomout?
1.30      www      3557: 
1.52      www      3558:    if ($thisallowed=~/X/) {
1.620     albertel 3559:       if ($env{'acc.randomout'}) {
1.579     albertel 3560: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3561:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3562:             return ''; 
                   3563:          }
1.247     www      3564:       }
                   3565:       if (&condval($statecond)) {
1.52      www      3566: 	 return '2';
                   3567:       } else {
                   3568:          return '';
                   3569:       }
                   3570:    }
1.30      www      3571: 
1.52      www      3572:    return 'F';
1.232     www      3573: }
                   3574: 
1.710     albertel 3575: sub split_uri_for_cond {
                   3576:     my $uri=&deversion(&declutter(shift));
                   3577:     my @uriparts=split(/\//,$uri);
                   3578:     my $filename=pop(@uriparts);
                   3579:     my $pathname=join('/',@uriparts);
                   3580:     return ($pathname,$filename);
                   3581: }
1.232     www      3582: # --------------------------------------------------- Is a resource on the map?
                   3583: 
                   3584: sub is_on_map {
1.710     albertel 3585:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3586:     #Trying to find the conditional for the file
1.620     albertel 3587:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3588: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3589:     if ($match) {
1.289     bowersj2 3590: 	return (1,$1);
                   3591:     } else {
1.434     www      3592: 	return (0,0);
1.289     bowersj2 3593:     }
1.12      www      3594: }
                   3595: 
1.427     www      3596: # --------------------------------------------------------- Get symb from alias
                   3597: 
                   3598: sub get_symb_from_alias {
                   3599:     my $symb=shift;
                   3600:     my ($map,$resid,$url)=&decode_symb($symb);
                   3601: # Already is a symb
                   3602:     if ($url) { return $symb; }
                   3603: # Must be an alias
                   3604:     my $aliassymb='';
                   3605:     my %bighash;
1.620     albertel 3606:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3607:                             &GDBM_READER(),0640)) {
                   3608:         my $rid=$bighash{'mapalias_'.$symb};
                   3609: 	if ($rid) {
                   3610: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3611: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3612: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3613: 	}
                   3614:         untie %bighash;
                   3615:     }
                   3616:     return $aliassymb;
                   3617: }
                   3618: 
1.12      www      3619: # ----------------------------------------------------------------- Define Role
                   3620: 
                   3621: sub definerole {
                   3622:   if (allowed('mcr','/')) {
                   3623:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3624:     foreach (split(':',$sysrole)) {
1.21      www      3625: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3626:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3627:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3628: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3629:                return "refused:s:$crole&$cqual"; 
                   3630:             }
                   3631:         }
1.191     harris41 3632:     }
1.392     www      3633:     foreach (split(':',$domrole)) {
1.21      www      3634: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3635:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3636:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3637: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3638:                return "refused:d:$crole&$cqual"; 
                   3639:             }
                   3640:         }
1.191     harris41 3641:     }
1.392     www      3642:     foreach (split(':',$courole)) {
1.21      www      3643: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3644:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3645:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3646: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3647:                return "refused:c:$crole&$cqual"; 
                   3648:             }
                   3649:         }
1.191     harris41 3650:     }
1.620     albertel 3651:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3652:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3653: 	        "rolesdef_$rolename=".
                   3654:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3655:     return reply($command,$env{'user.home'});
1.12      www      3656:   } else {
                   3657:     return 'refused';
                   3658:   }
1.105     harris41 3659: }
                   3660: 
                   3661: # ---------------- Make a metadata query against the network of library servers
                   3662: 
                   3663: sub metadata_query {
1.244     matthew  3664:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3665:     my %rhash;
1.244     matthew  3666:     my @server_list = (defined($server_array) ? @$server_array
                   3667:                                               : keys(%libserv) );
                   3668:     for my $server (@server_list) {
1.118     harris41 3669: 	unless ($custom or $customshow) {
                   3670: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3671: 	    $rhash{$server}=$reply;
                   3672: 	}
                   3673: 	else {
                   3674: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3675: 			     &escape($custom).':'.&escape($customshow),
                   3676: 			     $server);
                   3677: 	    $rhash{$server}=$reply;
                   3678: 	}
1.112     harris41 3679:     }
1.118     harris41 3680:     return \%rhash;
1.240     www      3681: }
                   3682: 
                   3683: # ----------------------------------------- Send log queries and wait for reply
                   3684: 
                   3685: sub log_query {
                   3686:     my ($uname,$udom,$query,%filters)=@_;
                   3687:     my $uhome=&homeserver($uname,$udom);
                   3688:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3689:     my $uhost=$hostname{$uhome};
1.241     www      3690:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3691:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3692:                        $uhome);
1.479     albertel 3693:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3694:     return get_query_reply($queryid);
                   3695: }
                   3696: 
1.508     raeburn  3697: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3698: 
                   3699: sub fetch_enrollment_query {
1.511     raeburn  3700:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3701:     my $homeserver;
1.547     raeburn  3702:     my $maxtries = 1;
1.508     raeburn  3703:     if ($context eq 'automated') {
                   3704:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3705:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3706:     } else {
                   3707:         $homeserver = &homeserver($cnum,$dom);
                   3708:     }
1.506     raeburn  3709:     my $host=$hostname{$homeserver};
                   3710:     my $cmd = '';
                   3711:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3712:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3713:     }
                   3714:     $cmd =~ s/%%$//;
                   3715:     $cmd = &escape($cmd);
                   3716:     my $query = 'fetchenrollment';
1.620     albertel 3717:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3718:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3719:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3720:         return 'error: '.$queryid;
                   3721:     }
1.506     raeburn  3722:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3723:     my $tries = 1;
                   3724:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3725:         $reply = &get_query_reply($queryid);
                   3726:         $tries ++;
                   3727:     }
1.526     raeburn  3728:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3729:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3730:     } else {
1.515     raeburn  3731:         my @responses = split/:/,$reply;
                   3732:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3733:             foreach (@responses) {
                   3734:                 my ($key,$value) = split/=/,$_;
                   3735:                 $$replyref{$key} = $value;
                   3736:             }
                   3737:         } else {
1.506     raeburn  3738:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3739:             foreach (@responses) {
                   3740:                 my ($key,$value) = split/=/,$_;
                   3741:                 $$replyref{$key} = $value;
                   3742:                 if ($value > 0) {
                   3743:                     foreach (@{$$affiliatesref{$key}}) {
                   3744:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3745:                         my $destname = $pathname.'/'.$filename;
                   3746:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3747:                         if ($xml_classlist =~ /^error/) {
                   3748:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3749:                         } else {
1.506     raeburn  3750:                             if ( open(FILE,">$destname") ) {
                   3751:                                 print FILE &unescape($xml_classlist);
                   3752:                                 close(FILE);
1.526     raeburn  3753:                             } else {
                   3754:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3755:                             }
                   3756:                         }
                   3757:                     }
                   3758:                 }
                   3759:             }
                   3760:         }
                   3761:         return 'ok';
                   3762:     }
                   3763:     return 'error';
                   3764: }
                   3765: 
1.242     www      3766: sub get_query_reply {
                   3767:     my $queryid=shift;
1.240     www      3768:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3769:     my $reply='';
                   3770:     for (1..100) {
                   3771: 	sleep 2;
                   3772:         if (-e $replyfile.'.end') {
1.448     albertel 3773: 	    if (open(my $fh,$replyfile)) {
1.240     www      3774:                $reply.=<$fh>;
1.448     albertel 3775:                close($fh);
1.240     www      3776: 	   } else { return 'error: reply_file_error'; }
1.242     www      3777:            return &unescape($reply);
                   3778: 	}
1.240     www      3779:     }
1.242     www      3780:     return 'timeout:'.$queryid;
1.240     www      3781: }
                   3782: 
                   3783: sub courselog_query {
1.241     www      3784: #
                   3785: # possible filters:
                   3786: # url: url or symb
                   3787: # username
                   3788: # domain
                   3789: # action: view, submit, grade
                   3790: # start: timestamp
                   3791: # end: timestamp
                   3792: #
1.240     www      3793:     my (%filters)=@_;
1.620     albertel 3794:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3795:     if ($filters{'url'}) {
                   3796: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3797:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3798:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3799:     }
1.620     albertel 3800:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3801:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3802:     return &log_query($cname,$cdom,'courselog',%filters);
                   3803: }
                   3804: 
                   3805: sub userlog_query {
                   3806:     my ($uname,$udom,%filters)=@_;
                   3807:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3808: }
                   3809: 
1.506     raeburn  3810: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3811: 
                   3812: sub auto_run {
1.508     raeburn  3813:     my ($cnum,$cdom) = @_;
                   3814:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3815:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3816:     return $response;
                   3817: }
                   3818:                                                                                    
                   3819: sub auto_get_sections {
1.508     raeburn  3820:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3821:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3822:     my @secs = ();
1.511     raeburn  3823:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3824:     unless ($response eq 'refused') {
                   3825:         @secs = split/:/,$response;
                   3826:     }
                   3827:     return @secs;
                   3828: }
                   3829:                                                                                    
                   3830: sub auto_new_course {
1.508     raeburn  3831:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3832:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3833:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3834:     return $response;
                   3835: }
                   3836:                                                                                    
                   3837: sub auto_validate_courseID {
1.508     raeburn  3838:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3839:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3840:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3841:     return $response;
                   3842: }
                   3843:                                                                                    
                   3844: sub auto_create_password {
1.508     raeburn  3845:     my ($cnum,$cdom,$authparam) = @_;
                   3846:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3847:     my $create_passwd = 0;
                   3848:     my $authchk = '';
1.511     raeburn  3849:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3850:     if ($response eq 'refused') {
                   3851:         $authchk = 'refused';
                   3852:     } else {
                   3853:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3854:     }
                   3855:     return ($authparam,$create_passwd,$authchk);
                   3856: }
                   3857: 
1.706     raeburn  3858: sub auto_photo_permission {
                   3859:     my ($cnum,$cdom,$students) = @_;
                   3860:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 3861:     my ($outcome,$perm_reqd,$conditions) = 
                   3862: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 3863:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3864: 	return (undef,undef);
                   3865:     }
1.706     raeburn  3866:     return ($outcome,$perm_reqd,$conditions);
                   3867: }
                   3868: 
                   3869: sub auto_checkphotos {
                   3870:     my ($uname,$udom,$pid) = @_;
                   3871:     my $homeserver = &homeserver($uname,$udom);
                   3872:     my ($result,$resulttype);
                   3873:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 3874: 				   &escape($uname).':'.&escape($pid),
                   3875: 				   $homeserver));
1.709     albertel 3876:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3877: 	return (undef,undef);
                   3878:     }
1.706     raeburn  3879:     if ($outcome) {
                   3880:         ($result,$resulttype) = split(/:/,$outcome);
                   3881:     } 
                   3882:     return ($result,$resulttype);
                   3883: }
                   3884: 
                   3885: sub auto_photochoice {
                   3886:     my ($cnum,$cdom) = @_;
                   3887:     my $homeserver = &homeserver($cnum,$cdom);
                   3888:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 3889: 						       &escape($cdom),
                   3890: 						       $homeserver)));
1.709     albertel 3891:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3892: 	return (undef,undef);
                   3893:     }
1.706     raeburn  3894:     return ($update,$comment);
                   3895: }
                   3896: 
                   3897: sub auto_photoupdate {
                   3898:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   3899:     my $homeserver = &homeserver($cnum,$dom);
                   3900:     my $host=$hostname{$homeserver};
                   3901:     my $cmd = '';
                   3902:     my $maxtries = 1;
                   3903:     foreach (keys %{$affiliatesref}) {
                   3904:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   3905:     }
                   3906:     $cmd =~ s/%%$//;
                   3907:     $cmd = &escape($cmd);
                   3908:     my $query = 'institutionalphotos';
                   3909:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   3910:     unless ($queryid=~/^\Q$host\E\_/) {
                   3911:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   3912:         return 'error: '.$queryid;
                   3913:     }
                   3914:     my $reply = &get_query_reply($queryid);
                   3915:     my $tries = 1;
                   3916:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3917:         $reply = &get_query_reply($queryid);
                   3918:         $tries ++;
                   3919:     }
                   3920:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   3921:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   3922:     } else {
                   3923:         my @responses = split(/:/,$reply);
                   3924:         my $outcome = shift(@responses); 
                   3925:         foreach my $item (@responses) {
                   3926:             my ($key,$value) = split(/=/,$item);
                   3927:             $$photo{$key} = $value;
                   3928:         }
                   3929:         return $outcome;
                   3930:     }
                   3931:     return 'error';
                   3932: }
                   3933: 
1.521     raeburn  3934: sub auto_instcode_format {
                   3935:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3936:     my $courses = '';
                   3937:     my $homeserver;
                   3938:     if ($caller eq 'global') {
1.584     raeburn  3939:         foreach my $tryserver (keys %libserv) {
                   3940:             if ($hostdom{$tryserver} eq $codedom) {
                   3941:                 $homeserver = $tryserver;
                   3942:                 last;
                   3943:             }
                   3944:         }
1.620     albertel 3945:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3946:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3947:         }
1.521     raeburn  3948:     } else {
                   3949:         $homeserver = &homeserver($caller,$codedom);
                   3950:     }
                   3951:     foreach (keys %{$instcodes}) {
                   3952:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3953:     }
                   3954:     chop($courses);
                   3955:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3956:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3957:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3958:         %{$codes} = &str2hash($codes_str);
                   3959:         @{$codetitles} = &str2array($codetitles_str);
                   3960:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3961:         %{$cat_order} = &str2hash($cat_order_str);
                   3962:         return 'ok';
                   3963:     }
                   3964:     return $response;
                   3965: }
                   3966: 
1.679     raeburn  3967: # ------------------------------------------------------- Course Group routines
                   3968: 
                   3969: sub get_coursegroups {
1.683     raeburn  3970:     my ($cdom,$cnum,$group) = @_;
                   3971:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  3972: }
                   3973: 
                   3974: sub modify_coursegroup {
                   3975:     my ($cdom,$cnum,$groupsettings) = @_;
                   3976:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   3977: }
                   3978: 
                   3979: sub modify_group_roles {
                   3980:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   3981:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   3982:     my $role = 'gr/'.&escape($userprivs);
                   3983:     my ($uname,$udom) = split(/:/,$user);
                   3984:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  3985:     if ($result eq 'ok') {
                   3986:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   3987:     }
1.679     raeburn  3988:     return $result;
                   3989: }
                   3990: 
                   3991: sub modify_coursegroup_membership {
                   3992:     my ($cdom,$cnum,$membership) = @_;
                   3993:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   3994:     return $result;
                   3995: }
                   3996: 
1.682     raeburn  3997: sub get_active_groups {
                   3998:     my ($udom,$uname,$cdom,$cnum) = @_;
                   3999:     my $now = time;
                   4000:     my %groups = ();
                   4001:     foreach my $key (keys(%env)) {
                   4002:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4003:             my ($start,$end) = split(/\./,$env{$key});
                   4004:             if (($end!=0) && ($end<$now)) { next; }
                   4005:             if (($start!=0) && ($start>$now)) { next; }
                   4006:             if ($1 eq $cdom && $2 eq $cnum) {
                   4007:                 $groups{$3} = $env{$key} ;
                   4008:             }
                   4009:         }
                   4010:     }
                   4011:     return %groups;
                   4012: }
                   4013: 
1.683     raeburn  4014: sub get_group_membership {
                   4015:     my ($cdom,$cnum,$group) = @_;
                   4016:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4017: }
                   4018: 
                   4019: sub get_users_groups {
                   4020:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4021:     my @usersgroups;
1.683     raeburn  4022:     my $cachetime=1800;
                   4023:     $courseid=~s/\_/\//g;
                   4024:     $courseid=~s/^(\w)/\/$1/;
                   4025: 
                   4026:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4027:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4028:     if (defined($cached)) {
1.734     albertel 4029:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4030:     } else {  
                   4031:         $grouplist = '';
                   4032:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4033:         my ($tmp) = keys(%roleshash);
                   4034:         if ($tmp=~/^error:/) {
                   4035:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4036:         } else {
                   4037:             my $access_end = $env{'course.'.$courseid.
                   4038:                                   '.default_enrollment_end_date'};
                   4039:             my $now = time;
1.734     albertel 4040:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4041:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4042:                     my $group = $1;
                   4043:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4044:                         my $start = $2;
                   4045:                         my $end = $1;
                   4046:                         if ($start == -1) { next; } # deleted from group
                   4047:                         if (($start!=0) && ($start>$now)) { next; }
                   4048:                         if (($end!=0) && ($end<$now)) {
                   4049:                             if ($access_end && $access_end < $now) {
                   4050:                                 if ($access_end - $end < 86400) {
                   4051:                                     push(@usersgroups,$group);
                   4052:                                 }
                   4053:                             }
                   4054:                             next;
                   4055:                         }
                   4056:                         push(@usersgroups,$group);
                   4057:                     }
1.683     raeburn  4058:                 }
                   4059:             }
1.733     raeburn  4060:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4061:             $grouplist = join(':',@usersgroups);
                   4062:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4063:         }
                   4064:     }
1.733     raeburn  4065:     return @usersgroups;
1.683     raeburn  4066: }
                   4067: 
                   4068: sub devalidate_getgroups_cache {
                   4069:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4070:     my $courseid = $cdom.'_'.$cnum;
                   4071:     $courseid=~s/\_/\//g;
                   4072:     $courseid=~s/^(\w)/\/$1/;
                   4073:     my $hashid="$udom:$uname:$courseid";
                   4074:     &devalidate_cache_new('getgroups',$hashid);
                   4075: }
                   4076: 
1.12      www      4077: # ------------------------------------------------------------------ Plain Text
                   4078: 
                   4079: sub plaintext {
1.22      www      4080:     my $short=shift;
1.676     albertel 4081:     return &Apache::lonlocal::mt($prp{$short});
1.12      www      4082: }
                   4083: 
                   4084: # ----------------------------------------------------------------- Assign Role
                   4085: 
                   4086: sub assignrole {
1.357     www      4087:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4088:     my $mrole;
                   4089:     if ($role =~ /^cr\//) {
1.393     www      4090:         my $cwosec=$url;
                   4091:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4092: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4093:            &logthis('Refused custom assignrole: '.
                   4094:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4095: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4096:            return 'refused'; 
                   4097:         }
1.21      www      4098:         $mrole='cr';
1.678     raeburn  4099:     } elsif ($role =~ /^gr\//) {
                   4100:         my $cwogrp=$url;
                   4101:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4102:         unless (&allowed('mdg',$cwogrp)) {
                   4103:             &logthis('Refused group assignrole: '.
                   4104:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4105:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4106:             return 'refused';
                   4107:         }
                   4108:         $mrole='gr';
1.21      www      4109:     } else {
1.82      www      4110:         my $cwosec=$url;
1.83      www      4111:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4112:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4113:            &logthis('Refused assignrole: '.
                   4114:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4115: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4116:            return 'refused'; 
                   4117:         }
1.21      www      4118:         $mrole=$role;
                   4119:     }
1.620     albertel 4120:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4121:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4122:     if ($end) { $command.='_'.$end; }
1.21      www      4123:     if ($start) {
                   4124: 	if ($end) { 
1.81      www      4125:            $command.='_'.$start; 
1.21      www      4126:         } else {
1.81      www      4127:            $command.='_0_'.$start;
1.21      www      4128:         }
                   4129:     }
1.739     raeburn  4130:     my $origstart = $start;
                   4131:     my $origend = $end;
1.357     www      4132: # actually delete
                   4133:     if ($deleteflag) {
1.373     www      4134: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4135: # modify command to delete the role
1.620     albertel 4136:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4137:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4138: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4139: # set start and finish to negative values for userrolelog
                   4140:            $start=-1;
                   4141:            $end=-1;
                   4142:         }
                   4143:     }
                   4144: # send command
1.349     www      4145:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4146: # log new user role if status is ok
1.349     www      4147:     if ($answer eq 'ok') {
1.663     raeburn  4148: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4149: # for course roles, perform group memberships changes triggered by role change.
                   4150:         unless ($role =~ /^gr/) {
                   4151:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4152:                                              $origstart);
                   4153:         }
1.349     www      4154:     }
                   4155:     return $answer;
1.169     harris41 4156: }
                   4157: 
                   4158: # -------------------------------------------------- Modify user authentication
1.197     www      4159: # Overrides without validation
                   4160: 
1.169     harris41 4161: sub modifyuserauth {
                   4162:     my ($udom,$uname,$umode,$upass)=@_;
                   4163:     my $uhome=&homeserver($uname,$udom);
1.197     www      4164:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4165:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4166:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4167:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4168:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4169: 		     &escape($upass),$uhome);
1.620     albertel 4170:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4171:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4172:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4173:     &log($udom,,$uname,$uhome,
1.620     albertel 4174:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4175:                                      $env{'user.name'}.', '.$umode.
1.197     www      4176:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4177:     unless ($reply eq 'ok') {
1.197     www      4178:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4179: 	return 'error: '.$reply;
                   4180:     }   
1.170     harris41 4181:     return 'ok';
1.80      www      4182: }
                   4183: 
1.81      www      4184: # --------------------------------------------------------------- Modify a user
1.80      www      4185: 
1.81      www      4186: sub modifyuser {
1.206     matthew  4187:     my ($udom,    $uname, $uid,
                   4188:         $umode,   $upass, $first,
                   4189:         $middle,  $last,  $gene,
1.387     www      4190:         $forceid, $desiredhome, $email)=@_;
1.198     www      4191:     $udom=~s/\W//g;
                   4192:     $uname=~s/\W//g;
1.81      www      4193:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4194:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4195: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4196:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4197:                                      ' desiredhome not specified'). 
1.620     albertel 4198:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4199:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4200:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4201: # ----------------------------------------------------------------- Create User
1.406     albertel 4202:     if (($uhome eq 'no_host') && 
                   4203: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4204:         my $unhome='';
1.209     matthew  4205:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4206:             $unhome = $desiredhome;
1.620     albertel 4207: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4208: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4209:         } else { # load balancing routine for determining $unhome
1.80      www      4210:             my $tryserver;
1.81      www      4211:             my $loadm=10000000;
1.80      www      4212:             foreach $tryserver (keys %libserv) {
                   4213: 	       if ($hostdom{$tryserver} eq $udom) {
                   4214:                   my $answer=reply('load',$tryserver);
                   4215:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4216: 		      $loadm=$answer;
                   4217:                       $unhome=$tryserver;
                   4218:                   }
                   4219: 	       }
                   4220: 	    }
                   4221:         }
                   4222:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4223: 	    return 'error: unable to find a home server for '.$uname.
                   4224:                    ' in domain '.$udom;
1.80      www      4225:         }
                   4226:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4227:                          &escape($upass),$unhome);
                   4228: 	unless ($reply eq 'ok') {
                   4229:             return 'error: '.$reply;
                   4230:         }   
1.230     stredwic 4231:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4232:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4233: 	    return 'error: unable verify users home machine.';
1.80      www      4234:         }
1.209     matthew  4235:     }   # End of creation of new user
1.80      www      4236: # ---------------------------------------------------------------------- Add ID
                   4237:     if ($uid) {
                   4238:        $uid=~tr/A-Z/a-z/;
                   4239:        my %uidhash=&idrget($udom,$uname);
1.196     www      4240:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4241:          && (!$forceid)) {
1.80      www      4242: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4243: 	      return 'error: user id "'.$uid.'" does not match '.
                   4244:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4245:           }
                   4246:        } else {
                   4247: 	  &idput($udom,($uname => $uid));
                   4248:        }
                   4249:     }
                   4250: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4251:     my @tmp=&get('environment',
1.134     albertel 4252: 		   ['firstname','middlename','lastname','generation'],
                   4253: 		   $udom,$uname);
1.313     matthew  4254:     my %names;
                   4255:     if ($tmp[0] =~ m/^error:.*/) { 
                   4256:         %names=(); 
                   4257:     } else {
                   4258:         %names = @tmp;
                   4259:     }
1.388     www      4260: #
                   4261: # Make sure to not trash student environment if instructor does not bother
                   4262: # to supply name and email information
                   4263: #
                   4264:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4265:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4266:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4267:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4268:     if ($email) {
                   4269:        $email=~s/[^\w\@\.\-\,]//gs;
                   4270:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4271: 			   $names{'critnotification'} = $email;
                   4272: 			   $names{'permanentemail'} = $email; }
                   4273:     }
1.134     albertel 4274:     my $reply = &put('environment', \%names, $udom,$uname);
                   4275:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4276:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4277:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4278:              $umode.', '.$first.', '.$middle.', '.
                   4279: 	     $last.', '.$gene.' by '.
1.620     albertel 4280:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4281:     return 'ok';
1.80      www      4282: }
                   4283: 
1.81      www      4284: # -------------------------------------------------------------- Modify student
1.80      www      4285: 
1.81      www      4286: sub modifystudent {
                   4287:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4288:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4289:     if (!$cid) {
1.620     albertel 4290: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4291: 	    return 'not_in_class';
                   4292: 	}
1.80      www      4293:     }
                   4294: # --------------------------------------------------------------- Make the user
1.81      www      4295:     my $reply=&modifyuser
1.209     matthew  4296: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4297:          $desiredhome,$email);
1.80      www      4298:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4299:     # This will cause &modify_student_enrollment to get the uid from the
                   4300:     # students environment
                   4301:     $uid = undef if (!$forceid);
1.455     albertel 4302:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4303: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4304:     return $reply;
                   4305: }
                   4306: 
                   4307: sub modify_student_enrollment {
1.515     raeburn  4308:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4309:     my ($cdom,$cnum,$chome);
                   4310:     if (!$cid) {
1.620     albertel 4311: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4312: 	    return 'not_in_class';
                   4313: 	}
1.620     albertel 4314: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4315: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4316:     } else {
                   4317: 	($cdom,$cnum)=split(/_/,$cid);
                   4318:     }
1.620     albertel 4319:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4320:     if (!$chome) {
1.457     raeburn  4321: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4322:     }
1.455     albertel 4323:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4324:     # Make sure the user exists
1.81      www      4325:     my $uhome=&homeserver($uname,$udom);
                   4326:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4327: 	return 'error: no such user';
                   4328:     }
1.297     matthew  4329:     # Get student data if we were not given enough information
                   4330:     if (!defined($first)  || $first  eq '' || 
                   4331:         !defined($last)   || $last   eq '' || 
                   4332:         !defined($uid)    || $uid    eq '' || 
                   4333:         !defined($middle) || $middle eq '' || 
                   4334:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4335:         # They did not supply us with enough data to enroll the student, so
                   4336:         # we need to pick up more information.
1.297     matthew  4337:         my %tmp = &get('environment',
1.294     matthew  4338:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4339:                        ,$udom,$uname);
                   4340: 
1.455     albertel 4341:         #foreach (keys(%tmp)) {
                   4342:         #    &logthis("key $_ = ".$tmp{$_});
                   4343:         #}
1.294     matthew  4344:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4345:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4346:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4347:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4348:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4349:     }
1.556     albertel 4350:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4351:     my $reply=cput('classlist',
                   4352: 		   {"$uname:$udom" => 
1.515     raeburn  4353: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4354: 		   $cdom,$cnum);
1.81      www      4355:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4356: 	return 'error: '.$reply;
1.652     albertel 4357:     } else {
                   4358: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4359:     }
1.297     matthew  4360:     # Add student role to user
1.83      www      4361:     my $uurl='/'.$cid;
1.81      www      4362:     $uurl=~s/\_/\//g;
                   4363:     if ($usec) {
                   4364: 	$uurl.='/'.$usec;
                   4365:     }
                   4366:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4367: }
                   4368: 
1.556     albertel 4369: sub format_name {
                   4370:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4371:     my $name;
                   4372:     if ($first ne 'lastname') {
                   4373: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4374:     } else {
                   4375: 	if ($lastname=~/\S/) {
                   4376: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4377: 	    $name=~s/\s+,/,/;
                   4378: 	} else {
                   4379: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4380: 	}
                   4381:     }
                   4382:     $name=~s/^\s+//;
                   4383:     $name=~s/\s+$//;
                   4384:     $name=~s/\s+/ /g;
                   4385:     return $name;
                   4386: }
                   4387: 
1.84      www      4388: # ------------------------------------------------- Write to course preferences
                   4389: 
                   4390: sub writecoursepref {
                   4391:     my ($courseid,%prefs)=@_;
                   4392:     $courseid=~s/^\///;
                   4393:     $courseid=~s/\_/\//g;
                   4394:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4395:     my $chome=homeserver($cnum,$cdomain);
                   4396:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4397: 	return 'error: no such course';
                   4398:     }
                   4399:     my $cstring='';
1.191     harris41 4400:     foreach (keys %prefs) {
1.84      www      4401: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4402:     }
1.84      www      4403:     $cstring=~s/\&$//;
                   4404:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4405: }
                   4406: 
                   4407: # ---------------------------------------------------------- Make/modify course
                   4408: 
                   4409: sub createcourse {
1.571     raeburn  4410:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      4411:     $url=&declutter($url);
                   4412:     my $cid='';
1.264     matthew  4413:     unless (&allowed('ccc',$udom)) {
1.84      www      4414:         return 'refused';
                   4415:     }
                   4416: # ------------------------------------------------------------------- Create ID
1.674     www      4417:    my $uname=int(1+rand(9)).
                   4418:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4419:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4420:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4421: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4422:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4423:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4424:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4425:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4426:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4427:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4428:            return 'error: unable to generate unique course-ID';
                   4429:        } 
                   4430:    }
1.264     matthew  4431: # ------------------------------------------------ Check supplied server name
1.620     albertel 4432:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4433:     if (! exists($libserv{$course_server})) {
                   4434:         return 'error:bad server name '.$course_server;
                   4435:     }
1.84      www      4436: # ------------------------------------------------------------- Make the course
                   4437:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4438:                       $course_server);
1.84      www      4439:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4440:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4441:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4442: 	return 'error: no such course';
                   4443:     }
1.271     www      4444: # ----------------------------------------------------------------- Course made
1.516     raeburn  4445: # log existence
                   4446:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  4447:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      4448:     &flushcourselogs();
                   4449: # set toplevel url
1.271     www      4450:     my $topurl=$url;
                   4451:     unless ($nonstandard) {
                   4452: # ------------------------------------------ For standard courses, make top url
                   4453:         my $mapurl=&clutter($url);
1.278     www      4454:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4455:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4456: <map>
                   4457: <resource id="1" type="start"></resource>
                   4458: <resource id="2" src="$mapurl"></resource>
                   4459: <resource id="3" type="finish"></resource>
                   4460: <link index="1" from="1" to="2"></link>
                   4461: <link index="2" from="2" to="3"></link>
                   4462: </map>
                   4463: ENDINITMAP
                   4464:         $topurl=&declutter(
1.638     albertel 4465:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4466:                           );
                   4467:     }
                   4468: # ----------------------------------------------------------- Write preferences
1.84      www      4469:     &writecoursepref($udom.'_'.$uname,
                   4470:                      ('description' => $description,
1.271     www      4471:                       'url'         => $topurl));
1.84      www      4472:     return '/'.$udom.'/'.$uname;
                   4473: }
                   4474: 
1.21      www      4475: # ---------------------------------------------------------- Assign Custom Role
                   4476: 
                   4477: sub assigncustomrole {
1.357     www      4478:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4479:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4480:                        $end,$start,$deleteflag);
1.21      www      4481: }
                   4482: 
                   4483: # ----------------------------------------------------------------- Revoke Role
                   4484: 
                   4485: sub revokerole {
1.357     www      4486:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4487:     my $now=time;
1.357     www      4488:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4489: }
                   4490: 
                   4491: # ---------------------------------------------------------- Revoke Custom Role
                   4492: 
                   4493: sub revokecustomrole {
1.357     www      4494:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4495:     my $now=time;
1.357     www      4496:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4497:            $deleteflag);
1.17      www      4498: }
                   4499: 
1.533     banghart 4500: # ------------------------------------------------------------ Disk usage
1.535     albertel 4501: sub diskusage {
1.533     banghart 4502:     my ($udom,$uname,$directoryRoot)=@_;
                   4503:     $directoryRoot =~ s/\/$//;
1.535     albertel 4504:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4505:     return $listing;
1.512     banghart 4506: }
                   4507: 
1.566     banghart 4508: sub is_locked {
                   4509:     my ($file_name, $domain, $user) = @_;
                   4510:     my @check;
                   4511:     my $is_locked;
                   4512:     push @check, $file_name;
1.613     albertel 4513:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4514: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4515:     my ($tmp)=keys(%locked);
                   4516:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 4517: 
1.566     banghart 4518:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   4519:         $is_locked = 'true';
                   4520:     } else {
                   4521:         $is_locked = 'false';
                   4522:     }
                   4523: }
                   4524: 
1.559     banghart 4525: # ------------------------------------------------------------- Mark as Read Only
                   4526: 
                   4527: sub mark_as_readonly {
                   4528:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4529:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4530:     my ($tmp)=keys(%current_permissions);
                   4531:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4532:     foreach my $file (@{$files}) {
1.561     banghart 4533:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4534:     }
1.613     albertel 4535:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4536:     return;
                   4537: }
                   4538: 
1.572     banghart 4539: # ------------------------------------------------------------Save Selected Files
                   4540: 
                   4541: sub save_selected_files {
                   4542:     my ($user, $path, @files) = @_;
                   4543:     my $filename = $user."savedfiles";
1.573     banghart 4544:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4545:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4546:     foreach my $file (@files) {
1.620     albertel 4547:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4548:     }
                   4549:     foreach my $file (@other_files) {
1.574     banghart 4550:         print (OUT $file."\n");
1.572     banghart 4551:     }
1.574     banghart 4552:     close (OUT);
1.572     banghart 4553:     return 'ok';
                   4554: }
                   4555: 
1.574     banghart 4556: sub clear_selected_files {
                   4557:     my ($user) = @_;
                   4558:     my $filename = $user."savedfiles";
                   4559:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4560:     print (OUT undef);
                   4561:     close (OUT);
                   4562:     return ("ok");    
                   4563: }
                   4564: 
1.572     banghart 4565: sub files_in_path {
                   4566:     my ($user, $path) = @_;
                   4567:     my $filename = $user."savedfiles";
                   4568:     my %return_files;
1.574     banghart 4569:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4570:     while (my $line_in = <IN>) {
1.574     banghart 4571:         chomp ($line_in);
                   4572:         my @paths_and_file = split (m!/!, $line_in);
                   4573:         my $file_part = pop (@paths_and_file);
                   4574:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4575:         $path_part.='/';
                   4576:         my $path_and_file = $path_part.$file_part;
                   4577:         if ($path_part eq $path) {
                   4578:             $return_files{$file_part}= 'selected';
                   4579:         }
                   4580:     }
1.574     banghart 4581:     close (IN);
                   4582:     return (\%return_files);
1.572     banghart 4583: }
                   4584: 
                   4585: # called in portfolio select mode, to show files selected NOT in current directory
                   4586: sub files_not_in_path {
                   4587:     my ($user, $path) = @_;
                   4588:     my $filename = $user."savedfiles";
                   4589:     my @return_files;
                   4590:     my $path_part;
1.574     banghart 4591:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4592:     while (<IN>) {
                   4593:         #ok, I know it's clunky, but I want it to work
                   4594:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4595:         my $file_part = pop (@paths_and_file);
                   4596:         chomp ($file_part);
                   4597:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4598:         $path_part .= '/';
                   4599:         my $path_and_file = $path_part.$file_part;
                   4600:         if ($path_part ne $path) {
1.574     banghart 4601:             push (@return_files, ($path_and_file));
1.572     banghart 4602:         }
                   4603:     }
1.574     banghart 4604:     close (OUT);
                   4605:     return (@return_files);
1.572     banghart 4606: }
                   4607: 
1.561     banghart 4608: #--------------------------------------------------------------Get Marked as Read Only
                   4609: 
1.629     banghart 4610: 
1.561     banghart 4611: sub get_marked_as_readonly {
                   4612:     my ($domain,$user,$what) = @_;
1.613     albertel 4613:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4614:     my ($tmp)=keys(%current_permissions);
                   4615:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563     banghart 4616:     my @readonly_files;
1.629     banghart 4617:     my $cmp1=$what;
                   4618:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.563     banghart 4619:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 4620:         if (ref($value) eq "ARRAY"){
                   4621:             foreach my $stored_what (@{$value}) {
1.629     banghart 4622:                 my $cmp2=$stored_what;
                   4623:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
                   4624:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4625:                     push(@readonly_files, $file_name);
1.563     banghart 4626:                 } elsif (!defined($what)) {
                   4627:                     push(@readonly_files, $file_name);
1.561     banghart 4628:                 }
                   4629:             }
                   4630:         } 
                   4631:     }
                   4632:     return @readonly_files;
                   4633: }
1.577     banghart 4634: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4635: 
1.577     banghart 4636: sub get_marked_as_readonly_hash {
                   4637:     my ($domain,$user,$what) = @_;
1.613     albertel 4638:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4639:     my ($tmp)=keys(%current_permissions);
                   4640:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4641: 
1.577     banghart 4642:     my %readonly_files;
                   4643:     while (my ($file_name,$value) = each(%current_permissions)) {
                   4644:         if (ref($value) eq "ARRAY"){
                   4645:             foreach my $stored_what (@{$value}) {
                   4646:                 if ($stored_what eq $what) {
                   4647:                     $readonly_files{$file_name} = 'locked';
                   4648:                 } elsif (!defined($what)) {
                   4649:                     $readonly_files{$file_name} = 'locked';
                   4650:                 }
                   4651:             }
                   4652:         } 
                   4653:     }
                   4654:     return %readonly_files;
                   4655: }
1.559     banghart 4656: # ------------------------------------------------------------ Unmark as Read Only
                   4657: 
                   4658: sub unmark_as_readonly {
1.629     banghart 4659:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4660:     # for portfolio submissions, $what contains [$symb,$crsid] 
                   4661:     my ($domain,$user,$what,$file_name) = @_;
1.634     albertel 4662:     my $symb_crs = $what;
                   4663:     if (ref($what)) { $symb_crs=join('',@$what); }
1.613     albertel 4664:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4665:     my ($tmp)=keys(%current_permissions);
                   4666:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4667:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.650     albertel 4668:     foreach my $file (@readonly_files) {
                   4669: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4670: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4671:         my @new_locks;
                   4672:         my @del_keys;
                   4673:         if (ref($current_locks) eq "ARRAY"){
                   4674:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4675:                 my $compare=$locker;
                   4676:                 if (ref($locker)) { $compare=join('',@{$locker}) };
1.650     albertel 4677:                 if ($compare ne $symb_crs) {
                   4678:                     push(@new_locks, $locker);
1.563     banghart 4679:                 }
                   4680:             }
1.650     albertel 4681:             if (scalar(@new_locks) > 0) {
1.563     banghart 4682:                 $current_permissions{$file} = \@new_locks;
                   4683:             } else {
                   4684:                 push(@del_keys, $file);
1.613     albertel 4685:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4686:                 delete($current_permissions{$file});
1.563     banghart 4687:             }
                   4688:         }
1.561     banghart 4689:     }
1.613     albertel 4690:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4691:     return;
                   4692: }
1.512     banghart 4693: 
1.17      www      4694: # ------------------------------------------------------------ Directory lister
                   4695: 
                   4696: sub dirlist {
1.253     stredwic 4697:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4698: 
1.18      www      4699:     $uri=~s/^\///;
                   4700:     $uri=~s/\/$//;
1.253     stredwic 4701:     my ($udom, $uname);
                   4702:     (undef,$udom,$uname)=split(/\//,$uri);
                   4703:     if(defined($userdomain)) {
                   4704:         $udom = $userdomain;
                   4705:     }
                   4706:     if(defined($username)) {
                   4707:         $uname = $username;
                   4708:     }
                   4709: 
                   4710:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4711:     if(defined($alternateDirectoryRoot)) {
                   4712:         $dirRoot = $alternateDirectoryRoot;
                   4713:         $dirRoot =~ s/\/$//;
                   4714:     }
                   4715: 
                   4716:     if($udom) {
                   4717:         if($uname) {
1.605     matthew  4718:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4719:                               homeserver($uname,$udom));
1.605     matthew  4720:             my @listing_results;
                   4721:             if ($listing eq 'unknown_cmd') {
                   4722:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4723:                                homeserver($uname,$udom));
                   4724:                 @listing_results = split(/:/,$listing);
                   4725:             } else {
                   4726:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4727:             }
                   4728:             return @listing_results;
1.253     stredwic 4729:         } elsif(!defined($alternateDirectoryRoot)) {
                   4730:             my $tryserver;
                   4731:             my %allusers=();
                   4732:             foreach $tryserver (keys %libserv) {
                   4733:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4734:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4735:                                       $udom, $tryserver);
1.605     matthew  4736:                     my @listing_results;
                   4737:                     if ($listing eq 'unknown_cmd') {
                   4738:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4739:                                        $udom, $tryserver);
                   4740:                         @listing_results = split(/:/,$listing);
                   4741:                     } else {
                   4742:                         @listing_results =
                   4743:                             map { &unescape($_); } split(/:/,$listing);
                   4744:                     }
                   4745:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4746:                         $listing_results[0] ne 'empty'       &&
                   4747:                         $listing_results[0] ne 'con_lost') {
                   4748:                         foreach (@listing_results) {
1.253     stredwic 4749:                             my ($entry,@stat)=split(/&/,$_);
                   4750:                             $allusers{$entry}=1;
                   4751:                         }
                   4752:                     }
1.191     harris41 4753:                 }
1.253     stredwic 4754:             }
                   4755:             my $alluserstr='';
                   4756:             foreach (sort keys %allusers) {
                   4757:                 $alluserstr.=$_.'&user:';
                   4758:             }
                   4759:             $alluserstr=~s/:$//;
                   4760:             return split(/:/,$alluserstr);
                   4761:         } else {
                   4762:             my @emptyResults = ();
                   4763:             push(@emptyResults, 'missing user name');
                   4764:             return split(':',@emptyResults);
                   4765:         }
                   4766:     } elsif(!defined($alternateDirectoryRoot)) {
                   4767:         my $tryserver;
                   4768:         my %alldom=();
                   4769:         foreach $tryserver (keys %libserv) {
                   4770:             $alldom{$hostdom{$tryserver}}=1;
                   4771:         }
                   4772:         my $alldomstr='';
                   4773:         foreach (sort keys %alldom) {
1.397     albertel 4774:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4775:         }
                   4776:         $alldomstr=~s/:$//;
                   4777:         return split(/:/,$alldomstr);       
                   4778:     } else {
                   4779:         my @emptyResults = ();
                   4780:         push(@emptyResults, 'missing domain');
                   4781:         return split(':',@emptyResults);
1.275     stredwic 4782:     }
                   4783: }
                   4784: 
                   4785: # --------------------------------------------- GetFileTimestamp
                   4786: # This function utilizes dirlist and returns the date stamp for
                   4787: # when it was last modified.  It will also return an error of -1
                   4788: # if an error occurs
                   4789: 
1.410     matthew  4790: ##
                   4791: ## FIXME: This subroutine assumes its caller knows something about the
                   4792: ## directory structure of the home server for the student ($root).
                   4793: ## Not a good assumption to make.  Since this is for looking up files
                   4794: ## in user directories, the full path should be constructed by lond, not
                   4795: ## whatever machine we request data from.
                   4796: ##
1.275     stredwic 4797: sub GetFileTimestamp {
                   4798:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4799:     $studentDomain=~s/\W//g;
                   4800:     $studentName=~s/\W//g;
                   4801:     my $subdir=$studentName.'__';
                   4802:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4803:     my $proname="$studentDomain/$subdir/$studentName";
                   4804:     $proname .= '/'.$filename;
1.375     matthew  4805:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4806:                                               $studentName, $root);
1.275     stredwic 4807:     my @stats = split('&', $fileStat);
                   4808:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4809:         # @stats contains first the filename, then the stat output
                   4810:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4811:     } else {
                   4812:         return -1;
1.253     stredwic 4813:     }
1.26      www      4814: }
                   4815: 
1.712     albertel 4816: sub stat_file {
                   4817:     my ($uri) = @_;
1.722     albertel 4818:     $uri = &clutter($uri);
                   4819: 
                   4820:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 4821:     if ($uri =~ m-^/adm/-) {
                   4822: 	$uri=~s-^/adm/wrapper/-/-;
                   4823: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 4824:     }
1.712     albertel 4825:     my ($udom,$uname,$file,$dir);
                   4826:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   4827: 	($udom,$uname,$file) =
                   4828: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   4829: 	$file = 'userfiles/'.$file;
1.740   ! www      4830: 	$dir = &propath($udom,$uname);
1.712     albertel 4831:     }
                   4832:     if ($uri =~ m-^/res/-) {
                   4833: 	($udom,$uname) = 
                   4834: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   4835: 	$file = $uri;
                   4836:     }
                   4837: 
                   4838:     if (!$udom || !$uname || !$file) {
                   4839: 	# unable to handle the uri
                   4840: 	return ();
                   4841:     }
                   4842: 
                   4843:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   4844:     my @stats = split('&', $result);
1.721     banghart 4845:     
1.712     albertel 4846:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   4847: 	shift(@stats); #filename is first
                   4848: 	return @stats;
                   4849:     }
                   4850:     return ();
                   4851: }
                   4852: 
1.26      www      4853: # -------------------------------------------------------- Value of a Condition
                   4854: 
1.713     albertel 4855: # gets the value of a specific preevaluated condition
                   4856: #    stored in the string  $env{user.state.<cid>}
                   4857: # or looks up a condition reference in the bighash and if if hasn't
                   4858: # already been evaluated recurses into docondval to get the value of
                   4859: # the condition, then memoizing it to 
                   4860: #   $env{user.state.<cid>.<condition>}
1.40      www      4861: sub directcondval {
                   4862:     my $number=shift;
1.620     albertel 4863:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4864: 	&Apache::lonuserstate::evalstate();
                   4865:     }
1.713     albertel 4866:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   4867: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   4868:     } elsif ($number =~ /^_/) {
                   4869: 	my $sub_condition;
                   4870: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   4871: 		&GDBM_READER(),0640)) {
                   4872: 	    $sub_condition=$bighash{'conditions'.$number};
                   4873: 	    untie(%bighash);
                   4874: 	}
                   4875: 	my $value = &docondval($sub_condition);
                   4876: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   4877: 	return $value;
                   4878:     }
1.620     albertel 4879:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4880:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4881:     } else {
                   4882:        return 2;
                   4883:     }
                   4884: }
                   4885: 
1.713     albertel 4886: # get the collection of conditions for this resource
1.26      www      4887: sub condval {
                   4888:     my $condidx=shift;
1.54      www      4889:     my $allpathcond='';
1.713     albertel 4890:     foreach my $cond (split(/\|/,$condidx)) {
                   4891: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   4892: 	    $allpathcond.=
                   4893: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   4894: 	}
1.191     harris41 4895:     }
1.54      www      4896:     $allpathcond=~s/\|$//;
1.713     albertel 4897:     return &docondval($allpathcond);
                   4898: }
                   4899: 
                   4900: #evaluates an expression of conditions
                   4901: sub docondval {
                   4902:     my ($allpathcond) = @_;
                   4903:     my $result=0;
                   4904:     if ($env{'request.course.id'}
                   4905: 	&& defined($allpathcond)) {
                   4906: 	my $operand='|';
                   4907: 	my @stack;
                   4908: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   4909: 	    if ($chunk eq '(') {
                   4910: 		push @stack,($operand,$result);
                   4911: 	    } elsif ($chunk eq ')') {
                   4912: 		my $before=pop @stack;
                   4913: 		if (pop @stack eq '&') {
                   4914: 		    $result=$result>$before?$before:$result;
                   4915: 		} else {
                   4916: 		    $result=$result>$before?$result:$before;
                   4917: 		}
                   4918: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   4919: 		$operand=$chunk;
                   4920: 	    } else {
                   4921: 		my $new=directcondval($chunk);
                   4922: 		if ($operand eq '&') {
                   4923: 		    $result=$result>$new?$new:$result;
                   4924: 		} else {
                   4925: 		    $result=$result>$new?$result:$new;
                   4926: 		}
                   4927: 	    }
                   4928: 	}
1.26      www      4929:     }
                   4930:     return $result;
1.421     albertel 4931: }
                   4932: 
                   4933: # ---------------------------------------------------- Devalidate courseresdata
                   4934: 
                   4935: sub devalidatecourseresdata {
                   4936:     my ($coursenum,$coursedomain)=@_;
                   4937:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4938:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4939: }
                   4940: 
1.200     www      4941: # --------------------------------------------------- Course Resourcedata Query
                   4942: 
1.624     albertel 4943: sub get_courseresdata {
                   4944:     my ($coursenum,$coursedomain)=@_;
1.200     www      4945:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4946:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4947:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4948:     my %dumpreply;
1.417     albertel 4949:     unless (defined($cached)) {
1.624     albertel 4950: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4951: 	$result=\%dumpreply;
1.251     albertel 4952: 	my ($tmp) = keys(%dumpreply);
                   4953: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4954: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4955: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4956: 	    return $tmp;
1.416     albertel 4957: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4958: 	    $result=undef;
1.599     albertel 4959: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4960: 	}
                   4961:     }
1.624     albertel 4962:     return $result;
                   4963: }
                   4964: 
1.633     albertel 4965: sub devalidateuserresdata {
                   4966:     my ($uname,$udom)=@_;
                   4967:     my $hashid="$udom:$uname";
                   4968:     &devalidate_cache_new('userres',$hashid);
                   4969: }
                   4970: 
1.624     albertel 4971: sub get_userresdata {
                   4972:     my ($uname,$udom)=@_;
                   4973:     #most student don\'t have any data set, check if there is some data
                   4974:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4975: 
                   4976:     my $hashid="$udom:$uname";
                   4977:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4978:     if (!defined($cached)) {
                   4979: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4980: 	$result=\%resourcedata;
                   4981: 	&do_cache_new('userres',$hashid,$result,600);
                   4982:     }
                   4983:     my ($tmp)=keys(%$result);
                   4984:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4985: 	return $result;
                   4986:     }
                   4987:     #error 2 occurs when the .db doesn't exist
                   4988:     if ($tmp!~/error: 2 /) {
1.672     albertel 4989: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 4990: 		 " Trying to get resource data for ".
                   4991: 		 $uname." at ".$udom.": ".
                   4992: 		 $tmp."</font>");
                   4993:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 4994: 	#&EXT_cache_set($udom,$uname);
                   4995: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 4996: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 4997:     }
                   4998:     return $tmp;
                   4999: }
                   5000: 
                   5001: sub resdata {
                   5002:     my ($name,$domain,$type,@which)=@_;
                   5003:     my $result;
                   5004:     if ($type eq 'course') {
                   5005: 	$result=&get_courseresdata($name,$domain);
                   5006:     } elsif ($type eq 'user') {
                   5007: 	$result=&get_userresdata($name,$domain);
                   5008:     }
                   5009:     if (!ref($result)) { return $result; }    
1.251     albertel 5010:     foreach my $item (@which) {
1.417     albertel 5011: 	if (defined($result->{$item})) {
                   5012: 	    return $result->{$item};
1.251     albertel 5013: 	}
1.250     albertel 5014:     }
1.291     albertel 5015:     return undef;
1.200     www      5016: }
                   5017: 
1.379     matthew  5018: #
                   5019: # EXT resource caching routines
                   5020: #
                   5021: 
                   5022: sub clear_EXT_cache_status {
1.383     albertel 5023:     &delenv('cache.EXT.');
1.379     matthew  5024: }
                   5025: 
                   5026: sub EXT_cache_status {
                   5027:     my ($target_domain,$target_user) = @_;
1.383     albertel 5028:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5029:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5030:         # We know already the user has no data
                   5031:         return 1;
                   5032:     } else {
                   5033:         return 0;
                   5034:     }
                   5035: }
                   5036: 
                   5037: sub EXT_cache_set {
                   5038:     my ($target_domain,$target_user) = @_;
1.383     albertel 5039:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5040:     #&appenv($cachename => time);
1.379     matthew  5041: }
                   5042: 
1.28      www      5043: # --------------------------------------------------------- Value of a Variable
1.58      www      5044: sub EXT {
1.715     albertel 5045: 
1.395     albertel 5046:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5047:     unless ($varname) { return ''; }
1.218     albertel 5048:     #get real user name/domain, courseid and symb
                   5049:     my $courseid;
1.359     albertel 5050:     my $publicuser;
1.427     www      5051:     if ($symbparm) {
                   5052: 	$symbparm=&get_symb_from_alias($symbparm);
                   5053:     }
1.218     albertel 5054:     if (!($uname && $udom)) {
1.360     albertel 5055:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5056: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5057:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5058:     } else {
1.620     albertel 5059: 	$courseid=$env{'request.course.id'};
1.218     albertel 5060:     }
1.48      www      5061:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5062:     my $rest;
1.320     albertel 5063:     if (defined($therest[0])) {
1.48      www      5064:        $rest=join('.',@therest);
                   5065:     } else {
                   5066:        $rest='';
                   5067:     }
1.320     albertel 5068: 
1.57      www      5069:     my $qualifierrest=$qualifier;
                   5070:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5071:     my $spacequalifierrest=$space;
                   5072:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5073:     if ($realm eq 'user') {
1.48      www      5074: # --------------------------------------------------------------- user.resource
                   5075: 	if ($space eq 'resource') {
1.651     albertel 5076: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5077: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5078: 		 &&
                   5079: 		 ($symbparm eq &symbread()) ) {
1.335     albertel 5080: 		return $Apache::lonhomework::history{$qualifierrest};
                   5081: 	    } else {
1.359     albertel 5082: 		my %restored;
1.620     albertel 5083: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5084: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5085: 		} else {
                   5086: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5087: 		}
1.335     albertel 5088: 		return $restored{$qualifierrest};
                   5089: 	    }
1.48      www      5090: # ----------------------------------------------------------------- user.access
                   5091:         } elsif ($space eq 'access') {
1.218     albertel 5092: 	    # FIXME - not supporting calls for a specific user
1.48      www      5093:             return &allowed($qualifier,$rest);
                   5094: # ------------------------------------------ user.preferences, user.environment
                   5095:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5096: 	    if (($uname eq $env{'user.name'}) &&
                   5097: 		($udom eq $env{'user.domain'})) {
                   5098: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5099: 	    } else {
1.359     albertel 5100: 		my %returnhash;
                   5101: 		if (!$publicuser) {
                   5102: 		    %returnhash=&userenvironment($udom,$uname,
                   5103: 						 $qualifierrest);
                   5104: 		}
1.218     albertel 5105: 		return $returnhash{$qualifierrest};
                   5106: 	    }
1.48      www      5107: # ----------------------------------------------------------------- user.course
                   5108:         } elsif ($space eq 'course') {
1.218     albertel 5109: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5110:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5111: # ------------------------------------------------------------------- user.role
                   5112:         } elsif ($space eq 'role') {
1.218     albertel 5113: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5114:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5115:             if ($qualifier eq 'value') {
                   5116: 		return $role;
                   5117:             } elsif ($qualifier eq 'extent') {
                   5118:                 return $where;
                   5119:             }
                   5120: # ----------------------------------------------------------------- user.domain
                   5121:         } elsif ($space eq 'domain') {
1.218     albertel 5122:             return $udom;
1.48      www      5123: # ------------------------------------------------------------------- user.name
                   5124:         } elsif ($space eq 'name') {
1.218     albertel 5125:             return $uname;
1.48      www      5126: # ---------------------------------------------------- Any other user namespace
1.29      www      5127:         } else {
1.359     albertel 5128: 	    my %reply;
                   5129: 	    if (!$publicuser) {
                   5130: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5131: 	    }
                   5132: 	    return $reply{$qualifierrest};
1.48      www      5133:         }
1.236     www      5134:     } elsif ($realm eq 'query') {
                   5135: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5136:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5137: 						[$spacequalifierrest]);
1.620     albertel 5138: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5139:    } elsif ($realm eq 'request') {
1.48      www      5140: # ------------------------------------------------------------- request.browser
                   5141:         if ($space eq 'browser') {
1.430     www      5142: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5143: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5144: 		    return 1;
                   5145: 		} else {
                   5146: 		    return 0;
                   5147: 		}
                   5148: 	    } else {
1.620     albertel 5149: 		return $env{'browser.'.$qualifier};
1.430     www      5150: 	    }
1.57      www      5151: # ------------------------------------------------------------ request.filename
                   5152:         } else {
1.620     albertel 5153:             return $env{'request.'.$spacequalifierrest};
1.29      www      5154:         }
1.28      www      5155:     } elsif ($realm eq 'course') {
1.48      www      5156: # ---------------------------------------------------------- course.description
1.620     albertel 5157:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5158:     } elsif ($realm eq 'resource') {
1.165     www      5159: 
1.620     albertel 5160: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5161: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5162: 	}
1.693     albertel 5163: 
                   5164: 	if ($space eq 'title') {
                   5165: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5166: 	    return &gettitle($symbparm);
                   5167: 	}
                   5168: 	
                   5169: 	if ($space eq 'map') {
                   5170: 	    my ($map) = &decode_symb($symbparm);
                   5171: 	    return &symbread($map);
                   5172: 	}
                   5173: 
                   5174: 	my ($section, $group, @groups);
1.593     albertel 5175: 	my ($courselevelm,$courselevel);
1.539     albertel 5176: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5177: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5178: 
1.218     albertel 5179: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5180: 
1.60      www      5181: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5182: 	    my $symbp=$symbparm;
1.735     albertel 5183: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5184: 
                   5185: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5186: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5187: 
1.620     albertel 5188: 	    if (($env{'user.name'} eq $uname) &&
                   5189: 		($env{'user.domain'} eq $udom)) {
                   5190: 		$section=$env{'request.course.sec'};
1.733     raeburn  5191:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5192:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5193: 	    } else {
1.539     albertel 5194: 		if (! defined($usection)) {
1.551     albertel 5195: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5196: 		} else {
                   5197: 		    $section = $usection;
                   5198: 		}
1.733     raeburn  5199:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5200: 	    }
                   5201: 
                   5202: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5203: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5204: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5205: 
1.593     albertel 5206: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5207: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5208: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5209: 
1.60      www      5210: # ----------------------------------------------------------- first, check user
1.624     albertel 5211: 
                   5212: 	    my $userreply=&resdata($uname,$udom,'user',
                   5213: 				       ($courselevelr,$courselevelm,
                   5214: 					$courselevel));
                   5215: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5216: 
1.594     albertel 5217: # ------------------------------------------------ second, check some of course
1.684     raeburn  5218:             my $coursereply;
1.691     raeburn  5219:             if (@groups > 0) {
                   5220:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5221:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5222:                 if (defined($coursereply)) { return $coursereply; }
                   5223:             }
1.96      www      5224: 
1.684     raeburn  5225: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5226: 				     $env{'course.'.$courseid.'.domain'},
                   5227: 				     'course',
                   5228: 				     ($seclevelr,$seclevelm,$seclevel,
                   5229: 				      $courselevelr));
1.287     albertel 5230: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5231: 
1.60      www      5232: # ------------------------------------------------------ third, check map parms
1.218     albertel 5233: 	    my %parmhash=();
                   5234: 	    my $thisparm='';
                   5235: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5236: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5237: 		    &GDBM_READER(),0640)) {
1.218     albertel 5238: 		$thisparm=$parmhash{$symbparm};
                   5239: 		untie(%parmhash);
                   5240: 	    }
                   5241: 	    if ($thisparm) { return $thisparm; }
                   5242: 	}
1.594     albertel 5243: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5244: 
1.218     albertel 5245: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5246: 	my $filename;
                   5247: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5248: 	if ($symbparm) {
1.409     www      5249: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5250: 	} else {
1.620     albertel 5251: 	    $filename=$env{'request.filename'};
1.282     albertel 5252: 	}
                   5253: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5254: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5255: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5256: 	if (defined($metadata)) { return $metadata; }
1.142     www      5257: 
1.594     albertel 5258: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5259: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5260: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5261: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5262: 				     $env{'course.'.$courseid.'.domain'},
                   5263: 				     'course',
                   5264: 				     ($courselevelm,$courselevel));
1.593     albertel 5265: 	    if (defined($coursereply)) { return $coursereply; }
                   5266: 	}
1.145     www      5267: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5268: 	unless ($space eq '0') {
1.336     albertel 5269: 	    my @parts=split(/_/,$space);
                   5270: 	    my $id=pop(@parts);
                   5271: 	    my $part=join('_',@parts);
                   5272: 	    if ($part eq '') { $part='0'; }
                   5273: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5274: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5275: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5276: 	}
1.395     albertel 5277: 	if ($recurse) { return undef; }
                   5278: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5279: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5280: 
1.48      www      5281: # ---------------------------------------------------- Any other user namespace
                   5282:     } elsif ($realm eq 'environment') {
                   5283: # ----------------------------------------------------------------- environment
1.620     albertel 5284: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5285: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5286: 	} else {
                   5287: 	    my %returnhash=&userenvironment($udom,$uname,
                   5288: 					    $spacequalifierrest);
                   5289: 	    return $returnhash{$spacequalifierrest};
                   5290: 	}
1.28      www      5291:     } elsif ($realm eq 'system') {
1.48      www      5292: # ----------------------------------------------------------------- system.time
                   5293: 	if ($space eq 'time') {
                   5294: 	    return time;
                   5295:         }
1.696     albertel 5296:     } elsif ($realm eq 'server') {
                   5297: # ----------------------------------------------------------------- system.time
                   5298: 	if ($space eq 'name') {
                   5299: 	    return $ENV{'SERVER_NAME'};
                   5300:         }
1.28      www      5301:     }
1.48      www      5302:     return '';
1.61      www      5303: }
                   5304: 
1.691     raeburn  5305: sub check_group_parms {
                   5306:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5307:     my @groupitems = ();
                   5308:     my $resultitem;
                   5309:     my @levels = ($symbparm,$mapparm,$what);
                   5310:     foreach my $group (@{$groups}) {
                   5311:         foreach my $level (@levels) {
                   5312:              my $item = $courseid.'.['.$group.'].'.$level;
                   5313:              push(@groupitems,$item);
                   5314:         }
                   5315:     }
                   5316:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5317:                             $env{'course.'.$courseid.'.domain'},
                   5318:                                      'course',@groupitems);
                   5319:     return $coursereply;
                   5320: }
                   5321: 
                   5322: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5323:     my ($courseid,@groups) = @_;
                   5324:     @groups = sort(@groups);
1.691     raeburn  5325:     return @groups;
                   5326: }
                   5327: 
1.395     albertel 5328: sub packages_tab_default {
                   5329:     my ($uri,$varname)=@_;
                   5330:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5331: 
                   5332:     my (@extension,@specifics,$do_default);
                   5333:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5334: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5335: 	if ($pack_type eq 'default') {
                   5336: 	    $do_default=1;
                   5337: 	} elsif ($pack_type eq 'extension') {
                   5338: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5339: 	} else {
                   5340: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5341: 	}
                   5342:     }
                   5343:     # first look for a package that matches the requested part id
                   5344:     foreach my $package (@specifics) {
                   5345: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5346: 	next if ($pack_part ne $part);
                   5347: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5348: 	    return $packagetab{"$pack_type&$name&default"};
                   5349: 	}
                   5350:     }
                   5351:     # look for any possible matching non extension_ package
                   5352:     foreach my $package (@specifics) {
                   5353: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5354: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5355: 	    return $packagetab{"$pack_type&$name&default"};
                   5356: 	}
1.585     albertel 5357: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5358: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5359: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5360: 	}
                   5361:     }
1.738     albertel 5362:     # look for any posible extension_ match
                   5363:     foreach my $package (@extension) {
                   5364: 	my ($package,$pack_type)=@{$package};
                   5365: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5366: 	    return $packagetab{"$pack_type&$name&default"};
                   5367: 	}
                   5368: 	if (defined($packagetab{$package."&$name&default"})) {
                   5369: 	    return $packagetab{$package."&$name&default"};
                   5370: 	}
                   5371:     }
                   5372:     # look for a global default setting
                   5373:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5374: 	return $packagetab{"default&$name&default"};
                   5375:     }
1.395     albertel 5376:     return undef;
                   5377: }
                   5378: 
1.334     albertel 5379: sub add_prefix_and_part {
                   5380:     my ($prefix,$part)=@_;
                   5381:     my $keyroot;
                   5382:     if (defined($prefix) && $prefix !~ /^__/) {
                   5383: 	# prefix that has a part already
                   5384: 	$keyroot=$prefix;
                   5385:     } elsif (defined($prefix)) {
                   5386: 	# prefix that is missing a part
                   5387: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5388:     } else {
                   5389: 	# no prefix at all
                   5390: 	if (defined($part)) { $keyroot='_'.$part; }
                   5391:     }
                   5392:     return $keyroot;
                   5393: }
                   5394: 
1.71      www      5395: # ---------------------------------------------------------------- Get metadata
                   5396: 
1.599     albertel 5397: my %metaentry;
1.71      www      5398: sub metadata {
1.176     www      5399:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5400:     $uri=&declutter($uri);
1.288     albertel 5401:     # if it is a non metadata possible uri return quickly
1.529     albertel 5402:     if (($uri eq '') || 
                   5403: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5404: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5405:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5406: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5407: 	return undef;
1.288     albertel 5408:     }
1.73      www      5409:     my $filename=$uri;
                   5410:     $uri=~s/\.meta$//;
1.172     www      5411: #
                   5412: # Is the metadata already cached?
1.177     www      5413: # Look at timestamp of caching
1.172     www      5414: # Everything is cached by the main uri, libraries are never directly cached
                   5415: #
1.428     albertel 5416:     if (!defined($liburi)) {
1.599     albertel 5417: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5418: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5419:     }
                   5420:     {
1.172     www      5421: #
                   5422: # Is this a recursive call for a library?
                   5423: #
1.599     albertel 5424: #	if (! exists($metacache{$uri})) {
                   5425: #	    $metacache{$uri}={};
                   5426: #	}
1.171     www      5427:         if ($liburi) {
                   5428: 	    $liburi=&declutter($liburi);
                   5429:             $filename=$liburi;
1.401     bowersj2 5430:         } else {
1.599     albertel 5431: 	    &devalidate_cache_new('meta',$uri);
                   5432: 	    undef(%metaentry);
1.401     bowersj2 5433: 	}
1.140     www      5434:         my %metathesekeys=();
1.73      www      5435:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5436: 	my $metastring;
1.609     banghart 5437: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 5438: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5439: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5440: 	    $metastring=&getfile($file);
1.489     albertel 5441: 	}
1.208     albertel 5442:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5443:         my $token;
1.140     www      5444:         undef %metathesekeys;
1.71      www      5445:         while ($token=$parser->get_token) {
1.339     albertel 5446: 	    if ($token->[0] eq 'S') {
                   5447: 		if (defined($token->[2]->{'package'})) {
1.172     www      5448: #
                   5449: # This is a package - get package info
                   5450: #
1.339     albertel 5451: 		    my $package=$token->[2]->{'package'};
                   5452: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5453: 		    if (defined($token->[2]->{'id'})) { 
                   5454: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5455: 		    }
1.599     albertel 5456: 		    if ($metaentry{':packages'}) {
                   5457: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5458: 		    } else {
1.599     albertel 5459: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5460: 		    }
1.736     albertel 5461: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5462: 			my $part=$keyroot;
                   5463: 			$part=~s/^\_//;
1.736     albertel 5464: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5465: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5466: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5467: 			    # ignore package.tab specified default values
                   5468:                             # here &package_tab_default() will fetch those
                   5469: 			    if ($subp eq 'default') { next; }
1.736     albertel 5470: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5471: 			    my $unikey;
                   5472: 			    if ($pack =~ /_0$/) {
                   5473: 				$unikey='parameter_0_'.$name;
                   5474: 				$part=0;
                   5475: 			    } else {
                   5476: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5477: 			    }
1.339     albertel 5478: 			    if ($subp eq 'display') {
                   5479: 				$value.=' [Part: '.$part.']';
                   5480: 			    }
1.599     albertel 5481: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5482: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5483: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5484: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5485: 			    }
1.599     albertel 5486: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5487: 				$metaentry{':'.$unikey}=
                   5488: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5489: 			    }
1.339     albertel 5490: 			}
                   5491: 		    }
                   5492: 		} else {
1.172     www      5493: #
                   5494: # This is not a package - some other kind of start tag
1.339     albertel 5495: #
                   5496: 		    my $entry=$token->[1];
                   5497: 		    my $unikey;
                   5498: 		    if ($entry eq 'import') {
                   5499: 			$unikey='';
                   5500: 		    } else {
                   5501: 			$unikey=$entry;
                   5502: 		    }
                   5503: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5504: 
                   5505: 		    if (defined($token->[2]->{'id'})) { 
                   5506: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5507: 		    }
1.175     www      5508: 
1.339     albertel 5509: 		    if ($entry eq 'import') {
1.175     www      5510: #
                   5511: # Importing a library here
1.339     albertel 5512: #
                   5513: 			if ($depthcount<20) {
                   5514: 			    my $location=$parser->get_text('/import');
                   5515: 			    my $dir=$filename;
                   5516: 			    $dir=~s|[^/]*$||;
                   5517: 			    $location=&filelocation($dir,$location);
1.736     albertel 5518: 			    my $metadata = 
                   5519: 				&metadata($uri,'keys', $location,$unikey,
                   5520: 					  $depthcount+1);
                   5521: 			    foreach my $meta (split(',',$metadata)) {
                   5522: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   5523: 				$metathesekeys{$meta}=1;
1.339     albertel 5524: 			    }
                   5525: 			}
                   5526: 		    } else { 
                   5527: 			
                   5528: 			if (defined($token->[2]->{'name'})) { 
                   5529: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5530: 			}
                   5531: 			$metathesekeys{$unikey}=1;
1.736     albertel 5532: 			foreach my $param (@{$token->[3]}) {
                   5533: 			    $metaentry{':'.$unikey.'.'.$param} =
                   5534: 				$token->[2]->{$param};
1.339     albertel 5535: 			}
                   5536: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5537: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5538: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5539: 		 # only ws inside the tag, and not in default, so use default
                   5540: 		 # as value
1.599     albertel 5541: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5542: 			} else {
1.321     albertel 5543: 		  # either something interesting inside the tag or default
                   5544:                   # uninteresting
1.599     albertel 5545: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5546: 			}
1.172     www      5547: # end of not-a-package not-a-library import
1.339     albertel 5548: 		    }
1.172     www      5549: # end of not-a-package start tag
1.339     albertel 5550: 		}
1.172     www      5551: # the next is the end of "start tag"
1.339     albertel 5552: 	    }
                   5553: 	}
1.483     albertel 5554: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 5555: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 5556: 	    #no specific packages #how's our extension
                   5557: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5558: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5559: 					 \%metathesekeys);
                   5560: 	}
1.599     albertel 5561: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 5562: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 5563: 		#no specific packages well let's get default then
                   5564: 		if ($key!~/^default&/) { next; }
1.488     albertel 5565: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5566: 					     \%metathesekeys);
                   5567: 	    }
                   5568: 	}
1.338     www      5569: # are there custom rights to evaluate
1.599     albertel 5570: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5571: 
1.338     www      5572:     #
                   5573:     # Importing a rights file here
1.339     albertel 5574:     #
                   5575: 	    unless ($depthcount) {
1.599     albertel 5576: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5577: 		my $dir=$filename;
                   5578: 		$dir=~s|[^/]*$||;
                   5579: 		$location=&filelocation($dir,$location);
1.736     albertel 5580: 		my $rights_metadata =
                   5581: 		    &metadata($uri,'keys',$location,'_rights',
                   5582: 			      $depthcount+1);
                   5583: 		foreach my $rights (split(',',$rights_metadata)) {
                   5584: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   5585: 		    $metathesekeys{$rights}=1;
1.339     albertel 5586: 		}
                   5587: 	    }
                   5588: 	}
1.737     albertel 5589: 	# uniqifiy package listing
                   5590: 	my %seen;
                   5591: 	my @uniq_packages =
                   5592: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   5593: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   5594: 
                   5595: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 5596: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5597: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 5598: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      5599: # this is the end of "was not already recently cached
1.71      www      5600:     }
1.599     albertel 5601:     return $metaentry{':'.$what};
1.261     albertel 5602: }
                   5603: 
1.488     albertel 5604: sub metadata_create_package_def {
1.483     albertel 5605:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5606:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5607:     if ($subp eq 'default') { next; }
                   5608:     
1.599     albertel 5609:     if (defined($metaentry{':packages'})) {
                   5610: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5611:     } else {
1.599     albertel 5612: 	$metaentry{':packages'}=$package;
1.483     albertel 5613:     }
                   5614:     my $value=$packagetab{$key};
                   5615:     my $unikey;
                   5616:     $unikey='parameter_0_'.$name;
1.599     albertel 5617:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5618:     $$metathesekeys{$unikey}=1;
1.599     albertel 5619:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5620: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5621:     }
1.599     albertel 5622:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5623: 	$metaentry{':'.$unikey}=
                   5624: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5625:     }
                   5626: }
                   5627: 
1.261     albertel 5628: sub metadata_generate_part0 {
                   5629:     my ($metadata,$metacache,$uri) = @_;
                   5630:     my %allnames;
1.737     albertel 5631:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 5632: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5633: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5634: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5635: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5636: 	    $allnames{$name}=$part;
                   5637: 	  }
                   5638: 	}
                   5639:     }
                   5640:     foreach my $name (keys(%allnames)) {
                   5641:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5642:       my $key=":parameter_0_$name";
1.261     albertel 5643:       $$metacache{"$key.part"}='0';
                   5644:       $$metacache{"$key.name"}=$name;
1.428     albertel 5645:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5646: 					   $allnames{$name}.'_'.$name.
                   5647: 					   '.type'};
1.428     albertel 5648:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5649: 			     '.display'};
1.644     www      5650:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5651:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5652:       $$metacache{"$key.display"}=$olddis;
                   5653:     }
1.71      www      5654: }
                   5655: 
1.301     www      5656: # ------------------------------------------------- Get the title of a resource
                   5657: 
                   5658: sub gettitle {
                   5659:     my $urlsymb=shift;
                   5660:     my $symb=&symbread($urlsymb);
1.534     albertel 5661:     if ($symb) {
1.620     albertel 5662: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5663: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5664: 	if (defined($cached)) { 
                   5665: 	    return $result;
                   5666: 	}
1.534     albertel 5667: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5668: 	my $title='';
                   5669: 	my %bighash;
1.620     albertel 5670: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5671: 		&GDBM_READER(),0640)) {
                   5672: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5673: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5674: 	    untie %bighash;
                   5675: 	}
                   5676: 	$title=~s/\&colon\;/\:/gs;
                   5677: 	if ($title) {
1.599     albertel 5678: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5679: 	}
                   5680: 	$urlsymb=$url;
                   5681:     }
                   5682:     my $title=&metadata($urlsymb,'title');
                   5683:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5684:     return $title;
1.301     www      5685: }
1.613     albertel 5686: 
1.614     albertel 5687: sub get_slot {
                   5688:     my ($which,$cnum,$cdom)=@_;
                   5689:     if (!$cnum || !$cdom) {
                   5690: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5691: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5692: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5693:     }
1.703     albertel 5694:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   5695:     my %slotinfo;
                   5696:     if (exists($remembered{$key})) {
                   5697: 	$slotinfo{$which} = $remembered{$key};
                   5698:     } else {
                   5699: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5700: 	&Apache::lonhomework::showhash(%slotinfo);
                   5701: 	my ($tmp)=keys(%slotinfo);
                   5702: 	if ($tmp=~/^error:/) { return (); }
                   5703: 	$remembered{$key} = $slotinfo{$which};
                   5704:     }
1.616     albertel 5705:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5706: 	return %{$slotinfo{$which}};
                   5707:     }
                   5708:     return $slotinfo{$which};
1.614     albertel 5709: }
1.31      www      5710: # ------------------------------------------------- Update symbolic store links
                   5711: 
                   5712: sub symblist {
                   5713:     my ($mapname,%newhash)=@_;
1.438     www      5714:     $mapname=&deversion(&declutter($mapname));
1.31      www      5715:     my %hash;
1.620     albertel 5716:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5717:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5718:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 5719: 	    foreach my $url (keys %newhash) {
                   5720: 		next if ($url eq 'last_known'
                   5721: 			 && $env{'form.no_update_last_known'});
                   5722: 		$hash{declutter($url)}=&encode_symb($mapname,
                   5723: 						    $newhash{$url}->[1],
                   5724: 						    $newhash{$url}->[0]);
1.191     harris41 5725:             }
1.31      www      5726:             if (untie(%hash)) {
                   5727: 		return 'ok';
                   5728:             }
                   5729:         }
                   5730:     }
                   5731:     return 'error';
1.212     www      5732: }
                   5733: 
                   5734: # --------------------------------------------------------------- Verify a symb
                   5735: 
                   5736: sub symbverify {
1.510     www      5737:     my ($symb,$thisurl)=@_;
                   5738:     my $thisfn=$thisurl;
                   5739: # wrapper not part of symbs
                   5740:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 5741:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      5742:     $thisfn=&declutter($thisfn);
1.215     www      5743: # direct jump to resource in page or to a sequence - will construct own symbs
                   5744:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5745: # check URL part
1.409     www      5746:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5747: 
1.431     www      5748:     unless ($url eq $thisfn) { return 0; }
1.213     www      5749: 
1.216     www      5750:     $symb=&symbclean($symb);
1.510     www      5751:     $thisurl=&deversion($thisurl);
1.439     www      5752:     $thisfn=&deversion($thisfn);
1.213     www      5753: 
                   5754:     my %bighash;
                   5755:     my $okay=0;
1.431     www      5756: 
1.620     albertel 5757:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5758:                             &GDBM_READER(),0640)) {
1.510     www      5759:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5760:         unless ($ids) { 
1.510     www      5761:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5762:         }
                   5763:         if ($ids) {
                   5764: # ------------------------------------------------------------------- Has ID(s)
                   5765: 	    foreach (split(/\,/,$ids)) {
1.644     www      5766: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5767:                if (
                   5768:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5769:    eq $symb) { 
1.620     albertel 5770: 		   if (($env{'request.role.adv'}) ||
                   5771: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5772: 		       $okay=1; 
                   5773: 		   }
                   5774: 	       }
1.216     www      5775: 	   }
                   5776:         }
1.213     www      5777: 	untie(%bighash);
                   5778:     }
                   5779:     return $okay;
1.31      www      5780: }
                   5781: 
1.210     www      5782: # --------------------------------------------------------------- Clean-up symb
                   5783: 
                   5784: sub symbclean {
                   5785:     my $symb=shift;
1.568     albertel 5786:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5787: # remove version from map
                   5788:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      5789: 
1.210     www      5790: # remove version from URL
                   5791:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      5792: 
1.507     www      5793: # remove wrapper
                   5794: 
1.510     www      5795:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 5796:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      5797:     return $symb;
1.409     www      5798: }
                   5799: 
                   5800: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 5801: 
                   5802: sub encode_symb {
                   5803:     my ($map,$resid,$url)=@_;
                   5804:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   5805: }
1.409     www      5806: 
                   5807: sub decode_symb {
1.568     albertel 5808:     my $symb=shift;
                   5809:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   5810:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      5811:     return (&fixversion($map),$resid,&fixversion($url));
                   5812: }
                   5813: 
                   5814: sub fixversion {
                   5815:     my $fn=shift;
1.609     banghart 5816:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      5817:     my %bighash;
                   5818:     my $uri=&clutter($fn);
1.620     albertel 5819:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      5820: # is this cached?
1.599     albertel 5821:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      5822:     if (defined($cached)) { return $result; }
                   5823: # unfortunately not cached, or expired
1.620     albertel 5824:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      5825: 	    &GDBM_READER(),0640)) {
                   5826:  	if ($bighash{'version_'.$uri}) {
                   5827:  	    my $version=$bighash{'version_'.$uri};
1.444     www      5828:  	    unless (($version eq 'mostrecent') || 
                   5829: 		    ($version==&getversion($uri))) {
1.440     www      5830:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   5831:  	    }
                   5832:  	}
                   5833:  	untie %bighash;
1.413     www      5834:     }
1.599     albertel 5835:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      5836: }
                   5837: 
                   5838: sub deversion {
                   5839:     my $url=shift;
                   5840:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   5841:     return $url;
1.210     www      5842: }
                   5843: 
1.31      www      5844: # ------------------------------------------------------ Return symb list entry
                   5845: 
                   5846: sub symbread {
1.249     www      5847:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 5848:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 5849:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      5850: # no filename provided? try from environment
1.44      www      5851:     unless ($thisfn) {
1.620     albertel 5852:         if ($env{'request.symb'}) {
                   5853: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 5854: 	}
1.620     albertel 5855: 	$thisfn=$env{'request.filename'};
1.44      www      5856:     }
1.569     albertel 5857:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      5858: # is that filename actually a symb? Verify, clean, and return
                   5859:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 5860: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 5861: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 5862: 	}
1.242     www      5863:     }
1.44      www      5864:     $thisfn=declutter($thisfn);
1.31      www      5865:     my %hash;
1.37      www      5866:     my %bighash;
                   5867:     my $syval='';
1.620     albertel 5868:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  5869:         my $targetfn = $thisfn;
1.609     banghart 5870:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  5871:             $targetfn = 'adm/wrapper/'.$thisfn;
                   5872:         }
1.687     albertel 5873: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   5874: 	    $targetfn=$1;
                   5875: 	}
1.620     albertel 5876:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5877:                       &GDBM_READER(),0640)) {
1.481     raeburn  5878: 	    $syval=$hash{$targetfn};
1.37      www      5879:             untie(%hash);
                   5880:         }
                   5881: # ---------------------------------------------------------- There was an entry
                   5882:         if ($syval) {
1.601     albertel 5883: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 5884: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 5885: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 5886: 		    #return $env{$cache_str}='';
1.601     albertel 5887: 		#}    
                   5888: 		#$syval.=$1;
                   5889: 	    #}
1.37      www      5890:         } else {
                   5891: # ------------------------------------------------------- Was not in symb table
1.620     albertel 5892:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5893:                             &GDBM_READER(),0640)) {
1.37      www      5894: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      5895:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      5896:               unless ($ids) { 
                   5897:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      5898:               }
                   5899:               unless ($ids) {
                   5900: # alias?
                   5901: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      5902:               }
1.37      www      5903:               if ($ids) {
                   5904: # ------------------------------------------------------------------- Has ID(s)
                   5905:                  my @possibilities=split(/\,/,$ids);
1.39      www      5906:                  if ($#possibilities==0) {
                   5907: # ----------------------------------------------- There is only one possibility
1.37      www      5908: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 5909: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5910: 						    $resid,$thisfn);
1.249     www      5911:                  } elsif (!$donotrecurse) {
1.39      www      5912: # ------------------------------------------ There is more than one possibility
                   5913:                      my $realpossible=0;
1.191     harris41 5914:                      foreach (@possibilities) {
1.39      www      5915: 			 my $file=$bighash{'src_'.$_};
                   5916:                          if (&allowed('bre',$file)) {
                   5917:          		    my ($mapid,$resid)=split(/\./,$_);
                   5918:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   5919: 				$realpossible++;
1.626     albertel 5920:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5921: 						    $resid,$thisfn);
1.39      www      5922:                             }
                   5923: 			 }
1.191     harris41 5924:                      }
1.39      www      5925: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      5926:                  } else {
                   5927:                      $syval='';
1.37      www      5928:                  }
                   5929: 	      }
                   5930:               untie(%bighash)
1.481     raeburn  5931:            }
1.31      www      5932:         }
1.62      www      5933:         if ($syval) {
1.620     albertel 5934: 	    return $env{$cache_str}=$syval;
1.62      www      5935:         }
1.31      www      5936:     }
1.44      www      5937:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 5938:     return $env{$cache_str}='';
1.31      www      5939: }
                   5940: 
                   5941: # ---------------------------------------------------------- Return random seed
                   5942: 
1.32      www      5943: sub numval {
                   5944:     my $txt=shift;
                   5945:     $txt=~tr/A-J/0-9/;
                   5946:     $txt=~tr/a-j/0-9/;
                   5947:     $txt=~tr/K-T/0-9/;
                   5948:     $txt=~tr/k-t/0-9/;
                   5949:     $txt=~tr/U-Z/0-5/;
                   5950:     $txt=~tr/u-z/0-5/;
                   5951:     $txt=~s/\D//g;
1.564     albertel 5952:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      5953:     return int($txt);
1.368     albertel 5954: }
                   5955: 
1.484     albertel 5956: sub numval2 {
                   5957:     my $txt=shift;
                   5958:     $txt=~tr/A-J/0-9/;
                   5959:     $txt=~tr/a-j/0-9/;
                   5960:     $txt=~tr/K-T/0-9/;
                   5961:     $txt=~tr/k-t/0-9/;
                   5962:     $txt=~tr/U-Z/0-5/;
                   5963:     $txt=~tr/u-z/0-5/;
                   5964:     $txt=~s/\D//g;
                   5965:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5966:     my $total;
                   5967:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5968:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5969:     return int($total);
                   5970: }
                   5971: 
1.575     albertel 5972: sub numval3 {
                   5973:     use integer;
                   5974:     my $txt=shift;
                   5975:     $txt=~tr/A-J/0-9/;
                   5976:     $txt=~tr/a-j/0-9/;
                   5977:     $txt=~tr/K-T/0-9/;
                   5978:     $txt=~tr/k-t/0-9/;
                   5979:     $txt=~tr/U-Z/0-5/;
                   5980:     $txt=~tr/u-z/0-5/;
                   5981:     $txt=~s/\D//g;
                   5982:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5983:     my $total;
                   5984:     foreach my $val (@txts) { $total+=$val; }
                   5985:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5986:     return $total;
                   5987: }
                   5988: 
1.675     albertel 5989: sub digest {
                   5990:     my ($data)=@_;
                   5991:     my $digest=&Digest::MD5::md5($data);
                   5992:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   5993:     my ($e,$f);
                   5994:     {
                   5995:         use integer;
                   5996:         $e=($a+$b);
                   5997:         $f=($c+$d);
                   5998:         if ($_64bit) {
                   5999:             $e=(($e<<32)>>32);
                   6000:             $f=(($f<<32)>>32);
                   6001:         }
                   6002:     }
                   6003:     if (wantarray) {
                   6004: 	return ($e,$f);
                   6005:     } else {
                   6006: 	my $g;
                   6007: 	{
                   6008: 	    use integer;
                   6009: 	    $g=($e+$f);
                   6010: 	    if ($_64bit) {
                   6011: 		$g=(($g<<32)>>32);
                   6012: 	    }
                   6013: 	}
                   6014: 	return $g;
                   6015:     }
                   6016: }
                   6017: 
1.368     albertel 6018: sub latest_rnd_algorithm_id {
1.675     albertel 6019:     return '64bit5';
1.366     albertel 6020: }
1.32      www      6021: 
1.503     albertel 6022: sub get_rand_alg {
                   6023:     my ($courseid)=@_;
                   6024:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6025:     if ($courseid) {
1.620     albertel 6026: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6027:     }
                   6028:     return &latest_rnd_algorithm_id();
                   6029: }
                   6030: 
1.562     albertel 6031: sub validCODE {
                   6032:     my ($CODE)=@_;
                   6033:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6034:     return 0;
                   6035: }
                   6036: 
1.491     albertel 6037: sub getCODE {
1.620     albertel 6038:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6039:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6040: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6041: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6042: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6043:     }
                   6044:     return undef;
                   6045: }
                   6046: 
1.31      www      6047: sub rndseed {
1.155     albertel 6048:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6049: 
                   6050:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6051:     if (!$symb) {
1.366     albertel 6052: 	unless ($symb=$wsymb) { return time; }
                   6053:     }
                   6054:     if (!$courseid) { $courseid=$wcourseid; }
                   6055:     if (!$domain) { $domain=$wdomain; }
                   6056:     if (!$username) { $username=$wusername }
1.503     albertel 6057:     my $which=&get_rand_alg();
1.491     albertel 6058:     if (defined(&getCODE())) {
1.675     albertel 6059: 	if ($which eq '64bit5') {
                   6060: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6061: 	} elsif ($which eq '64bit4') {
1.575     albertel 6062: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6063: 	} else {
                   6064: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6065: 	}
1.675     albertel 6066:     } elsif ($which eq '64bit5') {
                   6067: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6068:     } elsif ($which eq '64bit4') {
                   6069: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6070:     } elsif ($which eq '64bit3') {
                   6071: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6072:     } elsif ($which eq '64bit2') {
                   6073: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6074:     } elsif ($which eq '64bit') {
                   6075: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6076:     }
                   6077:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6078: }
                   6079: 
                   6080: sub rndseed_32bit {
                   6081:     my ($symb,$courseid,$domain,$username)=@_;
                   6082:     {
                   6083: 	use integer;
                   6084: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6085: 	my $symbseed=numval($symb) << 22;
                   6086: 	my $namechck=unpack("%32C*",$username) << 17;
                   6087: 	my $nameseed=numval($username) << 12;
                   6088: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6089: 	my $courseseed=unpack("%32C*",$courseid);
                   6090: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6091: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6092: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6093: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6094: 	return $num;
                   6095:     }
                   6096: }
                   6097: 
                   6098: sub rndseed_64bit {
                   6099:     my ($symb,$courseid,$domain,$username)=@_;
                   6100:     {
                   6101: 	use integer;
                   6102: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6103: 	my $symbseed=numval($symb) << 10;
                   6104: 	my $namechck=unpack("%32S*",$username);
                   6105: 	
                   6106: 	my $nameseed=numval($username) << 21;
                   6107: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6108: 	my $courseseed=unpack("%32S*",$courseid);
                   6109: 	
                   6110: 	my $num1=$symbchck+$symbseed+$namechck;
                   6111: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6112: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6113: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6114: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6115: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6116: 	return "$num1,$num2";
1.155     albertel 6117:     }
1.366     albertel 6118: }
                   6119: 
1.443     albertel 6120: sub rndseed_64bit2 {
                   6121:     my ($symb,$courseid,$domain,$username)=@_;
                   6122:     {
                   6123: 	use integer;
                   6124: 	# strings need to be an even # of cahracters long, it it is odd the
                   6125:         # last characters gets thrown away
                   6126: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6127: 	my $symbseed=numval($symb) << 10;
                   6128: 	my $namechck=unpack("%32S*",$username.' ');
                   6129: 	
                   6130: 	my $nameseed=numval($username) << 21;
1.501     albertel 6131: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6132: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6133: 	
                   6134: 	my $num1=$symbchck+$symbseed+$namechck;
                   6135: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6136: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6137: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6138: 	return "$num1,$num2";
                   6139:     }
                   6140: }
                   6141: 
                   6142: sub rndseed_64bit3 {
                   6143:     my ($symb,$courseid,$domain,$username)=@_;
                   6144:     {
                   6145: 	use integer;
                   6146: 	# strings need to be an even # of cahracters long, it it is odd the
                   6147:         # last characters gets thrown away
                   6148: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6149: 	my $symbseed=numval2($symb) << 10;
                   6150: 	my $namechck=unpack("%32S*",$username.' ');
                   6151: 	
                   6152: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6153: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6154: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6155: 	
                   6156: 	my $num1=$symbchck+$symbseed+$namechck;
                   6157: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6158: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6159: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6160: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6161: 	
1.503     albertel 6162: 	return "$num1:$num2";
1.443     albertel 6163:     }
                   6164: }
                   6165: 
1.575     albertel 6166: sub rndseed_64bit4 {
                   6167:     my ($symb,$courseid,$domain,$username)=@_;
                   6168:     {
                   6169: 	use integer;
                   6170: 	# strings need to be an even # of cahracters long, it it is odd the
                   6171:         # last characters gets thrown away
                   6172: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6173: 	my $symbseed=numval3($symb) << 10;
                   6174: 	my $namechck=unpack("%32S*",$username.' ');
                   6175: 	
                   6176: 	my $nameseed=numval3($username) << 21;
                   6177: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6178: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6179: 	
                   6180: 	my $num1=$symbchck+$symbseed+$namechck;
                   6181: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6182: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6183: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6184: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6185: 	
                   6186: 	return "$num1:$num2";
                   6187:     }
                   6188: }
                   6189: 
1.675     albertel 6190: sub rndseed_64bit5 {
                   6191:     my ($symb,$courseid,$domain,$username)=@_;
                   6192:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6193:     return "$num1:$num2";
                   6194: }
                   6195: 
1.366     albertel 6196: sub rndseed_CODE_64bit {
                   6197:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6198:     {
1.366     albertel 6199: 	use integer;
1.443     albertel 6200: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6201: 	my $symbseed=numval2($symb);
1.491     albertel 6202: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6203: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6204: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6205: 	my $num1=$symbseed+$CODEchck;
                   6206: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6207: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6208: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6209: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6210: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6211: 	return "$num1:$num2";
1.366     albertel 6212:     }
                   6213: }
                   6214: 
1.575     albertel 6215: sub rndseed_CODE_64bit4 {
                   6216:     my ($symb,$courseid,$domain,$username)=@_;
                   6217:     {
                   6218: 	use integer;
                   6219: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6220: 	my $symbseed=numval3($symb);
                   6221: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6222: 	my $CODEseed=numval3(&getCODE());
                   6223: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6224: 	my $num1=$symbseed+$CODEchck;
                   6225: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6226: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6227: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6228: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6229: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6230: 	return "$num1:$num2";
                   6231:     }
                   6232: }
                   6233: 
1.675     albertel 6234: sub rndseed_CODE_64bit5 {
                   6235:     my ($symb,$courseid,$domain,$username)=@_;
                   6236:     my $code = &getCODE();
                   6237:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6238:     return "$num1:$num2";
                   6239: }
                   6240: 
1.366     albertel 6241: sub setup_random_from_rndseed {
                   6242:     my ($rndseed)=@_;
1.503     albertel 6243:     if ($rndseed =~/([,:])/) {
                   6244: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6245: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6246:     } else {
                   6247: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6248:     }
1.36      albertel 6249: }
                   6250: 
1.474     albertel 6251: sub latest_receipt_algorithm_id {
                   6252:     return 'receipt2';
                   6253: }
                   6254: 
1.480     www      6255: sub recunique {
                   6256:     my $fucourseid=shift;
                   6257:     my $unique;
1.620     albertel 6258:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6259: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6260:     } else {
                   6261: 	$unique=$perlvar{'lonReceipt'};
                   6262:     }
                   6263:     return unpack("%32C*",$unique);
                   6264: }
                   6265: 
                   6266: sub recprefix {
                   6267:     my $fucourseid=shift;
                   6268:     my $prefix;
1.620     albertel 6269:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6270: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6271:     } else {
                   6272: 	$prefix=$perlvar{'lonHostID'};
                   6273:     }
                   6274:     return unpack("%32C*",$prefix);
                   6275: }
                   6276: 
1.76      www      6277: sub ireceipt {
1.474     albertel 6278:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6279:     my $cuname=unpack("%32C*",$funame);
                   6280:     my $cudom=unpack("%32C*",$fudom);
                   6281:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6282:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6283:     my $cunique=&recunique($fucourseid);
1.474     albertel 6284:     my $cpart=unpack("%32S*",$part);
1.480     www      6285:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6286:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6287: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6288: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6289: 			       " and ".($cpart%$cudom));
                   6290: 			       
                   6291: 	$return.= ($cunique%$cuname+
                   6292: 		   $cunique%$cudom+
                   6293: 		   $cusymb%$cuname+
                   6294: 		   $cusymb%$cudom+
                   6295: 		   $cucourseid%$cuname+
                   6296: 		   $cucourseid%$cudom+
                   6297: 		   $cpart%$cuname+
                   6298: 		   $cpart%$cudom);
                   6299:     } else {
                   6300: 	$return.= ($cunique%$cuname+
                   6301: 		   $cunique%$cudom+
                   6302: 		   $cusymb%$cuname+
                   6303: 		   $cusymb%$cudom+
                   6304: 		   $cucourseid%$cuname+
                   6305: 		   $cucourseid%$cudom);
                   6306:     }
                   6307:     return $return;
1.76      www      6308: }
                   6309: 
                   6310: sub receipt {
1.474     albertel 6311:     my ($part)=@_;
                   6312:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6313:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6314: }
1.260     ng       6315: 
1.36      albertel 6316: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6317: # returns either the contents of the file or 
                   6318: # -1 if the file doesn't exist
1.481     raeburn  6319: #
                   6320: # if the target is a file that was uploaded via DOCS, 
                   6321: # a check will be made to see if a current copy exists on the local server,
                   6322: # if it does this will be served, otherwise a copy will be retrieved from
                   6323: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6324: # the local server.   
1.472     albertel 6325: 
1.36      albertel 6326: sub getfile {
1.538     albertel 6327:     my ($file) = @_;
1.609     banghart 6328:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6329:     &repcopy($file);
                   6330:     return &readfile($file);
                   6331: }
                   6332: 
                   6333: sub repcopy_userfile {
                   6334:     my ($file)=@_;
1.609     banghart 6335:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6336:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6337:     my ($cdom,$cnum,$filename) = 
                   6338: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6339:     my ($info,$rtncode);
                   6340:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6341:     if (-e "$file") {
                   6342: 	my @fileinfo = stat($file);
                   6343: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6344: 	if ($lwpresp ne 'ok') {
                   6345: 	    if ($rtncode eq '404') {
1.538     albertel 6346: 		unlink($file);
1.482     albertel 6347: 	    }
1.517     albertel 6348: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6349: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6350: 	    #my $response=$ua->request($request);
                   6351: 	    #if ($response->is_success()) {
                   6352: 	#	return $response->content;
                   6353: 	#    } else {
                   6354: 	#	return -1;
                   6355: 	#    }
1.482     albertel 6356: 	    return -1;
                   6357: 	}
                   6358: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6359: 	    return 'ok';
1.482     albertel 6360: 	}
                   6361: 	$info = '';
1.538     albertel 6362: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6363: 	if ($lwpresp ne 'ok') {
                   6364: 	    return -1;
                   6365: 	}
                   6366:     } else {
1.538     albertel 6367: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6368: 	if ($lwpresp ne 'ok') {
1.517     albertel 6369: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6370: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6371: 	    my $response=$ua->request($request);
                   6372: 	    if ($response->is_success()) {
1.538     albertel 6373: 		$info=$response->content;
1.517     albertel 6374: 	    } else {
                   6375: 		return -1;
                   6376: 	    }
1.482     albertel 6377: 	}
                   6378: 	my @parts = ($cdom,$cnum); 
                   6379: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6380: 	    push @parts, split(/\//,$1);
1.518     albertel 6381: 	}
1.538     albertel 6382: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6383: 	foreach my $part (@parts) {
                   6384: 	    $path .= '/'.$part;
                   6385: 	    if (!-e $path) {
                   6386: 		mkdir($path,0770);
                   6387: 	    }
                   6388: 	}
                   6389:     }
1.538     albertel 6390:     open(FILE,">$file");
1.482     albertel 6391:     print FILE $info;
                   6392:     close(FILE);
1.607     raeburn  6393:     return 'ok';
1.481     raeburn  6394: }
                   6395: 
1.517     albertel 6396: sub tokenwrapper {
                   6397:     my $uri=shift;
1.552     albertel 6398:     $uri=~s|^http\://([^/]+)||;
                   6399:     $uri=~s|^/||;
1.620     albertel 6400:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6401:     my $token=$1;
1.552     albertel 6402:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6403:     if ($udom && $uname && $file) {
                   6404: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6405:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6406:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6407:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6408:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6409:     } else {
                   6410:         return '/adm/notfound.html';
                   6411:     }
                   6412: }
                   6413: 
1.481     raeburn  6414: sub getuploaded {
                   6415:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6416:     $uri=~s/^\///;
                   6417:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6418:     my $ua=new LWP::UserAgent;
                   6419:     my $request=new HTTP::Request($reqtype,$uri);
                   6420:     my $response=$ua->request($request);
                   6421:     $$rtncode = $response->code;
1.482     albertel 6422:     if (! $response->is_success()) {
                   6423: 	return 'failed';
                   6424:     }      
                   6425:     if ($reqtype eq 'HEAD') {
1.486     www      6426: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6427:     } elsif ($reqtype eq 'GET') {
                   6428: 	$$info = $response->content;
1.472     albertel 6429:     }
1.482     albertel 6430:     return 'ok';
1.36      albertel 6431: }
                   6432: 
1.481     raeburn  6433: sub readfile {
                   6434:     my $file = shift;
                   6435:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6436:     my $fh;
                   6437:     open($fh,"<$file");
                   6438:     my $a='';
                   6439:     while (<$fh>) { $a .=$_; }
                   6440:     return $a;
                   6441: }
                   6442: 
1.36      albertel 6443: sub filelocation {
1.590     banghart 6444:     my ($dir,$file) = @_;
                   6445:     my $location;
                   6446:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6447: 
                   6448:     if ($file =~ m-^/adm/-) {
                   6449: 	$file=~s-^/adm/wrapper/-/-;
                   6450: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6451:     }
1.590     banghart 6452:     if ($file=~m:^/~:) { # is a contruction space reference
                   6453:         $location = $file;
                   6454:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6455:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6456: 	# is a correct contruction space reference
                   6457:         $location = $file;
1.609     banghart 6458:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6459:         my ($udom,$uname,$filename)=
1.609     banghart 6460:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6461:         my $home=&homeserver($uname,$udom);
                   6462:         my $is_me=0;
                   6463:         my @ids=&current_machine_ids();
                   6464:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6465:         if ($is_me) {
1.740   ! www      6466:   	    $location=&propath($udom,$uname).
1.590     banghart 6467:   	      '/userfiles/'.$filename;
                   6468:         } else {
                   6469:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6470:   	      $udom.'/'.$uname.'/'.$filename;
                   6471:         }
                   6472:     } else {
                   6473:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6474:         $file=~s:^/res/:/:;
                   6475:         if ( !( $file =~ m:^/:) ) {
                   6476:             $location = $dir. '/'.$file;
                   6477:         } else {
                   6478:             $location = '/home/httpd/html/res'.$file;
                   6479:         }
1.59      albertel 6480:     }
1.590     banghart 6481:     $location=~s://+:/:g; # remove duplicate /
                   6482:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6483:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6484:     return $location;
1.46      www      6485: }
1.36      albertel 6486: 
1.46      www      6487: sub hreflocation {
                   6488:     my ($dir,$file)=@_;
1.460     albertel 6489:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6490: 	$file=filelocation($dir,$file);
1.700     albertel 6491:     } elsif ($file=~m-^/adm/-) {
                   6492: 	$file=~s-^/adm/wrapper/-/-;
                   6493: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6494:     }
                   6495:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6496: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6497:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6498: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6499:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6500: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6501: 	    -/uploaded/$1/$2/-x;
1.46      www      6502:     }
1.462     albertel 6503:     return $file;
1.465     albertel 6504: }
                   6505: 
                   6506: sub current_machine_domains {
                   6507:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6508:     my @domains;
                   6509:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6510: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6511: 	if ($hostname eq $name) {
                   6512: 	    push(@domains,$hostdom{$id});
                   6513: 	}
                   6514:     }
                   6515:     return @domains;
                   6516: }
                   6517: 
                   6518: sub current_machine_ids {
                   6519:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6520:     my @ids;
                   6521:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6522: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6523: 	if ($hostname eq $name) {
                   6524: 	    push(@ids,$id);
                   6525: 	}
                   6526:     }
                   6527:     return @ids;
1.31      www      6528: }
                   6529: 
                   6530: # ------------------------------------------------------------- Declutters URLs
                   6531: 
                   6532: sub declutter {
                   6533:     my $thisfn=shift;
1.569     albertel 6534:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6535:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6536:     $thisfn=~s/^\///;
1.697     albertel 6537:     $thisfn=~s|^adm/wrapper/||;
                   6538:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      6539:     $thisfn=~s/^res\///;
1.235     www      6540:     $thisfn=~s/\?.+$//;
1.268     www      6541:     return $thisfn;
                   6542: }
                   6543: 
                   6544: # ------------------------------------------------------------- Clutter up URLs
                   6545: 
                   6546: sub clutter {
                   6547:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6548:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6549:        $thisfn='/res'.$thisfn; 
                   6550:     }
1.694     albertel 6551:     if ($thisfn !~m|/adm|) {
1.695     albertel 6552: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 6553: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 6554: 	} else {
                   6555: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   6556: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 6557: 	    if ($embstyle eq 'ssi'
                   6558: 		|| ($embstyle eq 'hdn')
                   6559: 		|| ($embstyle eq 'rat')
                   6560: 		|| ($embstyle eq 'prv')
                   6561: 		|| ($embstyle eq 'ign')) {
                   6562: 		#do nothing with these
                   6563: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 6564: 		|| ($embstyle eq 'emb')
                   6565: 		|| ($embstyle eq 'wrp')) {
                   6566: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 6567: 	    } elsif ($embstyle eq 'unk'
                   6568: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 6569: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 6570: 	    } else {
1.718     www      6571: #		&logthis("Got a blank emb style");
1.695     albertel 6572: 	    }
1.694     albertel 6573: 	}
                   6574:     }
1.31      www      6575:     return $thisfn;
1.12      www      6576: }
                   6577: 
1.557     albertel 6578: sub freeze_escape {
                   6579:     my ($value)=@_;
                   6580:     if (ref($value)) {
                   6581: 	$value=&nfreeze($value);
                   6582: 	return '__FROZEN__'.&escape($value);
                   6583:     }
                   6584:     return &escape($value);
                   6585: }
                   6586: 
1.11      www      6587: 
1.557     albertel 6588: sub thaw_unescape {
                   6589:     my ($value)=@_;
                   6590:     if ($value =~ /^__FROZEN__/) {
                   6591: 	substr($value,0,10,undef);
                   6592: 	$value=&unescape($value);
                   6593: 	return &thaw($value);
                   6594:     }
                   6595:     return &unescape($value);
                   6596: }
                   6597: 
1.436     albertel 6598: sub correct_line_ends {
                   6599:     my ($result)=@_;
                   6600:     $$result =~s/\r\n/\n/mg;
                   6601:     $$result =~s/\r/\n/mg;
1.415     albertel 6602: }
1.1       albertel 6603: # ================================================================ Main Program
                   6604: 
1.184     www      6605: sub goodbye {
1.204     albertel 6606:    &logthis("Starting Shut down");
1.443     albertel 6607: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6608:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6609: #converted
1.599     albertel 6610: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6611:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6612: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6613: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6614: #1.1 only
1.599     albertel 6615: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6616: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6617: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6618: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6619:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6620:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6621:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6622:    &flushcourselogs();
                   6623:    &logthis("Shutting down");
                   6624: }
                   6625: 
1.179     www      6626: BEGIN {
1.228     harris41 6627: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6628:     unless ($readit) {
1.217     harris41 6629: {
1.581     matthew  6630:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6631:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6632: 
                   6633:     while (my $configline=<$config>) {
1.484     albertel 6634:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6635: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6636:            chomp($varvalue);
1.1       albertel 6637:            $perlvar{$varname}=$varvalue;
                   6638:         }
                   6639:     }
1.448     albertel 6640:     close($config);
1.1       albertel 6641: }
1.227     harris41 6642: {
1.448     albertel 6643:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6644: 
                   6645:     while (my $configline=<$config>) {
                   6646:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6647: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6648:            chomp($varvalue);
                   6649:            $perlvar{$varname}=$varvalue;
                   6650:         }
                   6651:     }
1.448     albertel 6652:     close($config);
1.227     harris41 6653: }
1.1       albertel 6654: 
1.327     albertel 6655: # ------------------------------------------------------------ Read domain file
                   6656: {
                   6657:     %domaindescription = ();
                   6658:     %domain_auth_def = ();
                   6659:     %domain_auth_arg_def = ();
1.448     albertel 6660:     my $fh;
                   6661:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6662:        while (<$fh>) {
1.390     matthew  6663:            next if (/^(\#|\s*$)/);
                   6664: #           next if /^\#/;
1.327     albertel 6665:            chomp;
1.403     www      6666:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  6667: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      6668: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6669:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6670: 	   $domaindescription{$domain}=$domain_description;
                   6671: 	   $domain_lang_def{$domain}=$def_lang;
                   6672: 	   $domain_city{$domain}=$city;
                   6673: 	   $domain_longi{$domain}=$longi;
                   6674: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  6675:            $domain_primary{$domain}=$primary;
1.403     www      6676: 
1.448     albertel 6677:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6678: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6679: 	}
1.327     albertel 6680:     }
1.448     albertel 6681:     close ($fh);
1.327     albertel 6682: }
                   6683: 
                   6684: 
1.1       albertel 6685: # ------------------------------------------------------------- Read hosts file
                   6686: {
1.448     albertel 6687:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6688: 
                   6689:     while (my $configline=<$config>) {
1.303     matthew  6690:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6691:        chomp($configline);
1.595     albertel 6692:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6693:        $name=~s/\s//g;
1.595     albertel 6694:        if ($id && $domain && $role && $name) {
1.252     albertel 6695: 	 $hostname{$id}=$name;
                   6696: 	 $hostdom{$id}=$domain;
                   6697: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6698:        }
1.1       albertel 6699:     }
1.448     albertel 6700:     close($config);
1.619     albertel 6701:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 6702:     #&get_iphost();
1.1       albertel 6703: }
                   6704: 
1.598     albertel 6705: sub get_iphost {
                   6706:     if (%iphost) { return %iphost; }
1.653     albertel 6707:     my %name_to_ip;
1.598     albertel 6708:     foreach my $id (keys(%hostname)) {
                   6709: 	my $name=$hostname{$id};
1.653     albertel 6710: 	my $ip;
                   6711: 	if (!exists($name_to_ip{$name})) {
                   6712: 	    $ip = gethostbyname($name);
                   6713: 	    if (!$ip || length($ip) ne 4) {
                   6714: 		&logthis("Skipping host $id name $name no IP found\n");
                   6715: 		next;
                   6716: 	    }
                   6717: 	    $ip=inet_ntoa($ip);
                   6718: 	    $name_to_ip{$name} = $ip;
                   6719: 	} else {
                   6720: 	    $ip = $name_to_ip{$name};
1.598     albertel 6721: 	}
                   6722: 	push(@{$iphost{$ip}},$id);
                   6723:     }
                   6724:     return %iphost;
                   6725: }
                   6726: 
1.1       albertel 6727: # ------------------------------------------------------ Read spare server file
                   6728: {
1.448     albertel 6729:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 6730: 
                   6731:     while (my $configline=<$config>) {
                   6732:        chomp($configline);
1.284     matthew  6733:        if ($configline) {
1.1       albertel 6734:           $spareid{$configline}=1;
                   6735:        }
                   6736:     }
1.448     albertel 6737:     close($config);
1.1       albertel 6738: }
1.11      www      6739: # ------------------------------------------------------------ Read permissions
                   6740: {
1.448     albertel 6741:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      6742: 
                   6743:     while (my $configline=<$config>) {
1.448     albertel 6744: 	chomp($configline);
                   6745: 	if ($configline) {
                   6746: 	    my ($role,$perm)=split(/ /,$configline);
                   6747: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   6748: 	}
1.11      www      6749:     }
1.448     albertel 6750:     close($config);
1.11      www      6751: }
                   6752: 
                   6753: # -------------------------------------------- Read plain texts for permissions
                   6754: {
1.448     albertel 6755:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      6756: 
                   6757:     while (my $configline=<$config>) {
1.448     albertel 6758: 	chomp($configline);
                   6759: 	if ($configline) {
                   6760: 	    my ($short,$plain)=split(/:/,$configline);
                   6761: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   6762: 	}
1.135     www      6763:     }
1.448     albertel 6764:     close($config);
1.135     www      6765: }
                   6766: 
                   6767: # ---------------------------------------------------------- Read package table
                   6768: {
1.448     albertel 6769:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      6770: 
                   6771:     while (my $configline=<$config>) {
1.483     albertel 6772: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 6773: 	chomp($configline);
                   6774: 	my ($short,$plain)=split(/:/,$configline);
                   6775: 	my ($pack,$name)=split(/\&/,$short);
                   6776: 	if ($plain ne '') {
                   6777: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   6778: 	    $packagetab{$short}=$plain; 
                   6779: 	}
1.11      www      6780:     }
1.448     albertel 6781:     close($config);
1.329     matthew  6782: }
                   6783: 
                   6784: # ------------- set up temporary directory
                   6785: {
                   6786:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   6787: 
1.11      www      6788: }
                   6789: 
1.599     albertel 6790: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      6791: 
1.281     www      6792: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      6793: $dumpcount=0;
1.22      www      6794: 
1.163     harris41 6795: &logtouch();
1.672     albertel 6796: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      6797: $readit=1;
1.564     albertel 6798:     {
                   6799: 	use integer;
                   6800: 	my $test=(2**32)+1;
1.568     albertel 6801: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 6802: 	&logthis(" Detected 64bit platform ($_64bit)");
                   6803:     }
1.195     www      6804: }
1.1       albertel 6805: }
1.179     www      6806: 
1.1       albertel 6807: 1;
1.191     harris41 6808: __END__
                   6809: 
1.243     albertel 6810: =pod
                   6811: 
1.191     harris41 6812: =head1 NAME
                   6813: 
1.243     albertel 6814: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 6815: 
                   6816: =head1 SYNOPSIS
                   6817: 
1.243     albertel 6818: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 6819: 
                   6820:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   6821: 
1.243     albertel 6822: Common parameters:
                   6823: 
                   6824: =over 4
                   6825: 
                   6826: =item *
                   6827: 
                   6828: $uname : an internal username (if $cname expecting a course Id specifically)
                   6829: 
                   6830: =item *
                   6831: 
                   6832: $udom : a domain (if $cdom expecting a course's domain specifically)
                   6833: 
                   6834: =item *
                   6835: 
                   6836: $symb : a resource instance identifier
                   6837: 
                   6838: =item *
                   6839: 
                   6840: $namespace : the name of a .db file that contains the data needed or
                   6841: being set.
                   6842: 
                   6843: =back
                   6844: 
1.394     bowersj2 6845: =head1 OVERVIEW
1.191     harris41 6846: 
1.394     bowersj2 6847: lonnet provides subroutines which interact with the
                   6848: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   6849: about classes, users, and resources.
1.243     albertel 6850: 
                   6851: For many of these objects you can also use this to store data about
                   6852: them or modify them in various ways.
1.191     harris41 6853: 
1.394     bowersj2 6854: =head2 Symbs
1.191     harris41 6855: 
1.394     bowersj2 6856: To identify a specific instance of a resource, LON-CAPA uses symbols
                   6857: or "symbs"X<symb>. These identifiers are built from the URL of the
                   6858: map, the resource number of the resource in the map, and the URL of
                   6859: the resource itself. The latter is somewhat redundant, but might help
                   6860: if maps change.
                   6861: 
                   6862: An example is
                   6863: 
                   6864:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   6865: 
                   6866: The respective map entry is
                   6867: 
                   6868:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   6869:   title="Problem 2">
                   6870:  </resource>
                   6871: 
                   6872: Symbs are used by the random number generator, as well as to store and
                   6873: restore data specific to a certain instance of for example a problem.
                   6874: 
                   6875: =head2 Storing And Retrieving Data
                   6876: 
                   6877: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   6878: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   6879: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   6880: is is the non-critical message twin of cstore. These functions are for
                   6881: handlers to store a perl hash to a user's permanent data space in an
                   6882: easy manner, and to retrieve it again on another call. It is expected
                   6883: that a handler would use this once at the beginning to retrieve data,
                   6884: and then again once at the end to send only the new data back.
                   6885: 
                   6886: The data is stored in the user's data directory on the user's
                   6887: homeserver under the ID of the course.
                   6888: 
                   6889: The hash that is returned by restore will have all of the previous
                   6890: value for all of the elements of the hash.
                   6891: 
                   6892: Example:
                   6893: 
                   6894:  #creating a hash
                   6895:  my %hash;
                   6896:  $hash{'foo'}='bar';
                   6897: 
                   6898:  #storing it
                   6899:  &Apache::lonnet::cstore(\%hash);
                   6900: 
                   6901:  #changing a value
                   6902:  $hash{'foo'}='notbar';
                   6903: 
                   6904:  #adding a new value
                   6905:  $hash{'bar'}='foo';
                   6906:  &Apache::lonnet::cstore(\%hash);
                   6907: 
                   6908:  #retrieving the hash
                   6909:  my %history=&Apache::lonnet::restore();
                   6910: 
                   6911:  #print the hash
                   6912:  foreach my $key (sort(keys(%history))) {
                   6913:    print("\%history{$key} = $history{$key}");
                   6914:  }
                   6915: 
                   6916: Will print out:
1.191     harris41 6917: 
1.394     bowersj2 6918:  %history{1:foo} = bar
                   6919:  %history{1:keys} = foo:timestamp
                   6920:  %history{1:timestamp} = 990455579
                   6921:  %history{2:bar} = foo
                   6922:  %history{2:foo} = notbar
                   6923:  %history{2:keys} = foo:bar:timestamp
                   6924:  %history{2:timestamp} = 990455580
                   6925:  %history{bar} = foo
                   6926:  %history{foo} = notbar
                   6927:  %history{timestamp} = 990455580
                   6928:  %history{version} = 2
                   6929: 
                   6930: Note that the special hash entries C<keys>, C<version> and
                   6931: C<timestamp> were added to the hash. C<version> will be equal to the
                   6932: total number of versions of the data that have been stored. The
                   6933: C<timestamp> attribute will be the UNIX time the hash was
                   6934: stored. C<keys> is available in every historical section to list which
                   6935: keys were added or changed at a specific historical revision of a
                   6936: hash.
                   6937: 
                   6938: B<Warning>: do not store the hash that restore returns directly. This
                   6939: will cause a mess since it will restore the historical keys as if the
                   6940: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 6941: 
1.394     bowersj2 6942: Calling convention:
1.191     harris41 6943: 
1.394     bowersj2 6944:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   6945:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 6946: 
1.394     bowersj2 6947: For more detailed information, see lonnet specific documentation.
1.191     harris41 6948: 
1.394     bowersj2 6949: =head1 RETURN MESSAGES
1.191     harris41 6950: 
1.394     bowersj2 6951: =over 4
1.191     harris41 6952: 
1.394     bowersj2 6953: =item * B<con_lost>: unable to contact remote host
1.191     harris41 6954: 
1.394     bowersj2 6955: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   6956: when the connection is brought back up
1.191     harris41 6957: 
1.394     bowersj2 6958: =item * B<con_failed>: unable to contact remote host and unable to save message
                   6959: for later delivery
1.191     harris41 6960: 
1.394     bowersj2 6961: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 6962: 
1.394     bowersj2 6963: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 6964: that was requested
1.191     harris41 6965: 
1.243     albertel 6966: =back
1.191     harris41 6967: 
1.243     albertel 6968: =head1 PUBLIC SUBROUTINES
1.191     harris41 6969: 
1.243     albertel 6970: =head2 Session Environment Functions
1.191     harris41 6971: 
1.243     albertel 6972: =over 4
1.191     harris41 6973: 
1.394     bowersj2 6974: =item * 
                   6975: X<appenv()>
                   6976: B<appenv(%hash)>: the value of %hash is written to
                   6977: the user envirnoment file, and will be restored for each access this
1.620     albertel 6978: user makes during this session, also modifies the %env for the current
1.394     bowersj2 6979: process
1.191     harris41 6980: 
                   6981: =item *
1.394     bowersj2 6982: X<delenv()>
                   6983: B<delenv($regexp)>: removes all items from the session
                   6984: environment file that matches the regular expression in $regexp. The
1.620     albertel 6985: values are also delted from the current processes %env.
1.191     harris41 6986: 
1.243     albertel 6987: =back
                   6988: 
                   6989: =head2 User Information
1.191     harris41 6990: 
1.243     albertel 6991: =over 4
1.191     harris41 6992: 
                   6993: =item *
1.394     bowersj2 6994: X<queryauthenticate()>
                   6995: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 6996: authentication scheme
                   6997: 
                   6998: =item *
1.394     bowersj2 6999: X<authenticate()>
                   7000: B<authenticate($uname,$upass,$udom)>: try to
                   7001: authenticate user from domain's lib servers (first use the current
                   7002: one). C<$upass> should be the users password.
1.191     harris41 7003: 
                   7004: =item *
1.394     bowersj2 7005: X<homeserver()>
                   7006: B<homeserver($uname,$udom)>: find the server which has
                   7007: the user's directory and files (there must be only one), this caches
                   7008: the answer, and also caches if there is a borken connection.
1.191     harris41 7009: 
                   7010: =item *
1.394     bowersj2 7011: X<idget()>
                   7012: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7013: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7014: username, and only 1 username per ID in a specific domain) (returns
                   7015: hash: id=>name,id=>name)
1.191     harris41 7016: 
                   7017: =item *
1.394     bowersj2 7018: X<idrget()>
                   7019: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7020: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7021: 
                   7022: =item *
1.394     bowersj2 7023: X<idput()>
                   7024: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7025: 
                   7026: =item *
1.394     bowersj2 7027: X<rolesinit()>
                   7028: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7029: 
                   7030: =item *
1.551     albertel 7031: X<getsection()>
                   7032: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7033: course $cname, return section name/number or '' for "not in course"
                   7034: and '-1' for "no section"
                   7035: 
                   7036: =item *
1.394     bowersj2 7037: X<userenvironment()>
                   7038: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7039: passed in @what from the requested user's environment, returns a hash
                   7040: 
                   7041: =back
                   7042: 
                   7043: =head2 User Roles
                   7044: 
                   7045: =over 4
                   7046: 
                   7047: =item *
                   7048: 
                   7049: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7050: actions
                   7051:  F: full access
                   7052:  U,I,K: authentication modes (cxx only)
                   7053:  '': forbidden
                   7054:  1: user needs to choose course
                   7055:  2: browse allowed
                   7056: 
                   7057: =item *
                   7058: 
                   7059: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7060: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7061: and course level
                   7062: 
                   7063: =item *
                   7064: 
                   7065: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7066: explanation of a user role term
                   7067: 
                   7068: =back
                   7069: 
                   7070: =head2 User Modification
                   7071: 
                   7072: =over 4
                   7073: 
                   7074: =item *
                   7075: 
                   7076: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7077: user for the level given by URL.  Optional start and end dates (leave empty
                   7078: string or zero for "no date")
1.191     harris41 7079: 
                   7080: =item *
                   7081: 
1.243     albertel 7082: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7083: change a users, password, possible return values are: ok,
                   7084: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7085: refused
1.191     harris41 7086: 
                   7087: =item *
                   7088: 
1.243     albertel 7089: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7090: 
                   7091: =item *
                   7092: 
1.243     albertel 7093: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7094: modify user
1.191     harris41 7095: 
                   7096: =item *
                   7097: 
1.286     matthew  7098: modifystudent
                   7099: 
                   7100: modify a students enrollment and identification information.
                   7101: The course id is resolved based on the current users environment.  
                   7102: This means the envoking user must be a course coordinator or otherwise
                   7103: associated with a course.
                   7104: 
1.297     matthew  7105: This call is essentially a wrapper for lonnet::modifyuser and
                   7106: lonnet::modify_student_enrollment
1.286     matthew  7107: 
                   7108: Inputs: 
                   7109: 
                   7110: =over 4
                   7111: 
                   7112: =item B<$udom> Students loncapa domain
                   7113: 
                   7114: =item B<$uname> Students loncapa login name
                   7115: 
                   7116: =item B<$uid> Students id/student number
                   7117: 
                   7118: =item B<$umode> Students authentication mode
                   7119: 
                   7120: =item B<$upass> Students password
                   7121: 
                   7122: =item B<$first> Students first name
                   7123: 
                   7124: =item B<$middle> Students middle name
                   7125: 
                   7126: =item B<$last> Students last name
                   7127: 
                   7128: =item B<$gene> Students generation
                   7129: 
                   7130: =item B<$usec> Students section in course
                   7131: 
                   7132: =item B<$end> Unix time of the roles expiration
                   7133: 
                   7134: =item B<$start> Unix time of the roles start date
                   7135: 
                   7136: =item B<$forceid> If defined, allow $uid to be changed
                   7137: 
                   7138: =item B<$desiredhome> server to use as home server for student
                   7139: 
                   7140: =back
1.297     matthew  7141: 
                   7142: =item *
                   7143: 
                   7144: modify_student_enrollment
                   7145: 
                   7146: Change a students enrollment status in a class.  The environment variable
                   7147: 'role.request.course' must be defined for this function to proceed.
                   7148: 
                   7149: Inputs:
                   7150: 
                   7151: =over 4
                   7152: 
                   7153: =item $udom, students domain
                   7154: 
                   7155: =item $uname, students name
                   7156: 
                   7157: =item $uid, students user id
                   7158: 
                   7159: =item $first, students first name
                   7160: 
                   7161: =item $middle
                   7162: 
                   7163: =item $last
                   7164: 
                   7165: =item $gene
                   7166: 
                   7167: =item $usec
                   7168: 
                   7169: =item $end
                   7170: 
                   7171: =item $start
                   7172: 
                   7173: =back
                   7174: 
1.191     harris41 7175: 
                   7176: =item *
                   7177: 
1.243     albertel 7178: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7179: custom role; give a custom role to a user for the level given by URL.  Specify
                   7180: name and domain of role author, and role name
1.191     harris41 7181: 
                   7182: =item *
                   7183: 
1.243     albertel 7184: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7185: 
                   7186: =item *
                   7187: 
1.243     albertel 7188: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7189: 
                   7190: =back
                   7191: 
                   7192: =head2 Course Infomation
                   7193: 
                   7194: =over 4
1.191     harris41 7195: 
                   7196: =item *
                   7197: 
1.631     albertel 7198: coursedescription($courseid) : returns a hash of information about the
                   7199: specified course id, including all environment settings for the
                   7200: course, the description of the course will be in the hash under the
                   7201: key 'description'
1.191     harris41 7202: 
                   7203: =item *
                   7204: 
1.624     albertel 7205: resdata($name,$domain,$type,@which) : request for current parameter
                   7206: setting for a specific $type, where $type is either 'course' or 'user',
                   7207: @what should be a list of parameters to ask about. This routine caches
                   7208: answers for 5 minutes.
1.243     albertel 7209: 
                   7210: =back
                   7211: 
                   7212: =head2 Course Modification
                   7213: 
                   7214: =over 4
1.191     harris41 7215: 
                   7216: =item *
                   7217: 
1.243     albertel 7218: writecoursepref($courseid,%prefs) : write preferences (environment
                   7219: database) for a course
1.191     harris41 7220: 
                   7221: =item *
                   7222: 
1.243     albertel 7223: createcourse($udom,$description,$url) : make/modify course
                   7224: 
                   7225: =back
                   7226: 
                   7227: =head2 Resource Subroutines
                   7228: 
                   7229: =over 4
1.191     harris41 7230: 
                   7231: =item *
                   7232: 
1.243     albertel 7233: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7234: 
                   7235: =item *
                   7236: 
1.243     albertel 7237: repcopy($filename) : subscribes to the requested file, and attempts to
                   7238: replicate from the owning library server, Might return
1.607     raeburn  7239: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7240: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7241: resource. Expects the local filesystem pathname
                   7242: (/home/httpd/html/res/....)
                   7243: 
                   7244: =back
                   7245: 
                   7246: =head2 Resource Information
                   7247: 
                   7248: =over 4
1.191     harris41 7249: 
                   7250: =item *
                   7251: 
1.243     albertel 7252: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7253: a vairety of different possible values, $varname should be a request
                   7254: string, and the other parameters can be used to specify who and what
                   7255: one is asking about.
                   7256: 
                   7257: Possible values for $varname are environment.lastname (or other item
                   7258: from the envirnment hash), user.name (or someother aspect about the
                   7259: user), resource.0.maxtries (or some other part and parameter of a
                   7260: resource)
1.204     albertel 7261: 
                   7262: =item *
                   7263: 
1.243     albertel 7264: directcondval($number) : get current value of a condition; reads from a state
                   7265: string
1.204     albertel 7266: 
                   7267: =item *
                   7268: 
1.243     albertel 7269: condval($condidx) : value of condition index based on state
1.204     albertel 7270: 
                   7271: =item *
                   7272: 
1.243     albertel 7273: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7274: resource's metadata, $what should be either a specific key, or either
                   7275: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7276: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7277: 
                   7278: this function automatically caches all requests
1.191     harris41 7279: 
                   7280: =item *
                   7281: 
1.243     albertel 7282: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7283: network of library servers; returns file handle of where SQL and regex results
                   7284: will be stored for query
1.191     harris41 7285: 
                   7286: =item *
                   7287: 
1.243     albertel 7288: symbread($filename) : return symbolic list entry (filename argument optional);
                   7289: returns the data handle
1.191     harris41 7290: 
                   7291: =item *
                   7292: 
1.243     albertel 7293: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7294: a possible symb for the URL in $thisfn, and if is an encryypted
                   7295: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7296: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7297: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7298: 
1.191     harris41 7299: 
                   7300: =item *
                   7301: 
1.243     albertel 7302: symbclean($symb) : removes versions numbers from a symb, returns the
                   7303: cleaned symb
1.191     harris41 7304: 
                   7305: =item *
                   7306: 
1.243     albertel 7307: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7308: course map, user must be in a course for it to work.
1.191     harris41 7309: 
                   7310: =item *
                   7311: 
1.243     albertel 7312: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7313: 
                   7314: =item *
                   7315: 
1.243     albertel 7316: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7317: a random seed, all arguments are optional, if they aren't sent it uses the
                   7318: environment to derive them. Note: if symb isn't sent and it can't get one
                   7319: from &symbread it will use the current time as its return value
1.191     harris41 7320: 
                   7321: =item *
                   7322: 
1.243     albertel 7323: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7324: unfakeable, receipt
1.191     harris41 7325: 
                   7326: =item *
                   7327: 
1.620     albertel 7328: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7329: 
                   7330: =item *
                   7331: 
1.243     albertel 7332: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7333: 
                   7334: =item *
                   7335: 
1.243     albertel 7336: 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 7337: 
                   7338: =item *
                   7339: 
1.243     albertel 7340: 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 7341: 
                   7342: =item *
                   7343: 
1.243     albertel 7344: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7345: 
                   7346: =item *
                   7347: 
1.243     albertel 7348: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7349: forcing spreadsheet to reevaluate the resource scores next time.
                   7350: 
                   7351: =back
                   7352: 
                   7353: =head2 Storing/Retreiving Data
                   7354: 
                   7355: =over 4
1.191     harris41 7356: 
                   7357: =item *
                   7358: 
1.243     albertel 7359: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7360: for this url; hashref needs to be given and should be a \%hashname; the
                   7361: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7362: be derived from the env
1.191     harris41 7363: 
                   7364: =item *
                   7365: 
1.243     albertel 7366: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7367: uses critical subroutine
1.191     harris41 7368: 
                   7369: =item *
                   7370: 
1.243     albertel 7371: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7372: all args are optional
1.191     harris41 7373: 
                   7374: =item *
                   7375: 
1.717     albertel 7376: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7377: dumps the complete (or key matching regexp) namespace into a hash
                   7378: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7379: normally &store()ed into
                   7380: 
                   7381: $range should be either an integer '100' (give me the first 100
                   7382:                                            matching records)
                   7383:               or be  two integers sperated by a - with no spaces
                   7384:                  '30-50' (give me the 30th through the 50th matching
                   7385:                           records)
                   7386: 
                   7387: 
                   7388: =item *
                   7389: 
                   7390: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7391: replaces a &store() version of data with a replacement set of data
                   7392: for a particular resource in a namespace passed in the $storehash hash 
                   7393: reference
                   7394: 
                   7395: =item *
                   7396: 
1.243     albertel 7397: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7398: works very similar to store/cstore, but all data is stored in a
                   7399: temporary location and can be reset using tmpreset, $storehash should
                   7400: be a hash reference, returns nothing on success
1.191     harris41 7401: 
                   7402: =item *
                   7403: 
1.243     albertel 7404: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7405: similar to restore, but all data is stored in a temporary location and
                   7406: can be reset using tmpreset. Returns a hash of values on success,
                   7407: error string otherwise.
1.191     harris41 7408: 
                   7409: =item *
                   7410: 
1.243     albertel 7411: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7412: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7413: 
                   7414: =item *
                   7415: 
1.243     albertel 7416: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7417: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7418: 
                   7419: =item *
                   7420: 
1.243     albertel 7421: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7422: namesp ($udom and $uname are optional)
1.191     harris41 7423: 
                   7424: =item *
                   7425: 
1.702     albertel 7426: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7427: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7428: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7429: 
1.702     albertel 7430: $range should be either an integer '100' (give me the first 100
                   7431:                                            matching records)
                   7432:               or be  two integers sperated by a - with no spaces
                   7433:                  '30-50' (give me the 30th through the 50th matching
                   7434:                           records)
1.449     matthew  7435: =item *
                   7436: 
                   7437: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7438: $store can be a scalar, an array reference, or if the amount to be 
                   7439: incremented is > 1, a hash reference.
                   7440: 
                   7441: ($udom and $uname are optional)
1.191     harris41 7442: 
                   7443: =item *
                   7444: 
1.243     albertel 7445: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7446: ($udom and $uname are optional)
1.191     harris41 7447: 
                   7448: =item *
                   7449: 
1.243     albertel 7450: cput($namespace,$storehash,$udom,$uname) : critical put
                   7451: ($udom and $uname are optional)
1.191     harris41 7452: 
                   7453: =item *
                   7454: 
1.243     albertel 7455: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7456: reference filled in from namesp (encrypts the return communication)
                   7457: ($udom and $uname are optional)
1.191     harris41 7458: 
                   7459: =item *
                   7460: 
1.243     albertel 7461: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7462: critical subroutine
                   7463: 
                   7464: =back
                   7465: 
                   7466: =head2 Network Status Functions
                   7467: 
                   7468: =over 4
1.191     harris41 7469: 
                   7470: =item *
                   7471: 
                   7472: dirlist($uri) : return directory list based on URI
                   7473: 
                   7474: =item *
                   7475: 
1.243     albertel 7476: spareserver() : find server with least workload from spare.tab
                   7477: 
                   7478: =back
                   7479: 
                   7480: =head2 Apache Request
                   7481: 
                   7482: =over 4
1.191     harris41 7483: 
                   7484: =item *
                   7485: 
1.243     albertel 7486: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7487: localhost, posts hash
                   7488: 
                   7489: =back
                   7490: 
                   7491: =head2 Data to String to Data
                   7492: 
                   7493: =over 4
1.191     harris41 7494: 
                   7495: =item *
                   7496: 
1.243     albertel 7497: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7498: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7499: 
                   7500: =item *
                   7501: 
1.243     albertel 7502: hashref2str($hashref) : convert a hashref into a string complete with
                   7503: escaping and '=' and '&' separators, supports elements that are
                   7504: arrayrefs and hashrefs
1.191     harris41 7505: 
                   7506: =item *
                   7507: 
1.243     albertel 7508: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7509: with escaping and '&' separators, supports elements that are arrayrefs
                   7510: and hashrefs
1.191     harris41 7511: 
                   7512: =item *
                   7513: 
1.243     albertel 7514: str2hash($string) : convert string to hash using unescaping and
                   7515: splitting on '=' and '&', supports elements that are arrayrefs and
                   7516: hashrefs
1.191     harris41 7517: 
                   7518: =item *
                   7519: 
1.243     albertel 7520: str2array($string) : convert string to hash using unescaping and
                   7521: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7522: 
                   7523: =back
                   7524: 
                   7525: =head2 Logging Routines
                   7526: 
                   7527: =over 4
                   7528: 
                   7529: These routines allow one to make log messages in the lonnet.log and
                   7530: lonnet.perm logfiles.
1.191     harris41 7531: 
                   7532: =item *
                   7533: 
1.243     albertel 7534: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 7535: 
                   7536: =item *
                   7537: 
1.243     albertel 7538: logthis() : append message to the normal lonnet.log file, it gets
                   7539: preiodically rolled over and deleted.
1.191     harris41 7540: 
                   7541: =item *
                   7542: 
1.243     albertel 7543: logperm() : append a permanent message to lonnet.perm.log, this log
                   7544: file never gets deleted by any automated portion of the system, only
                   7545: messages of critical importance should go in here.
                   7546: 
                   7547: =back
                   7548: 
                   7549: =head2 General File Helper Routines
                   7550: 
                   7551: =over 4
1.191     harris41 7552: 
                   7553: =item *
                   7554: 
1.481     raeburn  7555: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7556: (a) files in /uploaded
                   7557:   (i) If a local copy of the file exists - 
                   7558:       compares modification date of local copy with last-modified date for 
                   7559:       definitive version stored on home server for course. If local copy is 
                   7560:       stale, requests a new version from the home server and stores it. 
                   7561:       If the original has been removed from the home server, then local copy 
                   7562:       is unlinked.
                   7563:   (ii) If local copy does not exist -
                   7564:       requests the file from the home server and stores it. 
                   7565:   
                   7566:   If $caller is 'uploadrep':  
                   7567:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7568:     for request for files originally uploaded via DOCS. 
                   7569:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7570:   
                   7571:   Otherwise:
                   7572:      This indicates a call from the content generation phase of the request.
                   7573:      -  returns the entire contents of the file or -1.
                   7574:      
                   7575: (b) files in /res
                   7576:    - returns the entire contents of a file or -1; 
                   7577:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7578: 
1.712     albertel 7579: 
                   7580: =item *
                   7581: 
                   7582: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   7583:                   reference
                   7584: 
                   7585: returns either a stat() list of data about the file or an empty list
                   7586: if the file doesn't exist or couldn't find out about it (connection
                   7587: problems or user unknown)
                   7588: 
1.191     harris41 7589: =item *
                   7590: 
1.243     albertel 7591: filelocation($dir,$file) : returns file system location of a file
                   7592: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7593: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7594: and a file of ../bob will become /a/bob)
1.191     harris41 7595: 
                   7596: =item *
                   7597: 
                   7598: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7599: filelocation except for hrefs
                   7600: 
                   7601: =item *
                   7602: 
                   7603: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7604: 
1.243     albertel 7605: =back
                   7606: 
1.608     albertel 7607: =head2 Usererfile file routines (/uploaded*)
                   7608: 
                   7609: =over 4
                   7610: 
                   7611: =item *
                   7612: 
                   7613: userfileupload(): main rotine for putting a file in a user or course's
                   7614:                   filespace, arguments are,
                   7615: 
1.620     albertel 7616:  formname - required - this is the name of the element in $env where the
1.608     albertel 7617:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7618:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7619:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7620:  coursedoc - if true, store the file in the course of the active role
                   7621:              of the current user
                   7622:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7623:          if undefined, it will be placed in "unknown"
                   7624: 
                   7625:  (This routine calls clean_filename() to remove any dangerous
                   7626:  characters from the filename, and then calls finuserfileupload() to
                   7627:  complete the transaction)
                   7628: 
                   7629:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7630:  and /adm/notfound.html if unsuccessful
                   7631: 
                   7632: =item *
                   7633: 
                   7634: clean_filename(): routine for cleaing a filename up for storage in
                   7635:                  userfile space, argument is:
                   7636: 
                   7637:  filename - proposed filename
                   7638: 
                   7639: returns: the new clean filename
                   7640: 
                   7641: =item *
                   7642: 
                   7643: finishuserfileupload(): routine that creaes and sends the file to
                   7644: userspace, probably shouldn't be called directly
                   7645: 
                   7646:   docuname: username or courseid of destination for the file
                   7647:   docudom: domain of user/course of destination for the file
                   7648:   formname: same as for userfileupload()
                   7649:   fname: filename (inculding subdirectories) for the file
                   7650: 
                   7651:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7652:  and /adm/notfound.html if unsuccessful
                   7653: 
                   7654: =item *
                   7655: 
                   7656: renameuserfile(): renames an existing userfile to a new name
                   7657: 
                   7658:   Args:
                   7659:    docuname: username or courseid of destination for the file
                   7660:    docudom: domain of user/course of destination for the file
                   7661:    old: current file name (including any subdirs under userfiles)
                   7662:    new: desired file name (including any subdirs under userfiles)
                   7663: 
                   7664: =item *
                   7665: 
                   7666: mkdiruserfile(): creates a directory is a userfiles dir
                   7667: 
                   7668:   Args:
                   7669:    docuname: username or courseid of destination for the file
                   7670:    docudom: domain of user/course of destination for the file
                   7671:    dir: dir to create (including any subdirs under userfiles)
                   7672: 
                   7673: =item *
                   7674: 
                   7675: removeuserfile(): removes a file that exists in userfiles
                   7676: 
                   7677:   Args:
                   7678:    docuname: username or courseid of destination for the file
                   7679:    docudom: domain of user/course of destination for the file
                   7680:    fname: filname to delete (including any subdirs under userfiles)
                   7681: 
                   7682: =item *
                   7683: 
                   7684: removeuploadedurl(): convience function for removeuserfile()
                   7685: 
                   7686:   Args:
                   7687:    url:  a full /uploaded/... url to delete
                   7688: 
                   7689: =back
                   7690: 
1.243     albertel 7691: =head2 HTTP Helper Routines
                   7692: 
                   7693: =over 4
                   7694: 
1.191     harris41 7695: =item *
                   7696: 
                   7697: escape() : unpack non-word characters into CGI-compatible hex codes
                   7698: 
                   7699: =item *
                   7700: 
                   7701: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   7702: 
1.243     albertel 7703: =back
                   7704: 
                   7705: =head1 PRIVATE SUBROUTINES
                   7706: 
                   7707: =head2 Underlying communication routines (Shouldn't call)
                   7708: 
                   7709: =over 4
                   7710: 
                   7711: =item *
                   7712: 
                   7713: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   7714: 
                   7715: =item *
                   7716: 
                   7717: reply() : uses subreply to send a message to remote machine, logs all failures
                   7718: 
                   7719: =item *
                   7720: 
                   7721: critical() : passes a critical message to another server; if cannot
                   7722: get through then place message in connection buffer directory and
                   7723: returns con_delayed, if incapable of saving message, returns
                   7724: con_failed
                   7725: 
                   7726: =item *
                   7727: 
                   7728: reconlonc() : tries to reconnect lonc client processes.
                   7729: 
                   7730: =back
                   7731: 
                   7732: =head2 Resource Access Logging
                   7733: 
                   7734: =over 4
                   7735: 
                   7736: =item *
                   7737: 
                   7738: flushcourselogs() : flush (save) buffer logs and access logs
                   7739: 
                   7740: =item *
                   7741: 
                   7742: courselog($what) : save message for course in hash
                   7743: 
                   7744: =item *
                   7745: 
                   7746: courseacclog($what) : save message for course using &courselog().  Perform
                   7747: special processing for specific resource types (problems, exams, quizzes, etc).
                   7748: 
1.191     harris41 7749: =item *
                   7750: 
                   7751: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   7752: as a PerlChildExitHandler
1.243     albertel 7753: 
                   7754: =back
                   7755: 
                   7756: =head2 Other
                   7757: 
                   7758: =over 4
                   7759: 
                   7760: =item *
                   7761: 
                   7762: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 7763: 
                   7764: =back
                   7765: 
                   7766: =cut

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