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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.652   ! albertel    4: # $Id: lonnet.pm,v 1.651 2005/08/31 08:25:16 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.349     www        40:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
1.599     albertel   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
                     42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.619     albertel   43:    %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir $_64bit
                     44:    %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.8       www        48: use Apache::Constants qw(:common :http);
1.208     albertel   49: use HTML::LCParser;
1.637     raeburn    50: use HTML::Parser;
1.88      www        51: use Fcntl qw(:flock);
1.414     www        52: use Apache::lonlocal;
1.557     albertel   53: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   54: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   55: use Cache::Memcached;
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
                     88: 
1.163     harris41   89: sub logtouch {
                     90:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel   91:     unless (-e "$execdir/logs/lonnet.log") {	
                     92: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41   93: 	close $fh;
                     94:     }
                     95:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                     96:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                     97: }
                     98: 
1.1       albertel   99: sub logthis {
                    100:     my $message=shift;
                    101:     my $execdir=$perlvar{'lonDaemons'};
                    102:     my $now=time;
                    103:     my $local=localtime($now);
1.448     albertel  104:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    105: 	print $fh "$local ($$): $message\n";
                    106: 	close($fh);
                    107:     }
1.1       albertel  108:     return 1;
                    109: }
                    110: 
                    111: sub logperm {
                    112:     my $message=shift;
                    113:     my $execdir=$perlvar{'lonDaemons'};
                    114:     my $now=time;
                    115:     my $local=localtime($now);
1.448     albertel  116:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    117: 	print $fh "$now:$message:$local\n";
                    118: 	close($fh);
                    119:     }
1.1       albertel  120:     return 1;
                    121: }
                    122: 
                    123: # -------------------------------------------------- Non-critical communication
                    124: sub subreply {
                    125:     my ($cmd,$server)=@_;
                    126:     my $peerfile="$perlvar{'lonSockDir'}/$server";
1.549     foxr      127:     #
                    128:     #  With loncnew process trimming, there's a timing hole between lonc server
                    129:     #  process exit and the master server picking up the listen on the AF_UNIX
                    130:     #  socket.  In that time interval, a lock file will exist:
                    131: 
                    132:     my $lockfile=$peerfile.".lock";
                    133:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    134: 	sleep(1);
                    135:     }
                    136:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      137:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      138:     #
1.550     foxr      139:     #   We'll give the connection a few tries before abandoning it.  If
                    140:     #   connection is not possible, we'll con_lost back to the client.
                    141:     #   
                    142:     my $client;
                    143:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    144: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    145: 				      Type    => SOCK_STREAM,
                    146: 				      Timeout => 10);
                    147: 	if($client) {
                    148: 	    last;		# Connected!
                    149: 	}
                    150: 	sleep(1);		# Try again later if failed connection.
                    151:     }
                    152:     my $answer;
                    153:     if ($client) {
                    154: 	print $client "$cmd\n";
                    155: 	$answer=<$client>;
                    156: 	if (!$answer) { $answer="con_lost"; }
                    157: 	chomp($answer);
                    158:     } else {
                    159: 	$answer = 'con_lost';	# Failed connection.
                    160:     }
1.1       albertel  161:     return $answer;
                    162: }
                    163: 
                    164: sub reply {
                    165:     my ($cmd,$server)=@_;
1.205     www       166:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  167:     my $answer=subreply($cmd,$server);
1.65      www       168:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12      www       169:        &logthis("<font color=blue>WARNING:".
                    170:                 " $cmd to $server returned $answer</font>");
                    171:     }
1.1       albertel  172:     return $answer;
                    173: }
                    174: 
                    175: # ----------------------------------------------------------- Send USR1 to lonc
                    176: 
                    177: sub reconlonc {
                    178:     my $peerfile=shift;
                    179:     &logthis("Trying to reconnect for $peerfile");
                    180:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  181:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  182: 	my $loncpid=<$fh>;
                    183:         chomp($loncpid);
                    184:         if (kill 0 => $loncpid) {
                    185: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    186:             kill USR1 => $loncpid;
                    187:             sleep 1;
                    188:             if (-e "$peerfile") { return; }
                    189:             &logthis("$peerfile still not there, give it another try");
                    190:             sleep 5;
                    191:             if (-e "$peerfile") { return; }
1.12      www       192:             &logthis(
                    193:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  194:         } else {
1.12      www       195: 	    &logthis(
                    196:                "<font color=blue>WARNING:".
                    197:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  198:         }
                    199:     } else {
1.12      www       200:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1       albertel  201:     }
                    202: }
                    203: 
                    204: # ------------------------------------------------------ Critical communication
1.12      www       205: 
1.1       albertel  206: sub critical {
                    207:     my ($cmd,$server)=@_;
1.89      www       208:     unless ($hostname{$server}) {
                    209:         &logthis("<font color=blue>WARNING:".
                    210:                " Critical message to unknown server ($server)</font>");
                    211:         return 'no_such_host';
                    212:     }
1.1       albertel  213:     my $answer=reply($cmd,$server);
                    214:     if ($answer eq 'con_lost') {
                    215: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  216: 	my $answer=reply($cmd,$server);
1.1       albertel  217:         if ($answer eq 'con_lost') {
                    218:             my $now=time;
                    219:             my $middlename=$cmd;
1.5       www       220:             $middlename=substr($middlename,0,16);
1.1       albertel  221:             $middlename=~s/\W//g;
                    222:             my $dfilename=
1.305     www       223:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    224:             $dumpcount++;
1.1       albertel  225:             {
1.448     albertel  226: 		my $dfh;
                    227: 		if (open($dfh,">$dfilename")) {
                    228: 		    print $dfh "$cmd\n"; 
                    229: 		    close($dfh);
                    230: 		}
1.1       albertel  231:             }
                    232:             sleep 2;
                    233:             my $wcmd='';
                    234:             {
1.448     albertel  235: 		my $dfh;
                    236: 		if (open($dfh,"<$dfilename")) {
                    237: 		    $wcmd=<$dfh>; 
                    238: 		    close($dfh);
                    239: 		}
1.1       albertel  240:             }
                    241:             chomp($wcmd);
1.7       www       242:             if ($wcmd eq $cmd) {
1.12      www       243: 		&logthis("<font color=blue>WARNING: ".
                    244:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  245:                 &logperm("D:$server:$cmd");
                    246: 	        return 'con_delayed';
                    247:             } else {
1.12      www       248:                 &logthis("<font color=red>CRITICAL:"
                    249:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  250:                 &logperm("F:$server:$cmd");
                    251:                 return 'con_failed';
                    252:             }
                    253:         }
                    254:     }
                    255:     return $answer;
1.405     albertel  256: }
                    257: 
1.374     www       258: # ------------------------------------------- Transfer profile into environment
                    259: 
                    260: sub transfer_profile_to_env {
                    261:     my ($lonidsdir,$handle)=@_;
                    262:     my @profile;
                    263:     {
1.448     albertel  264: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       265: 	flock($idf,LOCK_SH);
                    266: 	@profile=<$idf>;
1.448     albertel  267: 	close($idf);
1.374     www       268:     }
                    269:     my $envi;
1.433     matthew   270:     my %Remove;
1.374     www       271:     for ($envi=0;$envi<=$#profile;$envi++) {
                    272: 	chomp($profile[$envi]);
                    273: 	my ($envname,$envvalue)=split(/=/,$profile[$envi]);
1.619     albertel  274: 	$env{$envname} = $envvalue;
1.433     matthew   275:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    276:             if ($time < time-300) {
                    277:                 $Remove{$key}++;
                    278:             }
                    279:         }
                    280:     }
1.619     albertel  281:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   282:     foreach my $expired_key (keys(%Remove)) {
                    283:         &delenv($expired_key);
1.374     www       284:     }
1.1       albertel  285: }
                    286: 
1.5       www       287: # ---------------------------------------------------------- Append Environment
                    288: 
                    289: sub appenv {
1.6       www       290:     my %newenv=@_;
1.191     harris41  291:     foreach (keys %newenv) {
1.35      www       292: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
                    293:             &logthis("<font color=blue>WARNING: ".
1.151     www       294:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    295:                 .'</font>');
1.35      www       296: 	    delete($newenv{$_});
                    297:         } else {
1.619     albertel  298:             $env{$_}=$newenv{$_};
1.35      www       299:         }
1.191     harris41  300:     }
1.95      www       301: 
                    302:     my $lockfh;
1.620     albertel  303:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  304: 	return 'error: '.$!;
1.95      www       305:     }
                    306:     unless (flock($lockfh,LOCK_EX)) {
                    307:          &logthis("<font color=blue>WARNING: ".
                    308:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  309:          close($lockfh);
1.95      www       310:          return 'error: '.$!;
                    311:     }
                    312: 
1.6       www       313:     my @oldenv;
                    314:     {
1.448     albertel  315: 	my $fh;
1.620     albertel  316: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  317: 	    return 'error: '.$!;
                    318: 	}
                    319: 	@oldenv=<$fh>;
                    320: 	close($fh);
1.6       www       321:     }
                    322:     for (my $i=0; $i<=$#oldenv; $i++) {
                    323:         chomp($oldenv[$i]);
1.9       www       324:         if ($oldenv[$i] ne '') {
1.448     albertel  325: 	    my ($name,$value)=split(/=/,$oldenv[$i]);
                    326: 	    unless (defined($newenv{$name})) {
                    327: 		$newenv{$name}=$value;
                    328: 	    }
1.9       www       329:         }
1.6       www       330:     }
                    331:     {
1.448     albertel  332: 	my $fh;
1.620     albertel  333: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  334: 	    return 'error';
                    335: 	}
                    336: 	my $newname;
                    337: 	foreach $newname (keys %newenv) {
                    338: 	    print $fh "$newname=$newenv{$newname}\n";
                    339: 	}
                    340: 	close($fh);
1.56      www       341:     }
1.448     albertel  342: 	
                    343:     close($lockfh);
1.56      www       344:     return 'ok';
                    345: }
                    346: # ----------------------------------------------------- Delete from Environment
                    347: 
                    348: sub delenv {
                    349:     my $delthis=shift;
                    350:     my %newenv=();
                    351:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
                    352:         &logthis("<font color=blue>WARNING: ".
                    353:                 "Attempt to delete from environment ".$delthis);
                    354:         return 'error';
                    355:     }
                    356:     my @oldenv;
                    357:     {
1.448     albertel  358: 	my $fh;
1.620     albertel  359: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  360: 	    return 'error';
                    361: 	}
                    362: 	unless (flock($fh,LOCK_SH)) {
                    363: 	    &logthis("<font color=blue>WARNING: ".
                    364: 		     'Could not obtain shared lock in delenv: '.$!);
                    365: 	    close($fh);
                    366: 	    return 'error: '.$!;
                    367: 	}
                    368: 	@oldenv=<$fh>;
                    369: 	close($fh);
1.56      www       370:     }
                    371:     {
1.448     albertel  372: 	my $fh;
1.620     albertel  373: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  374: 	    return 'error';
                    375: 	}
                    376: 	unless (flock($fh,LOCK_EX)) {
                    377: 	    &logthis("<font color=blue>WARNING: ".
                    378: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    379: 	    close($fh);
                    380: 	    return 'error: '.$!;
                    381: 	}
                    382: 	foreach (@oldenv) {
1.473     matthew   383: 	    if ($_=~/^$delthis/) { 
                    384:                 my ($key,undef) = split('=',$_);
1.619     albertel  385:                 delete($env{$key});
1.473     matthew   386:             } else {
                    387:                 print $fh $_; 
                    388:             }
1.448     albertel  389: 	}
                    390: 	close($fh);
1.5       www       391:     }
                    392:     return 'ok';
1.369     albertel  393: }
                    394: 
                    395: # ------------------------------------------ Find out current server userload
                    396: # there is a copy in lond
                    397: sub userload {
                    398:     my $numusers=0;
                    399:     {
                    400: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    401: 	my $filename;
                    402: 	my $curtime=time;
                    403: 	while ($filename=readdir(LONIDS)) {
                    404: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  405: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  406: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  407: 	}
                    408: 	closedir(LONIDS);
                    409:     }
                    410:     my $userloadpercent=0;
                    411:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    412:     if ($maxuserload) {
1.371     albertel  413: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  414:     }
1.372     albertel  415:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  416:     return $userloadpercent;
1.283     www       417: }
                    418: 
                    419: # ------------------------------------------ Fight off request when overloaded
                    420: 
                    421: sub overloaderror {
                    422:     my ($r,$checkserver)=@_;
                    423:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    424:     my $loadavg;
                    425:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  426:        open(my $loadfile,'/proc/loadavg');
1.283     www       427:        $loadavg=<$loadfile>;
                    428:        $loadavg =~ s/\s.*//g;
1.285     matthew   429:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  430:        close($loadfile);
1.283     www       431:     } else {
                    432:        $loadavg=&reply('load',$checkserver);
                    433:     }
1.285     matthew   434:     my $overload=$loadavg-100;
1.283     www       435:     if ($overload>0) {
1.285     matthew   436: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       437:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       438:         return 413;
1.283     www       439:     }    
                    440:     return '';
1.5       www       441: }
1.1       albertel  442: 
                    443: # ------------------------------ Find server with least workload from spare.tab
1.11      www       444: 
1.1       albertel  445: sub spareserver {
1.370     albertel  446:     my ($loadpercent,$userloadpercent) = @_;
1.1       albertel  447:     my $tryserver;
                    448:     my $spareserver='';
1.370     albertel  449:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    450:     my $lowestserver=$loadpercent > $userloadpercent?
                    451: 	             $loadpercent :  $userloadpercent;
1.1       albertel  452:     foreach $tryserver (keys %spareid) {
1.411     albertel  453: 	my $loadans=reply('load',$tryserver);
                    454: 	my $userloadans=reply('userload',$tryserver);
                    455: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    456: 	    next; #didn't get a number from the server
                    457: 	}
                    458: 	my $answer;
                    459: 	if ($loadans =~ /\d/) {
                    460: 	    if ($userloadans =~ /\d/) {
                    461: 		#both are numbers, pick the bigger one
                    462: 		$answer=$loadans > $userloadans?
                    463: 		    $loadans :  $userloadans;
                    464: 	    } else {
                    465: 		$answer = $loadans;
                    466: 	    }
                    467: 	} else {
                    468: 	    $answer = $userloadans;
                    469: 	}
                    470: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
                    471: 	    $spareserver="http://$hostname{$tryserver}";
                    472: 	    $lowestserver=$answer;
                    473: 	}
1.370     albertel  474:     }
1.1       albertel  475:     return $spareserver;
1.202     matthew   476: }
                    477: 
                    478: # --------------------------------------------- Try to change a user's password
                    479: 
                    480: sub changepass {
                    481:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    482:     $currentpass = &escape($currentpass);
                    483:     $newpass     = &escape($newpass);
                    484:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    485: 		       $server);
                    486:     if (! $answer) {
                    487: 	&logthis("No reply on password change request to $server ".
                    488: 		 "by $uname in domain $udom.");
                    489:     } elsif ($answer =~ "^ok") {
                    490:         &logthis("$uname in $udom successfully changed their password ".
                    491: 		 "on $server.");
                    492:     } elsif ($answer =~ "^pwchange_failure") {
                    493: 	&logthis("$uname in $udom was unable to change their password ".
                    494: 		 "on $server.  The action was blocked by either lcpasswd ".
                    495: 		 "or pwchange");
                    496:     } elsif ($answer =~ "^non_authorized") {
                    497:         &logthis("$uname in $udom did not get their password correct when ".
                    498: 		 "attempting to change it on $server.");
                    499:     } elsif ($answer =~ "^auth_mode_error") {
                    500:         &logthis("$uname in $udom attempted to change their password despite ".
                    501: 		 "not being locally or internally authenticated on $server.");
                    502:     } elsif ($answer =~ "^unknown_user") {
                    503:         &logthis("$uname in $udom attempted to change their password ".
                    504: 		 "on $server but were unable to because $server is not ".
                    505: 		 "their home server.");
                    506:     } elsif ($answer =~ "^refused") {
                    507: 	&logthis("$server refused to change $uname in $udom password because ".
                    508: 		 "it was sent an unencrypted request to change the password.");
                    509:     }
                    510:     return $answer;
1.1       albertel  511: }
                    512: 
1.169     harris41  513: # ----------------------- Try to determine user's current authentication scheme
                    514: 
                    515: sub queryauthenticate {
                    516:     my ($uname,$udom)=@_;
1.456     albertel  517:     my $uhome=&homeserver($uname,$udom);
                    518:     if (!$uhome) {
                    519: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    520: 	return 'no_host';
                    521:     }
                    522:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    523:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    524: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  525:     }
1.456     albertel  526:     return $answer;
1.169     harris41  527: }
                    528: 
1.1       albertel  529: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       530: 
1.1       albertel  531: sub authenticate {
                    532:     my ($uname,$upass,$udom)=@_;
1.12      www       533:     $upass=escape($upass);
1.199     www       534:     $uname=~s/\W//g;
1.471     albertel  535:     my $uhome=&homeserver($uname,$udom);
                    536:     if (!$uhome) {
                    537: 	&logthis("User $uname at $udom is unknown in authenticate");
                    538: 	return 'no_host';
1.1       albertel  539:     }
1.471     albertel  540:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    541:     if ($answer eq 'authorized') {
                    542: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    543: 	return $uhome; 
                    544:     }
                    545:     if ($answer eq 'non_authorized') {
                    546: 	&logthis("User $uname at $udom rejected by $uhome");
                    547: 	return 'no_host'; 
1.9       www       548:     }
1.471     albertel  549:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  550:     return 'no_host';
                    551: }
                    552: 
                    553: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       554: 
1.599     albertel  555: my %homecache;
1.1       albertel  556: sub homeserver {
1.230     stredwic  557:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  558:     my $index="$uname:$udom";
1.426     albertel  559: 
1.599     albertel  560:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  561:     my $tryserver;
                    562:     foreach $tryserver (keys %libserv) {
1.230     stredwic  563:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  564: 		 exists($badServerCache{$tryserver}));
1.1       albertel  565: 	if ($hostdom{$tryserver} eq $udom) {
                    566:            my $answer=reply("home:$udom:$uname",$tryserver);
                    567:            if ($answer eq 'found') { 
1.599     albertel  568: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  569:            } elsif ($answer eq 'no_host') {
                    570: 	       $badServerCache{$tryserver}=1;
1.221     matthew   571:            }
1.1       albertel  572:        }
                    573:     }    
                    574:     return 'no_host';
1.70      www       575: }
                    576: 
                    577: # ------------------------------------- Find the usernames behind a list of IDs
                    578: 
                    579: sub idget {
                    580:     my ($udom,@ids)=@_;
                    581:     my %returnhash=();
                    582:     
                    583:     my $tryserver;
                    584:     foreach $tryserver (keys %libserv) {
                    585:        if ($hostdom{$tryserver} eq $udom) {
                    586: 	  my $idlist=join('&',@ids);
                    587:           $idlist=~tr/A-Z/a-z/; 
                    588: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    589:           my @answer=();
1.76      www       590:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       591: 	      @answer=split(/\&/,$reply);
                    592:           }                    ;
                    593:           my $i;
                    594:           for ($i=0;$i<=$#ids;$i++) {
                    595:               if ($answer[$i]) {
                    596: 		  $returnhash{$ids[$i]}=$answer[$i];
                    597:               } 
                    598:           }
                    599:        }
                    600:     }    
                    601:     return %returnhash;
                    602: }
                    603: 
                    604: # ------------------------------------- Find the IDs behind a list of usernames
                    605: 
                    606: sub idrget {
                    607:     my ($udom,@unames)=@_;
                    608:     my %returnhash=();
1.191     harris41  609:     foreach (@unames) {
1.70      www       610:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  611:     }
1.70      www       612:     return %returnhash;
                    613: }
                    614: 
                    615: # ------------------------------- Store away a list of names and associated IDs
                    616: 
                    617: sub idput {
                    618:     my ($udom,%ids)=@_;
                    619:     my %servers=();
1.191     harris41  620:     foreach (keys %ids) {
1.487     albertel  621: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       622:         my $uhom=&homeserver($_,$udom);
                    623:         if ($uhom ne 'no_host') {
                    624:             my $id=&escape($ids{$_});
                    625:             $id=~tr/A-Z/a-z/;
                    626:             my $unam=&escape($_);
                    627: 	    if ($servers{$uhom}) {
                    628: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    629:             } else {
                    630:                 $servers{$uhom}=$id.'='.$unam;
                    631:             }
                    632:         }
1.191     harris41  633:     }
                    634:     foreach (keys %servers) {
1.70      www       635:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  636:     }
1.344     www       637: }
                    638: 
                    639: # --------------------------------------------------- Assign a key to a student
                    640: 
                    641: sub assign_access_key {
1.364     www       642: #
                    643: # a valid key looks like uname:udom#comments
                    644: # comments are being appended
                    645: #
1.498     www       646:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    647:     $kdom=
1.620     albertel  648:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       649:     $knum=
1.620     albertel  650:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       651:     $cdom=
1.620     albertel  652:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       653:     $cnum=
1.620     albertel  654:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    655:     $udom=$env{'user.name'} unless (defined($udom));
                    656:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       657:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       658:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  659:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       660:                                                   # assigned to this person
                    661:                                                   # - this should not happen,
1.345     www       662:                                                   # unless something went wrong
                    663:                                                   # the first time around
                    664: # ready to assign
1.364     www       665:         $logentry=$1.'; '.$logentry;
1.496     www       666:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       667:                                                  $kdom,$knum) eq 'ok') {
1.345     www       668: # key now belongs to user
1.346     www       669: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       670:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    671:                 &appenv('environment.'.$envkey => $ckey);
                    672:                 return 'ok';
                    673:             } else {
                    674:                 return 
                    675:   'error: Count not permanently assign key, will need to be re-entered later.';
                    676: 	    }
                    677:         } else {
                    678:             return 'error: Could not assign key, try again later.';
                    679:         }
1.364     www       680:     } elsif (!$existing{$ckey}) {
1.345     www       681: # the key does not exist
                    682: 	return 'error: The key does not exist';
                    683:     } else {
                    684: # the key is somebody else's
                    685: 	return 'error: The key is already in use';
                    686:     }
1.344     www       687: }
                    688: 
1.364     www       689: # ------------------------------------------ put an additional comment on a key
                    690: 
                    691: sub comment_access_key {
                    692: #
                    693: # a valid key looks like uname:udom#comments
                    694: # comments are being appended
                    695: #
                    696:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    697:     $cdom=
1.620     albertel  698:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       699:     $cnum=
1.620     albertel  700:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       701:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    702:     if ($existing{$ckey}) {
                    703:         $existing{$ckey}.='; '.$logentry;
                    704: # ready to assign
1.367     www       705:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       706:                                                  $cdom,$cnum) eq 'ok') {
                    707: 	    return 'ok';
                    708:         } else {
                    709: 	    return 'error: Count not store comment.';
                    710:         }
                    711:     } else {
                    712: # the key does not exist
                    713: 	return 'error: The key does not exist';
                    714:     }
                    715: }
                    716: 
1.344     www       717: # ------------------------------------------------------ Generate a set of keys
                    718: 
                    719: sub generate_access_keys {
1.364     www       720:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       721:     $cdom=
1.620     albertel  722:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       723:     $cnum=
1.620     albertel  724:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       725:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       726:     unless (($cdom) && ($cnum)) { return 0; }
                    727:     if ($number>10000) { return 0; }
                    728:     sleep(2); # make sure don't get same seed twice
                    729:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    730:     my $total=0;
                    731:     for (my $i=1;$i<=$number;$i++) {
                    732:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    733:                   sprintf("%lx",int(100000*rand)).'-'.
                    734:                   sprintf("%lx",int(100000*rand));
                    735:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    736:        $newkey=~s/0/h/g; # and also 0 and O
                    737:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    738:        if ($existing{$newkey}) {
                    739:            $i--;
                    740:        } else {
1.364     www       741: 	  if (&put('accesskeys',
                    742:               { $newkey => '# generated '.localtime().
1.620     albertel  743:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       744:                            '; '.$logentry },
                    745: 		   $cdom,$cnum) eq 'ok') {
1.344     www       746:               $total++;
                    747: 	  }
                    748:        }
                    749:     }
1.620     albertel  750:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       751:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    752:     return $total;
                    753: }
                    754: 
                    755: # ------------------------------------------------------- Validate an accesskey
                    756: 
                    757: sub validate_access_key {
                    758:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    759:     $cdom=
1.620     albertel  760:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       761:     $cnum=
1.620     albertel  762:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    763:     $udom=$env{'user.domain'} unless (defined($udom));
                    764:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       765:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  766:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       767: }
                    768: 
                    769: # ------------------------------------- Find the section of student in a course
1.652   ! albertel  770: sub devalidate_getsection_cache {
        !           771:     my ($udom,$unam,$courseid)=@_;
        !           772:     $courseid=~s/\_/\//g;
        !           773:     $courseid=~s/^(\w)/\/$1/;
        !           774:     my $hashid="$udom:$unam:$courseid";
        !           775:     &devalidate_cache_new('getsection',$hashid);
        !           776: }
1.298     matthew   777: 
                    778: sub getsection {
                    779:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  780:     my $cachetime=1800;
1.298     matthew   781:     $courseid=~s/\_/\//g;
                    782:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  783: 
                    784:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  785:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  786:     if (defined($cached)) { return $result; }
                    787: 
1.298     matthew   788:     my %Pending; 
                    789:     my %Expired;
                    790:     #
                    791:     # Each role can either have not started yet (pending), be active, 
                    792:     #    or have expired.
                    793:     #
                    794:     # If there is an active role, we are done.
                    795:     #
                    796:     # If there is more than one role which has not started yet, 
                    797:     #     choose the one which will start sooner
                    798:     # If there is one role which has not started yet, return it.
                    799:     #
                    800:     # If there is more than one expired role, choose the one which ended last.
                    801:     # If there is a role which has expired, return it.
                    802:     #
                    803:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    804:                         &homeserver($unam,$udom)))) {
                    805:         my ($key,$value)=split(/\=/,$_);
                    806:         $key=&unescape($key);
1.479     albertel  807:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   808:         my $section=$1;
                    809:         if ($key eq $courseid.'_st') { $section=''; }
                    810:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    811:         my $now=time;
1.548     albertel  812:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   813:             $Expired{$end}=$section;
                    814:             next;
                    815:         }
1.548     albertel  816:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   817:             $Pending{$start}=$section;
                    818:             next;
                    819:         }
1.599     albertel  820:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   821:     }
                    822:     #
                    823:     # Presumedly there will be few matching roles from the above
                    824:     # loop and the sorting time will be negligible.
                    825:     if (scalar(keys(%Pending))) {
                    826:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  827:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   828:     } 
                    829:     if (scalar(keys(%Expired))) {
                    830:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    831:         my $time = pop(@sorted);
1.599     albertel  832:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   833:     }
1.599     albertel  834:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   835: }
1.70      www       836: 
1.599     albertel  837: sub save_cache {
1.628     albertel  838:     my ($r)=@_;
                    839:     if (! $r->is_initial_req()) { return DECLINED; }
1.599     albertel  840:     &purge_remembered();
1.620     albertel  841:     undef(%env);
1.628     albertel  842:     return OK;
1.599     albertel  843: }
1.452     albertel  844: 
1.599     albertel  845: my $to_remember=-1;
                    846: my %remembered;
                    847: my %accessed;
                    848: my $kicks=0;
                    849: my $hits=0;
                    850: sub devalidate_cache_new {
                    851:     my ($name,$id,$debug) = @_;
                    852:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    853:     $id=&escape($name.':'.$id);
                    854:     $memcache->delete($id);
                    855:     delete($remembered{$id});
                    856:     delete($accessed{$id});
                    857: }
                    858: 
                    859: sub is_cached_new {
                    860:     my ($name,$id,$debug) = @_;
                    861:     $id=&escape($name.':'.$id);
                    862:     if (exists($remembered{$id})) {
                    863: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    864: 	$accessed{$id}=[&gettimeofday()];
                    865: 	$hits++;
                    866: 	return ($remembered{$id},1);
                    867:     }
                    868:     my $value = $memcache->get($id);
                    869:     if (!(defined($value))) {
                    870: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  871: 	return (undef,undef);
1.416     albertel  872:     }
1.599     albertel  873:     if ($value eq '__undef__') {
                    874: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    875: 	$value=undef;
                    876:     }
                    877:     &make_room($id,$value,$debug);
                    878:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    879:     return ($value,1);
                    880: }
                    881: 
                    882: sub do_cache_new {
                    883:     my ($name,$id,$value,$time,$debug) = @_;
                    884:     $id=&escape($name.':'.$id);
                    885:     my $setvalue=$value;
                    886:     if (!defined($setvalue)) {
                    887: 	$setvalue='__undef__';
                    888:     }
1.623     albertel  889:     if (!defined($time) ) {
                    890: 	$time=600;
                    891:     }
1.599     albertel  892:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  893:     $memcache->set($id,$setvalue,$time);
                    894:     # need to make a copy of $value
                    895:     #&make_room($id,$value,$debug);
1.599     albertel  896:     return $value;
                    897: }
                    898: 
                    899: sub make_room {
                    900:     my ($id,$value,$debug)=@_;
                    901:     $remembered{$id}=$value;
                    902:     if ($to_remember<0) { return; }
                    903:     $accessed{$id}=[&gettimeofday()];
                    904:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    905:     my $to_kick;
                    906:     my $max_time=0;
                    907:     foreach my $other (keys(%accessed)) {
                    908: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    909: 	    $to_kick=$other;
                    910: 	    $max_time=&tv_interval($accessed{$other});
                    911: 	}
                    912:     }
                    913:     delete($remembered{$to_kick});
                    914:     delete($accessed{$to_kick});
                    915:     $kicks++;
                    916:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  917:     return;
                    918: }
                    919: 
1.599     albertel  920: sub purge_remembered {
1.604     albertel  921:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    922:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  923:     undef(%remembered);
                    924:     undef(%accessed);
1.428     albertel  925: }
1.70      www       926: # ------------------------------------- Read an entry from a user's environment
                    927: 
                    928: sub userenvironment {
                    929:     my ($udom,$unam,@what)=@_;
                    930:     my %returnhash=();
                    931:     my @answer=split(/\&/,
                    932:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    933:                       &homeserver($unam,$udom)));
                    934:     my $i;
                    935:     for ($i=0;$i<=$#what;$i++) {
                    936: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    937:     }
                    938:     return %returnhash;
1.1       albertel  939: }
                    940: 
1.617     albertel  941: # ---------------------------------------------------------- Get a studentphoto
                    942: sub studentphoto {
                    943:     my ($udom,$unam,$ext) = @_;
                    944:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                    945:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext",$home);
                    946:     my $url="/uploaded/$udom/$unam/internal/studentphoto.".$ext;
                    947:     if ($ret ne 'ok') {
                    948: 	return '/adm/lonKaputt/lonlogo_broken.gif';
                    949:     }
                    950:     my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                    951:     return $tokenurl;
                    952: }
                    953: 
1.263     www       954: # -------------------------------------------------------------------- New chat
                    955: 
                    956: sub chatsend {
                    957:     my ($newentry,$anon)=@_;
1.620     albertel  958:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                    959:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                    960:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www       961:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel  962: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.263     www       963: 		   &escape($newentry)),$chome);
1.292     www       964: }
                    965: 
                    966: # ------------------------------------------ Find current version of a resource
                    967: 
                    968: sub getversion {
                    969:     my $fname=&clutter(shift);
                    970:     unless ($fname=~/^\/res\//) { return -1; }
                    971:     return &currentversion(&filelocation('',$fname));
                    972: }
                    973: 
                    974: sub currentversion {
                    975:     my $fname=shift;
1.599     albertel  976:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www       977:     if (defined($cached)) { return $result; }
1.292     www       978:     my $author=$fname;
                    979:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    980:     my ($udom,$uname)=split(/\//,$author);
                    981:     my $home=homeserver($uname,$udom);
                    982:     if ($home eq 'no_host') { 
                    983:         return -1; 
                    984:     }
                    985:     my $answer=reply("currentversion:$fname",$home);
                    986:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    987: 	return -1;
                    988:     }
1.599     albertel  989:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www       990: }
                    991: 
1.1       albertel  992: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www       993: 
1.1       albertel  994: sub subscribe {
                    995:     my $fname=shift;
1.312     www       996:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel  997:     $fname=~s/[\n\r]//g;
1.1       albertel  998:     my $author=$fname;
                    999:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1000:     my ($udom,$uname)=split(/\//,$author);
                   1001:     my $home=homeserver($uname,$udom);
1.335     albertel 1002:     if ($home eq 'no_host') {
                   1003:         return 'not_found';
1.1       albertel 1004:     }
                   1005:     my $answer=reply("sub:$fname",$home);
1.64      www      1006:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1007: 	$answer.=' by '.$home;
                   1008:     }
1.1       albertel 1009:     return $answer;
                   1010: }
                   1011:     
1.8       www      1012: # -------------------------------------------------------------- Replicate file
                   1013: 
                   1014: sub repcopy {
                   1015:     my $filename=shift;
1.23      www      1016:     $filename=~s/\/+/\//g;
1.607     raeburn  1017:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1018:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1019:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1020: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1021: 	return &repcopy_userfile($filename);
                   1022:     }
1.532     albertel 1023:     $filename=~s/[\n\r]//g;
1.8       www      1024:     my $transname="$filename.in.transfer";
1.607     raeburn  1025:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1026:     my $remoteurl=subscribe($filename);
1.64      www      1027:     if ($remoteurl =~ /^con_lost by/) {
                   1028: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1029:            return 'unavailable';
1.8       www      1030:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1031: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1032: 	   return 'not_found';
1.64      www      1033:     } elsif ($remoteurl =~ /^rejected by/) {
                   1034: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1035:            return 'forbidden';
1.20      www      1036:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1037:            return 'ok';
1.8       www      1038:     } else {
1.290     www      1039:         my $author=$filename;
                   1040:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1041:         my ($udom,$uname)=split(/\//,$author);
                   1042:         my $home=homeserver($uname,$udom);
                   1043:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1044:            my @parts=split(/\//,$filename);
                   1045:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1046:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1047:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1048: 	       return 'bad_request';
1.8       www      1049:            }
                   1050:            my $count;
                   1051:            for ($count=5;$count<$#parts;$count++) {
                   1052:                $path.="/$parts[$count]";
                   1053:                if ((-e $path)!=1) {
                   1054: 		   mkdir($path,0777);
                   1055:                }
                   1056:            }
                   1057:            my $ua=new LWP::UserAgent;
                   1058:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1059:            my $response=$ua->request($request,$transname);
                   1060:            if ($response->is_error()) {
                   1061: 	       unlink($transname);
                   1062:                my $message=$response->status_line;
1.12      www      1063:                &logthis("<font color=blue>WARNING:"
                   1064:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1065:                return 'unavailable';
1.8       www      1066:            } else {
1.16      www      1067: 	       if ($remoteurl!~/\.meta$/) {
                   1068:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1069:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1070:                   if ($mresponse->is_error()) {
                   1071: 		      unlink($filename.'.meta');
                   1072:                       &logthis(
                   1073:                      "<font color=yellow>INFO: No metadata: $filename</font>");
                   1074:                   }
                   1075: 	       }
1.8       www      1076:                rename($transname,$filename);
1.607     raeburn  1077:                return 'ok';
1.8       www      1078:            }
1.290     www      1079:        }
1.8       www      1080:     }
1.330     www      1081: }
                   1082: 
                   1083: # ------------------------------------------------ Get server side include body
                   1084: sub ssi_body {
1.381     albertel 1085:     my ($filelink,%form)=@_;
1.606     matthew  1086:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1087:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1088:     }
1.330     www      1089:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1090:                                      &ssi($filelink,%form));
1.565     albertel 1091:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1092:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1093:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1094:     return $output;
1.8       www      1095: }
                   1096: 
1.15      www      1097: # --------------------------------------------------------- Server Side Include
                   1098: 
                   1099: sub ssi {
                   1100: 
1.23      www      1101:     my ($fn,%form)=@_;
1.15      www      1102: 
                   1103:     my $ua=new LWP::UserAgent;
1.23      www      1104:     
                   1105:     my $request;
                   1106:     
                   1107:     if (%form) {
                   1108:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1109:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1110:     } else {
                   1111:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1112:     }
                   1113: 
1.15      www      1114:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1115:     my $response=$ua->request($request);
                   1116: 
1.324     www      1117:     return $response->content;
                   1118: }
                   1119: 
                   1120: sub externalssi {
                   1121:     my ($url)=@_;
                   1122:     my $ua=new LWP::UserAgent;
                   1123:     my $request=new HTTP::Request('GET',$url);
                   1124:     my $response=$ua->request($request);
1.15      www      1125:     return $response->content;
                   1126: }
1.254     www      1127: 
1.492     albertel 1128: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1129: 
                   1130: sub allowuploaded {
                   1131:     my ($srcurl,$url)=@_;
                   1132:     $url=&clutter(&declutter($url));
                   1133:     my $dir=$url;
                   1134:     $dir=~s/\/[^\/]+$//;
                   1135:     my %httpref=();
                   1136:     my $httpurl=&hreflocation('',$url);
                   1137:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1138:     &Apache::lonnet::appenv(%httpref);
1.254     www      1139: }
1.477     raeburn  1140: 
1.478     albertel 1141: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1142: # input: action, courseID, current domain, intended
1.637     raeburn  1143: #        path to file, source of file, instruction to parse file for objects,
                   1144: #        ref to hash for embedded objects,
                   1145: #        ref to hash for codebase of java objects.
                   1146: #
1.485     raeburn  1147: # output: url to file (if action was uploaddoc), 
                   1148: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1149: #
1.478     albertel 1150: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1151: # course.
1.477     raeburn  1152: #
1.478     albertel 1153: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1154: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1155: #          course's home server.
1.477     raeburn  1156: #
1.478     albertel 1157: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1158: #          be copied from $source (current location) to 
                   1159: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1160: #         and will then be copied to
                   1161: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1162: #         course's home server.
1.485     raeburn  1163: #
1.481     raeburn  1164: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1165: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1166: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1167: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1168: #         in course's home server.
1.637     raeburn  1169: #
1.477     raeburn  1170: 
                   1171: sub process_coursefile {
1.638     albertel 1172:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1173:     my $fetchresult;
1.638     albertel 1174:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1175:     if ($action eq 'propagate') {
1.638     albertel 1176:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1177: 			     $home);
1.481     raeburn  1178:     } else {
1.477     raeburn  1179:         my $fetchresult = '';
                   1180:         my $fpath = '';
                   1181:         my $fname = $file;
1.478     albertel 1182:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1183:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1184:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1185:         if ($action eq 'copy') {
                   1186:             if ($source eq '') {
                   1187:                 $fetchresult = 'no source file';
                   1188:                 return $fetchresult;
                   1189:             } else {
                   1190:                 my $destination = $filepath.'/'.$fname;
                   1191:                 rename($source,$destination);
                   1192:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1193:                                  $home);
1.481     raeburn  1194:             }
                   1195:         } elsif ($action eq 'uploaddoc') {
                   1196:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1197:             print $fh $env{'form.'.$source};
1.481     raeburn  1198:             close($fh);
1.637     raeburn  1199:             if ($parser eq 'parse') {
                   1200:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1201:                 unless ($parse_result eq 'ok') {
                   1202:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1203:                 }
                   1204:             }
1.477     raeburn  1205:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1206:                                  $home);
1.481     raeburn  1207:             if ($fetchresult eq 'ok') {
                   1208:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1209:             } else {
                   1210:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1211:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1212:                 return '/adm/notfound.html';
                   1213:             }
1.477     raeburn  1214:         }
                   1215:     }
1.485     raeburn  1216:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1217:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1218:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1219:     }
                   1220:     return $fetchresult;
                   1221: }
                   1222: 
1.637     raeburn  1223: sub build_filepath {
                   1224:     my ($fpath) = @_;
                   1225:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1226:     unless ($fpath eq '') {
                   1227:         my @parts=split('/',$fpath);
                   1228:         foreach my $part (@parts) {
                   1229:             $filepath.= '/'.$part;
                   1230:             if ((-e $filepath)!=1) {
                   1231:                 mkdir($filepath,0777);
                   1232:             }
                   1233:         }
                   1234:     }
                   1235:     return $filepath;
                   1236: }
                   1237: 
                   1238: sub store_edited_file {
1.638     albertel 1239:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1240:     my $file = $primary_url;
                   1241:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1242:     my $fpath = '';
                   1243:     my $fname = $file;
                   1244:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1245:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1246:     my $filepath = &build_filepath($fpath);
                   1247:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1248:     print $fh $content;
                   1249:     close($fh);
1.638     albertel 1250:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1251:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1252: 			  $home);
1.637     raeburn  1253:     if ($$fetchresult eq 'ok') {
                   1254:         return '/uploaded/'.$fpath.'/'.$fname;
                   1255:     } else {
1.638     albertel 1256:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1257: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1258:         return '/adm/notfound.html';
                   1259:     }
                   1260: }
                   1261: 
1.531     albertel 1262: sub clean_filename {
                   1263:     my ($fname)=@_;
1.315     www      1264: # Replace Windows backslashes by forward slashes
1.257     www      1265:     $fname=~s/\\/\//g;
1.315     www      1266: # Get rid of everything but the actual filename
1.257     www      1267:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1268: # Replace spaces by underscores
                   1269:     $fname=~s/\s+/\_/g;
                   1270: # Replace all other weird characters by nothing
1.317     www      1271:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1272: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1273: # numbers
                   1274:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1275:     return $fname;
                   1276: }
                   1277: 
1.608     albertel 1278: # --------------- Take an uploaded file and put it into the userfiles directory
                   1279: # input: name of form element, coursedoc=1 means this is for the course
                   1280: # output: url of file in userspace
                   1281: 
                   1282: 
1.531     albertel 1283: sub userfileupload {
1.637     raeburn  1284:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase)=@_;
1.531     albertel 1285:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1286:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1287:     $fname=&clean_filename($fname);
1.315     www      1288: # See if there is anything left
1.257     www      1289:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1290:     chop($env{'form.'.$formname});
1.523     raeburn  1291:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1292:         my $now = time;
                   1293:         my $filepath = 'tmp/helprequests/'.$now;
                   1294:         my @parts=split(/\//,$filepath);
                   1295:         my $fullpath = $perlvar{'lonDaemons'};
                   1296:         for (my $i=0;$i<@parts;$i++) {
                   1297:             $fullpath .= '/'.$parts[$i];
                   1298:             if ((-e $fullpath)!=1) {
                   1299:                 mkdir($fullpath,0777);
                   1300:             }
                   1301:         }
                   1302:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1303:         print $fh $env{'form.'.$formname};
1.523     raeburn  1304:         close($fh);
                   1305:         return $fullpath.'/'.$fname; 
                   1306:     }
1.258     www      1307: # Create the directory if not present
1.493     albertel 1308:     $fname="$subdir/$fname";
1.259     www      1309:     if ($coursedoc) {
1.638     albertel 1310: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1311: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1312:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1313:             return &finishuserfileupload($docuname,$docudom,
                   1314: 					 $formname,$fname,$parser,$allfiles,
                   1315: 					 $codebase);
1.481     raeburn  1316:         } else {
1.620     albertel 1317:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1318:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1319: 				       $fname,$formname,$parser,
                   1320: 				       $allfiles,$codebase);
1.481     raeburn  1321:         }
1.259     www      1322:     } else {
1.638     albertel 1323:         my $docuname=$env{'user.name'};
                   1324:         my $docudom=$env{'user.domain'};
                   1325: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1326: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1327:     }
1.271     www      1328: }
                   1329: 
                   1330: sub finishuserfileupload {
1.638     albertel 1331:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1332:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1333:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1334:     my ($fnamepath,$file);
                   1335:     $file=$fname;
                   1336:     if ($fname=~m|/|) {
                   1337:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1338: 	$path.=$fnamepath.'/';
                   1339:     }
1.259     www      1340:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1341:     my $count;
                   1342:     for ($count=4;$count<=$#parts;$count++) {
                   1343:         $filepath.="/$parts[$count]";
                   1344:         if ((-e $filepath)!=1) {
                   1345: 	    mkdir($filepath,0777);
                   1346:         }
                   1347:     }
                   1348: # Save the file
                   1349:     {
1.570     albertel 1350: 	open(FH,'>'.$filepath.'/'.$file);
1.620     albertel 1351: 	print FH $env{'form.'.$formname};
1.570     albertel 1352: 	close(FH);
1.258     www      1353:     }
1.637     raeburn  1354:     if ($parser eq 'parse') {
1.638     albertel 1355:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1356: 						   $codebase);
1.637     raeburn  1357:         unless ($parse_result eq 'ok') {
1.638     albertel 1358:             &logthis('Failed to parse '.$filepath.$file.
                   1359: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1360:         }
                   1361:     }
1.259     www      1362: # Notify homeserver to grep it
                   1363: #
1.638     albertel 1364:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1365:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1366:     if ($fetchresult eq 'ok') {
1.259     www      1367: #
1.258     www      1368: # Return the URL to it
1.494     albertel 1369:         return '/uploaded/'.$path.$file;
1.263     www      1370:     } else {
1.494     albertel 1371:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1372: 		 ': '.$fetchresult);
1.263     www      1373:         return '/adm/notfound.html';
                   1374:     }    
1.493     albertel 1375: }
                   1376: 
1.637     raeburn  1377: sub extract_embedded_items {
1.648     raeburn  1378:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1379:     my @state = ();
                   1380:     my %javafiles = (
                   1381:                       codebase => '',
                   1382:                       code => '',
                   1383:                       archive => ''
                   1384:                     );
                   1385:     my %mediafiles = (
                   1386:                       src => '',
                   1387:                       movie => '',
                   1388:                      );
1.648     raeburn  1389:     my $p;
                   1390:     if ($content) {
                   1391:         $p = HTML::LCParser->new($content);
                   1392:     } else {
                   1393:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1394:     }
1.641     albertel 1395:     while (my $t=$p->get_token()) {
1.640     albertel 1396: 	if ($t->[0] eq 'S') {
                   1397: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1398: 	    push (@state, $tagname);
1.648     raeburn  1399:             if (lc($tagname) eq 'allow') {
                   1400:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1401:             }
1.640     albertel 1402: 	    if (lc($tagname) eq 'img') {
                   1403: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1404: 	    }
1.645     raeburn  1405:             if (lc($tagname) eq 'script') {
                   1406:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1407:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1408:                 } else {
                   1409:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1410:                 }
                   1411:             }
                   1412:             if (lc($tagname) eq 'link') {
                   1413:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1414:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1415:                 }
                   1416:             }
1.640     albertel 1417: 	    if (lc($tagname) eq 'object' ||
                   1418: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1419: 		foreach my $item (keys(%javafiles)) {
                   1420: 		    $javafiles{$item} = '';
                   1421: 		}
                   1422: 	    }
                   1423: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1424: 		my $name = lc($attr->{'name'});
                   1425: 		foreach my $item (keys(%javafiles)) {
                   1426: 		    if ($name eq $item) {
                   1427: 			$javafiles{$item} = $attr->{'value'};
                   1428: 			last;
                   1429: 		    }
                   1430: 		}
                   1431: 		foreach my $item (keys(%mediafiles)) {
                   1432: 		    if ($name eq $item) {
                   1433: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1434: 			last;
                   1435: 		    }
                   1436: 		}
                   1437: 	    }
                   1438: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1439: 		foreach my $item (keys(%javafiles)) {
                   1440: 		    if ($attr->{$item}) {
                   1441: 			$javafiles{$item} = $attr->{$item};
                   1442: 			last;
                   1443: 		    }
                   1444: 		}
                   1445: 		foreach my $item (keys(%mediafiles)) {
                   1446: 		    if ($attr->{$item}) {
                   1447: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1448: 			last;
                   1449: 		    }
                   1450: 		}
                   1451: 	    }
                   1452: 	} elsif ($t->[0] eq 'E') {
                   1453: 	    my ($tagname) = ($t->[1]);
                   1454: 	    if ($javafiles{'codebase'} ne '') {
                   1455: 		$javafiles{'codebase'} .= '/';
                   1456: 	    }  
                   1457: 	    if (lc($tagname) eq 'applet' ||
                   1458: 		lc($tagname) eq 'object' ||
                   1459: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1460: 		) {
                   1461: 		foreach my $item (keys(%javafiles)) {
                   1462: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1463: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1464: 			&add_filetype($allfiles,$file,$item);
                   1465: 		    }
                   1466: 		}
                   1467: 	    } 
                   1468: 	    pop @state;
                   1469: 	}
                   1470:     }
1.637     raeburn  1471:     return 'ok';
                   1472: }
                   1473: 
1.639     albertel 1474: sub add_filetype {
                   1475:     my ($allfiles,$file,$type)=@_;
                   1476:     if (exists($allfiles->{$file})) {
                   1477: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1478: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1479: 	}
                   1480:     } else {
                   1481: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1482:     }
                   1483: }
                   1484: 
1.493     albertel 1485: sub removeuploadedurl {
                   1486:     my ($url)=@_;
                   1487:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1488:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1489: }
                   1490: 
                   1491: sub removeuserfile {
                   1492:     my ($docuname,$docudom,$fname)=@_;
                   1493:     my $home=&homeserver($docuname,$docudom);
                   1494:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1495: }
1.15      www      1496: 
1.530     albertel 1497: sub mkdiruserfile {
                   1498:     my ($docuname,$docudom,$dir)=@_;
                   1499:     my $home=&homeserver($docuname,$docudom);
                   1500:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1501: }
                   1502: 
1.531     albertel 1503: sub renameuserfile {
                   1504:     my ($docuname,$docudom,$old,$new)=@_;
                   1505:     my $home=&homeserver($docuname,$docudom);
                   1506:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1507: 		  &escape("$new"),$home);
                   1508: }
                   1509: 
1.14      www      1510: # ------------------------------------------------------------------------- Log
                   1511: 
                   1512: sub log {
                   1513:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1514:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1515: }
                   1516: 
                   1517: # ------------------------------------------------------------------ Course Log
1.352     www      1518: #
                   1519: # This routine flushes several buffers of non-mission-critical nature
                   1520: #
1.157     www      1521: 
                   1522: sub flushcourselogs {
1.352     www      1523:     &logthis('Flushing log buffers');
                   1524: #
                   1525: # course logs
                   1526: # This is a log of all transactions in a course, which can be used
                   1527: # for data mining purposes
                   1528: #
                   1529: # It also collects the courseid database, which lists last transaction
                   1530: # times and course titles for all courseids
                   1531: #
                   1532:     my %courseidbuffer=();
1.191     harris41 1533:     foreach (keys %courselogs) {
1.157     www      1534:         my $crsid=$_;
1.352     www      1535:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1536: 		          &escape($courselogs{$crsid}),
                   1537: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1538: 	    delete $courselogs{$crsid};
                   1539:         } else {
                   1540:             &logthis('Failed to flush log buffer for '.$crsid);
                   1541:             if (length($courselogs{$crsid})>40000) {
                   1542:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
                   1543:                         " exceeded maximum size, deleting.</font>");
                   1544:                delete $courselogs{$crsid};
                   1545:             }
1.352     www      1546:         }
                   1547:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1548:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1549: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1550:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352     www      1551:         } else {
                   1552:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1553: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1554:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
                   1555:         }
1.191     harris41 1556:     }
1.352     www      1557: #
                   1558: # Write course id database (reverse lookup) to homeserver of courses 
                   1559: # Is used in pickcourse
                   1560: #
                   1561:     foreach (keys %courseidbuffer) {
1.353     www      1562:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1563:     }
                   1564: #
                   1565: # File accesses
                   1566: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1567: #
1.449     matthew  1568:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1569:         if ($entry =~ /___count$/) {
                   1570:             my ($dom,$name);
                   1571:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1572:             if (! defined($dom) || $dom eq '' || 
                   1573:                 ! defined($name) || $name eq '') {
1.620     albertel 1574:                 my $cid = $env{'request.course.id'};
                   1575:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1576:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1577:             }
1.450     matthew  1578:             my $value = $accesshash{$entry};
                   1579:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1580:             my %temphash=($url => $value);
1.449     matthew  1581:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1582:             if ($result eq 'ok') {
                   1583:                 delete $accesshash{$entry};
                   1584:             } elsif ($result eq 'unknown_cmd') {
                   1585:                 # Target server has old code running on it.
1.450     matthew  1586:                 my %temphash=($entry => $value);
1.449     matthew  1587:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1588:                     delete $accesshash{$entry};
                   1589:                 }
                   1590:             }
                   1591:         } else {
1.458     matthew  1592:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1593:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1594:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1595:                 delete $accesshash{$entry};
                   1596:             }
1.185     www      1597:         }
1.191     harris41 1598:     }
1.352     www      1599: #
                   1600: # Roles
                   1601: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1602: #
1.349     www      1603:     foreach (keys %userrolehash) {
                   1604:         my $entry=$_;
1.351     www      1605:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1606: 	    split(/\:/,$entry);
                   1607:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1608:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1609:                 $rudom,$runame) eq 'ok') {
                   1610: 	    delete $userrolehash{$entry};
                   1611:         }
                   1612:     }
1.186     www      1613:     $dumpcount++;
1.157     www      1614: }
                   1615: 
                   1616: sub courselog {
                   1617:     my $what=shift;
1.158     www      1618:     $what=time.':'.$what;
1.620     albertel 1619:     unless ($env{'request.course.id'}) { return ''; }
                   1620:     $coursedombuf{$env{'request.course.id'}}=
                   1621:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1622:     $coursenumbuf{$env{'request.course.id'}}=
                   1623:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1624:     $coursehombuf{$env{'request.course.id'}}=
                   1625:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1626:     $coursedescrbuf{$env{'request.course.id'}}=
                   1627:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1628:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1629:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1630:     $courseownerbuf{$env{'request.course.id'}}=
                   1631:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   1632:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1633: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1634:     } else {
1.620     albertel 1635: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1636:     }
1.620     albertel 1637:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1638: 	&flushcourselogs();
                   1639:     }
1.158     www      1640: }
                   1641: 
                   1642: sub courseacclog {
                   1643:     my $fnsymb=shift;
1.620     albertel 1644:     unless ($env{'request.course.id'}) { return ''; }
                   1645:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.408     www      1646:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) {
1.187     www      1647:         $what.=':POST';
1.583     matthew  1648:         # FIXME: Probably ought to escape things....
1.620     albertel 1649: 	foreach (keys %env) {
1.158     www      1650:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1651: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1652:             }
1.191     harris41 1653:         }
1.583     matthew  1654:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1655:         # FIXME: We should not be depending on a form parameter that someone
                   1656:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1657:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1658:             $what.= ':POST';
                   1659:             # FIXME: Probably ought to escape things....
                   1660:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1661:                                  'crsdiscuss') {
1.620     albertel 1662:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1663:             }
                   1664:         }
1.158     www      1665:     }
                   1666:     &courselog($what);
1.149     www      1667: }
                   1668: 
1.185     www      1669: sub countacc {
                   1670:     my $url=&declutter(shift);
1.458     matthew  1671:     return if (! defined($url) || $url eq '');
1.620     albertel 1672:     unless ($env{'request.course.id'}) { return ''; }
                   1673:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1674:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1675:     $accesshash{$key}++;
1.185     www      1676: }
1.349     www      1677: 
1.361     www      1678: sub linklog {
                   1679:     my ($from,$to)=@_;
                   1680:     $from=&declutter($from);
                   1681:     $to=&declutter($to);
                   1682:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1683:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1684: }
                   1685:   
1.349     www      1686: sub userrolelog {
                   1687:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
                   1688:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
                   1689:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.469     www      1690:         ($trole=~/^cr/) || ($trole=~/^ta/)) {
1.350     www      1691:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1692:        $userrolehash
                   1693:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1694:                     =$tend.':'.$tstart;
                   1695:    }
1.351     www      1696: }
                   1697: 
                   1698: sub get_course_adv_roles {
                   1699:     my $cid=shift;
1.620     albertel 1700:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1701:     my %coursehash=&coursedescription($cid);
1.470     www      1702:     my %nothide=();
                   1703:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1704: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1705:     }
1.351     www      1706:     my %returnhash=();
                   1707:     my %dumphash=
                   1708:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1709:     my $now=time;
                   1710:     foreach (keys %dumphash) {
                   1711: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1712:         if (($tstart) && ($tstart<0)) { next; }
                   1713:         if (($tend) && ($tend<$now)) { next; }
                   1714:         if (($tstart) && ($now<$tstart)) { next; }
                   1715:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1716: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1717: 	if ((&privileged($username,$domain)) && 
                   1718: 	    (!$nothide{$username.':'.$domain})) { next; }
1.351     www      1719:         my $key=&plaintext($role);
                   1720:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1721:         if ($returnhash{$key}) {
                   1722: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1723:         } else {
                   1724:             $returnhash{$key}=$username.':'.$domain;
                   1725:         }
1.400     www      1726:      }
                   1727:     return %returnhash;
                   1728: }
                   1729: 
                   1730: sub get_my_roles {
                   1731:     my ($uname,$udom)=@_;
1.620     albertel 1732:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1733:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1734:     my %dumphash=
                   1735:             &dump('nohist_userroles',$udom,$uname);
                   1736:     my %returnhash=();
                   1737:     my $now=time;
                   1738:     foreach (keys %dumphash) {
                   1739: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1740:         if (($tstart) && ($tstart<0)) { next; }
                   1741:         if (($tend) && ($tend<$now)) { next; }
                   1742:         if (($tstart) && ($now<$tstart)) { next; }
                   1743:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1744: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1745:      }
                   1746:     return %returnhash;
1.399     www      1747: }
                   1748: 
                   1749: # ----------------------------------------------------- Frontpage Announcements
                   1750: #
                   1751: #
                   1752: 
                   1753: sub postannounce {
                   1754:     my ($server,$text)=@_;
                   1755:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1756:     unless ($text=~/\w/) { $text=''; }
                   1757:     return &reply('setannounce:'.&escape($text),$server);
                   1758: }
                   1759: 
                   1760: sub getannounce {
1.448     albertel 1761: 
                   1762:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1763: 	my $announcement='';
                   1764: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1765: 	close($fh);
1.399     www      1766: 	if ($announcement=~/\w/) { 
                   1767: 	    return 
                   1768:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1769:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1770: 	} else {
                   1771: 	    return '';
                   1772: 	}
                   1773:     } else {
                   1774: 	return '';
                   1775:     }
1.351     www      1776: }
1.353     www      1777: 
                   1778: # ---------------------------------------------------------- Course ID routines
                   1779: # Deal with domain's nohist_courseid.db files
                   1780: #
                   1781: 
                   1782: sub courseidput {
                   1783:     my ($domain,$what,$coursehome)=@_;
                   1784:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1785: }
                   1786: 
                   1787: sub courseiddump {
1.622     raeburn  1788:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353     www      1789:     my %returnhash=();
1.355     www      1790:     unless ($domfilter) { $domfilter=''; }
1.353     www      1791:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1792:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1793: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1794: 	        foreach (
                   1795:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1796: 			       $sincefilter.':'.&escape($descfilter).':'.
1.622     raeburn  1797:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354     www      1798:                                $tryserver))) {
1.506     raeburn  1799: 		    my ($key,$value)=split(/\=/,$_);
                   1800:                     if (($key) && ($value)) {
1.516     raeburn  1801: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1802:                     }
1.353     www      1803:                 }
                   1804:             }
                   1805:         }
                   1806:     }
                   1807:     return %returnhash;
                   1808: }
                   1809: 
                   1810: #
1.149     www      1811: # ----------------------------------------------------------- Check out an item
                   1812: 
1.504     albertel 1813: sub get_first_access {
                   1814:     my ($type,$argsymb)=@_;
                   1815:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   1816:     if ($argsymb) { $symb=$argsymb; }
                   1817:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 1818:     if ($type eq 'map') {
                   1819: 	$res=&symbread($map);
                   1820:     } else {
                   1821: 	$res=$symb;
                   1822:     }
                   1823:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   1824:     return $times{"$courseid\0$res"};
1.504     albertel 1825: }
                   1826: 
                   1827: sub set_first_access {
                   1828:     my ($type)=@_;
                   1829:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   1830:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 1831:     if ($type eq 'map') {
                   1832: 	$res=&symbread($map);
                   1833:     } else {
                   1834: 	$res=$symb;
                   1835:     }
                   1836:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 1837:     if (!$firstaccess) {
1.588     albertel 1838: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 1839:     }
                   1840:     return 'already_set';
1.504     albertel 1841: }
                   1842: 
1.149     www      1843: sub checkout {
                   1844:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   1845:     my $now=time;
                   1846:     my $lonhost=$perlvar{'lonHostID'};
                   1847:     my $infostr=&escape(
1.234     www      1848:                  'CHECKOUTTOKEN&'.
1.149     www      1849:                  $tuname.'&'.
                   1850:                  $tudom.'&'.
                   1851:                  $tcrsid.'&'.
                   1852:                  $symb.'&'.
                   1853: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   1854:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      1855:     if ($token=~/^error\:/) { 
                   1856:         &logthis("<font color=blue>WARNING: ".
                   1857:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1858:                  "</font>");
                   1859:         return ''; 
                   1860:     }
                   1861: 
1.149     www      1862:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   1863:     $token=~tr/a-z/A-Z/;
                   1864: 
1.153     www      1865:     my %infohash=('resource.0.outtoken' => $token,
                   1866:                   'resource.0.checkouttime' => $now,
                   1867:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      1868: 
                   1869:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1870:        return '';
1.151     www      1871:     } else {
                   1872:         &logthis("<font color=blue>WARNING: ".
                   1873:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1874:                  "</font>");
1.149     www      1875:     }    
                   1876: 
                   1877:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1878:                          &escape('Checkout '.$infostr.' - '.
                   1879:                                                  $token)) ne 'ok') {
                   1880: 	return '';
1.151     www      1881:     } else {
                   1882:         &logthis("<font color=blue>WARNING: ".
                   1883:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1884:                  "</font>");
1.149     www      1885:     }
1.151     www      1886:     return $token;
1.149     www      1887: }
                   1888: 
                   1889: # ------------------------------------------------------------ Check in an item
                   1890: 
                   1891: sub checkin {
                   1892:     my $token=shift;
1.150     www      1893:     my $now=time;
                   1894:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   1895:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 1896:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      1897:     $dtoken=~s/\W/\_/g;
1.234     www      1898:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      1899:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   1900: 
1.154     www      1901:     unless (($tuname) && ($tudom)) {
                   1902:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   1903:         return '';
                   1904:     }
                   1905:     
                   1906:     unless (&allowed('mgr',$tcrsid)) {
                   1907:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 1908:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      1909:         return '';
                   1910:     }
                   1911: 
1.153     www      1912:     my %infohash=('resource.0.intoken' => $token,
                   1913:                   'resource.0.checkintime' => $now,
                   1914:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      1915: 
                   1916:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1917:        return '';
                   1918:     }    
                   1919: 
                   1920:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1921:                          &escape('Checkin - '.$token)) ne 'ok') {
                   1922: 	return '';
                   1923:     }
                   1924: 
                   1925:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      1926: }
                   1927: 
                   1928: # --------------------------------------------- Set Expire Date for Spreadsheet
                   1929: 
                   1930: sub expirespread {
                   1931:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 1932:     my $cid=$env{'request.course.id'}; 
1.110     www      1933:     if ($cid) {
                   1934:        my $now=time;
                   1935:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 1936:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   1937:                             $env{'course.'.$cid.'.num'}.
1.110     www      1938: 	        	    ':nohist_expirationdates:'.
                   1939:                             &escape($key).'='.$now,
1.620     albertel 1940:                             $env{'course.'.$cid.'.home'})
1.110     www      1941:     }
                   1942:     return 'ok';
1.14      www      1943: }
                   1944: 
1.109     www      1945: # ----------------------------------------------------- Devalidate Spreadsheets
                   1946: 
                   1947: sub devalidate {
1.325     www      1948:     my ($symb,$uname,$udom)=@_;
1.620     albertel 1949:     my $cid=$env{'request.course.id'}; 
1.109     www      1950:     if ($cid) {
1.391     matthew  1951:         # delete the stored spreadsheets for
                   1952:         # - the student level sheet of this user in course's homespace
                   1953:         # - the assessment level sheet for this resource 
                   1954:         #   for this user in user's homespace
1.553     albertel 1955: 	# - current conditional state info
1.325     www      1956: 	my $key=$uname.':'.$udom.':';
1.109     www      1957:         my $status=
1.299     matthew  1958: 	    &del('nohist_calculatedsheets',
1.391     matthew  1959: 		 [$key.'studentcalc:'],
1.620     albertel 1960: 		 $env{'course.'.$cid.'.domain'},
                   1961: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 1962: 		.' '.
                   1963: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  1964: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      1965:         unless ($status eq 'ok ok') {
                   1966:            &logthis('Could not devalidate spreadsheet '.
1.325     www      1967:                     $uname.' at '.$udom.' for '.
1.109     www      1968: 		    $symb.': '.$status);
1.133     albertel 1969:         }
1.553     albertel 1970: 	&delenv('user.state.'.$cid);
1.109     www      1971:     }
                   1972: }
                   1973: 
1.265     albertel 1974: sub get_scalar {
                   1975:     my ($string,$end) = @_;
                   1976:     my $value;
                   1977:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   1978: 	$value = $1;
                   1979:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   1980: 	$value = $1;
                   1981:     }
                   1982:     return &unescape($value);
                   1983: }
                   1984: 
                   1985: sub array2str {
                   1986:   my (@array) = @_;
                   1987:   my $result=&arrayref2str(\@array);
                   1988:   $result=~s/^__ARRAY_REF__//;
                   1989:   $result=~s/__END_ARRAY_REF__$//;
                   1990:   return $result;
                   1991: }
                   1992: 
1.204     albertel 1993: sub arrayref2str {
                   1994:   my ($arrayref) = @_;
1.265     albertel 1995:   my $result='__ARRAY_REF__';
1.204     albertel 1996:   foreach my $elem (@$arrayref) {
1.265     albertel 1997:     if(ref($elem) eq 'ARRAY') {
                   1998:       $result.=&arrayref2str($elem).'&';
                   1999:     } elsif(ref($elem) eq 'HASH') {
                   2000:       $result.=&hashref2str($elem).'&';
                   2001:     } elsif(ref($elem)) {
                   2002:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2003:     } else {
                   2004:       $result.=&escape($elem).'&';
                   2005:     }
                   2006:   }
                   2007:   $result=~s/\&$//;
1.265     albertel 2008:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2009:   return $result;
                   2010: }
                   2011: 
1.168     albertel 2012: sub hash2str {
1.204     albertel 2013:   my (%hash) = @_;
                   2014:   my $result=&hashref2str(\%hash);
1.265     albertel 2015:   $result=~s/^__HASH_REF__//;
                   2016:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2017:   return $result;
                   2018: }
                   2019: 
                   2020: sub hashref2str {
                   2021:   my ($hashref)=@_;
1.265     albertel 2022:   my $result='__HASH_REF__';
1.495     albertel 2023:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2024:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2025:       $result.=&arrayref2str($_).'=';
1.204     albertel 2026:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2027:       $result.=&hashref2str($_).'=';
1.204     albertel 2028:     } elsif (ref($_)) {
1.265     albertel 2029:       $result.='=';
                   2030:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2031:     } else {
1.265     albertel 2032: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2033:     }
                   2034: 
1.265     albertel 2035:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2036:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2037:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2038:       $result.=&hashref2str($hashref->{$_}).'&';
                   2039:     } elsif(ref($hashref->{$_})) {
                   2040:        $result.='&';
                   2041:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2042:     } else {
1.265     albertel 2043:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2044:     }
                   2045:   }
1.168     albertel 2046:   $result=~s/\&$//;
1.265     albertel 2047:   $result .= '__END_HASH_REF__';
1.168     albertel 2048:   return $result;
                   2049: }
                   2050: 
                   2051: sub str2hash {
1.265     albertel 2052:     my ($string)=@_;
                   2053:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2054:     return %$hash;
                   2055: }
                   2056: 
                   2057: sub str2hashref {
1.168     albertel 2058:   my ($string) = @_;
1.265     albertel 2059: 
                   2060:   my %hash;
                   2061: 
                   2062:   if($string !~ /^__HASH_REF__/) {
                   2063:       if (! ($string eq '' || !defined($string))) {
                   2064: 	  $hash{'error'}='Not hash reference';
                   2065:       }
                   2066:       return (\%hash, $string);
                   2067:   }
                   2068: 
                   2069:   $string =~ s/^__HASH_REF__//;
                   2070: 
                   2071:   while($string !~ /^__END_HASH_REF__/) {
                   2072:       #key
                   2073:       my $key='';
                   2074:       if($string =~ /^__HASH_REF__/) {
                   2075:           ($key, $string)=&str2hashref($string);
                   2076:           if(defined($key->{'error'})) {
                   2077:               $hash{'error'}='Bad data';
                   2078:               return (\%hash, $string);
                   2079:           }
                   2080:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2081:           ($key, $string)=&str2arrayref($string);
                   2082:           if($key->[0] eq 'Array reference error') {
                   2083:               $hash{'error'}='Bad data';
                   2084:               return (\%hash, $string);
                   2085:           }
                   2086:       } else {
                   2087:           $string =~ s/^(.*?)=//;
1.267     albertel 2088: 	  $key=&unescape($1);
1.265     albertel 2089:       }
                   2090:       $string =~ s/^=//;
                   2091: 
                   2092:       #value
                   2093:       my $value='';
                   2094:       if($string =~ /^__HASH_REF__/) {
                   2095:           ($value, $string)=&str2hashref($string);
                   2096:           if(defined($value->{'error'})) {
                   2097:               $hash{'error'}='Bad data';
                   2098:               return (\%hash, $string);
                   2099:           }
                   2100:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2101:           ($value, $string)=&str2arrayref($string);
                   2102:           if($value->[0] eq 'Array reference error') {
                   2103:               $hash{'error'}='Bad data';
                   2104:               return (\%hash, $string);
                   2105:           }
                   2106:       } else {
                   2107: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2108:       }
                   2109:       $string =~ s/^&//;
                   2110: 
                   2111:       $hash{$key}=$value;
1.204     albertel 2112:   }
1.265     albertel 2113: 
                   2114:   $string =~ s/^__END_HASH_REF__//;
                   2115: 
                   2116:   return (\%hash, $string);
1.204     albertel 2117: }
                   2118: 
                   2119: sub str2array {
1.265     albertel 2120:     my ($string)=@_;
                   2121:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2122:     return @$array;
                   2123: }
                   2124: 
                   2125: sub str2arrayref {
1.204     albertel 2126:   my ($string) = @_;
1.265     albertel 2127:   my @array;
                   2128: 
                   2129:   if($string !~ /^__ARRAY_REF__/) {
                   2130:       if (! ($string eq '' || !defined($string))) {
                   2131: 	  $array[0]='Array reference error';
                   2132:       }
                   2133:       return (\@array, $string);
                   2134:   }
                   2135: 
                   2136:   $string =~ s/^__ARRAY_REF__//;
                   2137: 
                   2138:   while($string !~ /^__END_ARRAY_REF__/) {
                   2139:       my $value='';
                   2140:       if($string =~ /^__HASH_REF__/) {
                   2141:           ($value, $string)=&str2hashref($string);
                   2142:           if(defined($value->{'error'})) {
                   2143:               $array[0] ='Array reference error';
                   2144:               return (\@array, $string);
                   2145:           }
                   2146:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2147:           ($value, $string)=&str2arrayref($string);
                   2148:           if($value->[0] eq 'Array reference error') {
                   2149:               $array[0] ='Array reference error';
                   2150:               return (\@array, $string);
                   2151:           }
                   2152:       } else {
                   2153: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2154:       }
                   2155:       $string =~ s/^&//;
                   2156: 
                   2157:       push(@array, $value);
1.191     harris41 2158:   }
1.265     albertel 2159: 
                   2160:   $string =~ s/^__END_ARRAY_REF__//;
                   2161: 
                   2162:   return (\@array, $string);
1.168     albertel 2163: }
                   2164: 
1.167     albertel 2165: # -------------------------------------------------------------------Temp Store
                   2166: 
1.168     albertel 2167: sub tmpreset {
                   2168:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2169:   if (!$symb) {
                   2170:     $symb=&symbread();
1.620     albertel 2171:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2172:   }
                   2173:   $symb=escape($symb);
                   2174: 
1.620     albertel 2175:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2176:   $namespace=~s/\//\_/g;
                   2177:   $namespace=~s/\W//g;
                   2178: 
1.620     albertel 2179:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2180:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2181:   if ($domain eq 'public' && $stuname eq 'public') {
                   2182:       $stuname=$ENV{'REMOTE_ADDR'};
                   2183:   }
1.168     albertel 2184:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2185:   my %hash;
                   2186:   if (tie(%hash,'GDBM_File',
                   2187: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2188: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2189:     foreach my $key (keys %hash) {
1.180     albertel 2190:       if ($key=~ /:$symb/) {
1.168     albertel 2191: 	delete($hash{$key});
                   2192:       }
                   2193:     }
                   2194:   }
                   2195: }
                   2196: 
1.167     albertel 2197: sub tmpstore {
1.168     albertel 2198:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2199: 
                   2200:   if (!$symb) {
                   2201:     $symb=&symbread();
1.620     albertel 2202:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2203:   }
                   2204:   $symb=escape($symb);
                   2205: 
                   2206:   if (!$namespace) {
                   2207:     # I don't think we would ever want to store this for a course.
                   2208:     # it seems this will only be used if we don't have a course.
1.620     albertel 2209:     #$namespace=$env{'request.course.id'};
1.168     albertel 2210:     #if (!$namespace) {
1.620     albertel 2211:       $namespace=$env{'request.state'};
1.168     albertel 2212:     #}
                   2213:   }
                   2214:   $namespace=~s/\//\_/g;
                   2215:   $namespace=~s/\W//g;
1.620     albertel 2216:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2217:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2218:   if ($domain eq 'public' && $stuname eq 'public') {
                   2219:       $stuname=$ENV{'REMOTE_ADDR'};
                   2220:   }
1.168     albertel 2221:   my $now=time;
                   2222:   my %hash;
                   2223:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2224:   if (tie(%hash,'GDBM_File',
                   2225: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2226: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2227:     $hash{"version:$symb"}++;
                   2228:     my $version=$hash{"version:$symb"};
                   2229:     my $allkeys=''; 
                   2230:     foreach my $key (keys(%$storehash)) {
                   2231:       $allkeys.=$key.':';
1.591     albertel 2232:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2233:     }
                   2234:     $hash{"$version:$symb:timestamp"}=$now;
                   2235:     $allkeys.='timestamp';
                   2236:     $hash{"$version:keys:$symb"}=$allkeys;
                   2237:     if (untie(%hash)) {
                   2238:       return 'ok';
                   2239:     } else {
                   2240:       return "error:$!";
                   2241:     }
                   2242:   } else {
                   2243:     return "error:$!";
                   2244:   }
                   2245: }
1.167     albertel 2246: 
1.168     albertel 2247: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2248: 
1.168     albertel 2249: sub tmprestore {
                   2250:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2251: 
1.168     albertel 2252:   if (!$symb) {
                   2253:     $symb=&symbread();
1.620     albertel 2254:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2255:   }
                   2256:   $symb=escape($symb);
                   2257: 
1.620     albertel 2258:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2259: 
1.620     albertel 2260:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2261:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2262:   if ($domain eq 'public' && $stuname eq 'public') {
                   2263:       $stuname=$ENV{'REMOTE_ADDR'};
                   2264:   }
1.168     albertel 2265:   my %returnhash;
                   2266:   $namespace=~s/\//\_/g;
                   2267:   $namespace=~s/\W//g;
                   2268:   my %hash;
                   2269:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2270:   if (tie(%hash,'GDBM_File',
                   2271: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2272: 	  &GDBM_READER(),0640)) {
1.168     albertel 2273:     my $version=$hash{"version:$symb"};
                   2274:     $returnhash{'version'}=$version;
                   2275:     my $scope;
                   2276:     for ($scope=1;$scope<=$version;$scope++) {
                   2277:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2278:       my @keys=split(/:/,$vkeys);
                   2279:       my $key;
                   2280:       $returnhash{"$scope:keys"}=$vkeys;
                   2281:       foreach $key (@keys) {
1.591     albertel 2282: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2283: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2284:       }
                   2285:     }
1.168     albertel 2286:     if (!(untie(%hash))) {
                   2287:       return "error:$!";
                   2288:     }
                   2289:   } else {
                   2290:     return "error:$!";
                   2291:   }
                   2292:   return %returnhash;
1.167     albertel 2293: }
                   2294: 
1.9       www      2295: # ----------------------------------------------------------------------- Store
                   2296: 
                   2297: sub store {
1.124     www      2298:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2299:     my $home='';
                   2300: 
1.168     albertel 2301:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2302: 
1.213     www      2303:     $symb=&symbclean($symb);
1.122     albertel 2304:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2305: 
1.620     albertel 2306:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2307:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2308: 
                   2309:     &devalidate($symb,$stuname,$domain);
1.109     www      2310: 
                   2311:     $symb=escape($symb);
1.187     www      2312:     if (!$namespace) { 
1.620     albertel 2313:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2314:           return ''; 
                   2315:        } 
                   2316:     }
1.620     albertel 2317:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2318: 
                   2319:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2320:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2321: 
1.12      www      2322:     my $namevalue='';
1.191     harris41 2323:     foreach (keys %$storehash) {
1.591     albertel 2324:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2325:     }
1.12      www      2326:     $namevalue=~s/\&$//;
1.187     www      2327:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2328:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2329: }
                   2330: 
1.47      www      2331: # -------------------------------------------------------------- Critical Store
                   2332: 
                   2333: sub cstore {
1.124     www      2334:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2335:     my $home='';
                   2336: 
1.168     albertel 2337:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2338: 
1.213     www      2339:     $symb=&symbclean($symb);
1.122     albertel 2340:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2341: 
1.620     albertel 2342:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2343:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2344: 
                   2345:     &devalidate($symb,$stuname,$domain);
1.109     www      2346: 
                   2347:     $symb=escape($symb);
1.187     www      2348:     if (!$namespace) { 
1.620     albertel 2349:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2350:           return ''; 
                   2351:        } 
                   2352:     }
1.620     albertel 2353:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2354: 
                   2355:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2356:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2357: 
1.47      www      2358:     my $namevalue='';
1.191     harris41 2359:     foreach (keys %$storehash) {
1.591     albertel 2360:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2361:     }
1.47      www      2362:     $namevalue=~s/\&$//;
1.187     www      2363:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2364:     return critical
                   2365:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2366: }
                   2367: 
1.9       www      2368: # --------------------------------------------------------------------- Restore
                   2369: 
                   2370: sub restore {
1.124     www      2371:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2372:     my $home='';
                   2373: 
1.168     albertel 2374:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2375: 
1.122     albertel 2376:     if (!$symb) {
                   2377:       unless ($symb=escape(&symbread())) { return ''; }
                   2378:     } else {
1.213     www      2379:       $symb=&escape(&symbclean($symb));
1.122     albertel 2380:     }
1.188     www      2381:     if (!$namespace) { 
1.620     albertel 2382:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2383:           return ''; 
                   2384:        } 
                   2385:     }
1.620     albertel 2386:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2387:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2388:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2389:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2390: 
1.12      www      2391:     my %returnhash=();
1.191     harris41 2392:     foreach (split(/\&/,$answer)) {
1.12      www      2393: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2394:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2395:     }
1.75      www      2396:     my $version;
                   2397:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2398:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2399:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2400:        }
1.75      www      2401:     }
1.13      www      2402:     return %returnhash;
1.34      www      2403: }
                   2404: 
                   2405: # ---------------------------------------------------------- Course Description
                   2406: 
                   2407: sub coursedescription {
                   2408:     my $courseid=shift;
                   2409:     $courseid=~s/^\///;
1.49      www      2410:     $courseid=~s/\_/\//g;
1.34      www      2411:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2412:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2413:     my $normalid=$cdomain.'_'.$cnum;
                   2414:     # need to always cache even if we get errors otherwise we keep 
                   2415:     # trying and trying and trying to get the course description.
                   2416:     my %envhash=();
                   2417:     my %returnhash=();
                   2418:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      2419:     if ($chome ne 'no_host') {
1.302     albertel 2420:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2421:        if (!exists($returnhash{'con_lost'})) {
                   2422:            $returnhash{'home'}= $chome;
                   2423: 	   $returnhash{'domain'} = $cdomain;
                   2424: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2425:            while (my ($name,$value) = each %returnhash) {
1.53      www      2426:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2427:            }
1.270     www      2428:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2429:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2430: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2431:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2432:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2433:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2434:        }
                   2435:     }
1.302     albertel 2436:     &appenv(%envhash);
                   2437:     return %returnhash;
1.461     www      2438: }
                   2439: 
                   2440: # -------------------------------------------------See if a user is privileged
                   2441: 
                   2442: sub privileged {
                   2443:     my ($username,$domain)=@_;
                   2444:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2445: 			&homeserver($username,$domain));
                   2446:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2447:     my $now=time;
                   2448:     if ($rolesdump ne '') {
                   2449:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2450: 	    if ($_!~/^rolesdef_/) {
1.461     www      2451: 		my ($area,$role)=split(/=/,$_);
                   2452: 		$area=~s/\_\w\w$//;
                   2453: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2454: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2455: 		    my $active=1;
                   2456: 		    if ($tend) {
                   2457: 			if ($tend<$now) { $active=0; }
                   2458: 		    }
                   2459: 		    if ($tstart) {
                   2460: 			if ($tstart>$now) { $active=0; }
                   2461: 		    }
                   2462: 		    if ($active) { return 1; }
                   2463: 		}
                   2464: 	    }
                   2465: 	}
                   2466:     }
                   2467:     return 0;
1.9       www      2468: }
1.1       albertel 2469: 
1.103     harris41 2470: # -------------------------------------------------------- Get user privileges
1.11      www      2471: 
                   2472: sub rolesinit {
                   2473:     my ($domain,$username,$authhost)=@_;
                   2474:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2475:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2476:     my %allroles=();
                   2477:     my $now=time;
1.21      www      2478:     my $userroles="user.login.time=$now\n";
1.11      www      2479: 
                   2480:     if ($rolesdump ne '') {
1.191     harris41 2481:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2482: 	  if ($_!~/^rolesdef_/) {
1.11      www      2483:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2484: 	    $area=~s/\_\w\w$//;
                   2485: 	    
                   2486:             my ($trole,$tend,$tstart);
                   2487: 	    if ($role=~/^cr/) { 
                   2488: 		($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2489: 		($tend,$tstart)=split('_',$trest);
                   2490: 	    } else {
                   2491: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2492: 	    }
1.576     albertel 2493:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567     raeburn  2494:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2495:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2496:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2497: 		my $spec=$trole.'.'.$area;
                   2498: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2499: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2500:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.347     albertel 2501: 		} else {
1.567     raeburn  2502:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2503: 		}
1.12      www      2504:             }
                   2505:           } 
1.191     harris41 2506:         }
1.567     raeburn  2507:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles);
1.128     www      2508:         $userroles.='user.adv='.$adv."\n".
                   2509: 	            'user.author='.$author."\n";
1.620     albertel 2510:         $env{'user.adv'}=$adv;
1.11      www      2511:     }
                   2512:     return $userroles;  
                   2513: }
                   2514: 
1.567     raeburn  2515: sub set_arearole {
                   2516:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2517: # log the associated role with the area
                   2518:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   2519:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
                   2520: }
                   2521: 
                   2522: sub custom_roleprivs {
                   2523:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2524:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2525:     my $homsvr=homeserver($rauthor,$rdomain);
                   2526:     if ($hostname{$homsvr} ne '') {
                   2527:         my ($rdummy,$roledef)=
                   2528:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2529:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2530:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2531:             if (defined($syspriv)) {
                   2532:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2533:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2534:             }
                   2535:             if ($tdomain ne '') {
                   2536:                 if (defined($dompriv)) {
                   2537:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2538:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2539:                 }
                   2540:                 if (($trest ne '') && (defined($coursepriv))) {
                   2541:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2542:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2543:                 }
                   2544:             }
                   2545:         }
                   2546:     }
                   2547: }
                   2548: 
                   2549: 
                   2550: sub standard_roleprivs {
                   2551:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2552:     if (defined($pr{$trole.':s'})) {
                   2553:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2554:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2555:     }
                   2556:     if ($tdomain ne '') {
                   2557:         if (defined($pr{$trole.':d'})) {
                   2558:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2559:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2560:         }
                   2561:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2562:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2563:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2564:         }
                   2565:     }
                   2566: }
                   2567: 
                   2568: sub set_userprivs {
                   2569:     my ($userroles,$allroles) = @_; 
                   2570:     my $author=0;
                   2571:     my $adv=0;
                   2572:     foreach (keys %{$allroles}) {
                   2573:         my %thesepriv=();
                   2574:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2575:         foreach (split(/:/,$$allroles{$_})) {
                   2576:             if ($_ ne '') {
                   2577:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2578:                 if ($restrictions eq '') {
                   2579:                     $thesepriv{$privilege}='F';
                   2580:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2581:                     $thesepriv{$privilege}.=$restrictions;
                   2582:                 }
                   2583:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2584:             }
                   2585:         }
                   2586:         my $thesestr='';
                   2587:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
                   2588:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
                   2589:     }
                   2590:     return ($author,$adv);
                   2591: }
                   2592: 
1.12      www      2593: # --------------------------------------------------------------- get interface
                   2594: 
                   2595: sub get {
1.131     albertel 2596:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2597:    my $items='';
1.191     harris41 2598:    foreach (@$storearr) {
1.12      www      2599:        $items.=escape($_).'&';
1.191     harris41 2600:    }
1.12      www      2601:    $items=~s/\&$//;
1.620     albertel 2602:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2603:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2604:    my $uhome=&homeserver($uname,$udomain);
                   2605: 
1.133     albertel 2606:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2607:    my @pairs=split(/\&/,$rep);
1.273     albertel 2608:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2609:      return @pairs;
                   2610:    }
1.15      www      2611:    my %returnhash=();
1.42      www      2612:    my $i=0;
1.191     harris41 2613:    foreach (@$storearr) {
1.557     albertel 2614:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2615:       $i++;
1.191     harris41 2616:    }
1.15      www      2617:    return %returnhash;
1.27      www      2618: }
                   2619: 
                   2620: # --------------------------------------------------------------- del interface
                   2621: 
                   2622: sub del {
1.133     albertel 2623:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2624:    my $items='';
1.191     harris41 2625:    foreach (@$storearr) {
1.27      www      2626:        $items.=escape($_).'&';
1.191     harris41 2627:    }
1.27      www      2628:    $items=~s/\&$//;
1.620     albertel 2629:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2630:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2631:    my $uhome=&homeserver($uname,$udomain);
                   2632: 
                   2633:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2634: }
                   2635: 
                   2636: # -------------------------------------------------------------- dump interface
                   2637: 
                   2638: sub dump {
1.193     www      2639:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.620     albertel 2640:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2641:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2642:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2643:    if ($regexp) {
                   2644:        $regexp=&escape($regexp);
                   2645:    } else {
                   2646:        $regexp='.';
                   2647:    }
                   2648:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      2649:    my @pairs=split(/\&/,$rep);
                   2650:    my %returnhash=();
1.191     harris41 2651:    foreach (@pairs) {
1.12      www      2652:       my ($key,$value)=split(/=/,$_);
1.557     albertel 2653:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2654:    }
                   2655:    return %returnhash;
1.407     www      2656: }
                   2657: 
                   2658: # -------------------------------------------------------------- keys interface
                   2659: 
                   2660: sub getkeys {
                   2661:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2662:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2663:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2664:    my $uhome=&homeserver($uname,$udomain);
                   2665:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2666:    my @keyarray=();
                   2667:    foreach (split(/\&/,$rep)) {
                   2668:       push (@keyarray,&unescape($_));
                   2669:    }
                   2670:    return @keyarray;
1.318     matthew  2671: }
                   2672: 
1.319     matthew  2673: # --------------------------------------------------------------- currentdump
                   2674: sub currentdump {
1.328     matthew  2675:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2676:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2677:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2678:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2679:    my $uhome = &homeserver($sname,$sdom);
                   2680:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2681:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2682:    #
1.318     matthew  2683:    my %returnhash=();
1.319     matthew  2684:    #
                   2685:    if ($rep eq "unknown_cmd") { 
                   2686:        # an old lond will not know currentdump
                   2687:        # Do a dump and make it look like a currentdump
1.326     matthew  2688:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2689:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2690:        my %hash = @tmp;
                   2691:        @tmp=();
1.424     matthew  2692:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2693:    } else {
                   2694:        my @pairs=split(/\&/,$rep);
                   2695:        foreach (@pairs) {
                   2696:            my ($key,$value)=split(/=/,$_);
                   2697:            my ($symb,$param) = split(/:/,$key);
                   2698:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2699:                                                         &thaw_unescape($value);
1.319     matthew  2700:        }
1.191     harris41 2701:    }
1.12      www      2702:    return %returnhash;
1.424     matthew  2703: }
                   2704: 
                   2705: sub convert_dump_to_currentdump{
                   2706:     my %hash = %{shift()};
                   2707:     my %returnhash;
                   2708:     # Code ripped from lond, essentially.  The only difference
                   2709:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2710:     # we might run in to problems with parameter names =~ /^v\./
                   2711:     while (my ($key,$value) = each(%hash)) {
                   2712:         my ($v,$symb,$param) = split(/:/,$key);
                   2713:         next if ($v eq 'version' || $symb eq 'keys');
                   2714:         next if (exists($returnhash{$symb}) &&
                   2715:                  exists($returnhash{$symb}->{$param}) &&
                   2716:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2717:         $returnhash{$symb}->{$param}=$value;
                   2718:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2719:     }
                   2720:     #
                   2721:     # Remove all of the keys in the hashes which keep track of
                   2722:     # the version of the parameter.
                   2723:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2724:         # use a foreach because we are going to delete from the hash.
                   2725:         foreach my $key (keys(%$param_hash)) {
                   2726:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2727:         }
                   2728:     }
                   2729:     return \%returnhash;
1.12      www      2730: }
                   2731: 
1.627     albertel 2732: # ------------------------------------------------------ critical inc interface
                   2733: 
                   2734: sub cinc {
                   2735:     return &inc(@_,'critical');
                   2736: }
                   2737: 
1.449     matthew  2738: # --------------------------------------------------------------- inc interface
                   2739: 
                   2740: sub inc {
1.627     albertel 2741:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 2742:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2743:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  2744:     my $uhome=&homeserver($uname,$udomain);
                   2745:     my $items='';
                   2746:     if (! ref($store)) {
                   2747:         # got a single value, so use that instead
                   2748:         $items = &escape($store).'=&';
                   2749:     } elsif (ref($store) eq 'SCALAR') {
                   2750:         $items = &escape($$store).'=&';        
                   2751:     } elsif (ref($store) eq 'ARRAY') {
                   2752:         $items = join('=&',map {&escape($_);} @{$store});
                   2753:     } elsif (ref($store) eq 'HASH') {
                   2754:         while (my($key,$value) = each(%{$store})) {
                   2755:             $items.= &escape($key).'='.&escape($value).'&';
                   2756:         }
                   2757:     }
                   2758:     $items=~s/\&$//;
1.627     albertel 2759:     if ($critical) {
                   2760: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2761:     } else {
                   2762: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2763:     }
1.449     matthew  2764: }
                   2765: 
1.12      www      2766: # --------------------------------------------------------------- put interface
                   2767: 
                   2768: sub put {
1.134     albertel 2769:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2770:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2771:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 2772:    my $uhome=&homeserver($uname,$udomain);
1.12      www      2773:    my $items='';
1.191     harris41 2774:    foreach (keys %$storehash) {
1.557     albertel 2775:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2776:    }
1.12      www      2777:    $items=~s/\&$//;
1.134     albertel 2778:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      2779: }
                   2780: 
1.631     albertel 2781: # ------------------------------------------------------------ newput interface
                   2782: 
                   2783: sub newput {
                   2784:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2785:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2786:    if (!$uname) { $uname=$env{'user.name'}; }
                   2787:    my $uhome=&homeserver($uname,$udomain);
                   2788:    my $items='';
                   2789:    foreach my $key (keys(%$storehash)) {
                   2790:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2791:    }
                   2792:    $items=~s/\&$//;
                   2793:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   2794: }
                   2795: 
                   2796: # ---------------------------------------------------------  putstore interface
                   2797: 
1.524     raeburn  2798: sub putstore {
                   2799:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2800:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2801:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  2802:    my $uhome=&homeserver($uname,$udomain);
                   2803:    my $items='';
                   2804:    my %allitems = ();
                   2805:    foreach (keys %$storehash) {
                   2806:        if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   2807:            my $key = $1.':keys:'.$2;
                   2808:            $allitems{$key} .= $3.':';
                   2809:        }
1.591     albertel 2810:        $items.=$_.'='.&freeze_escape($$storehash{$_}).'&';
1.524     raeburn  2811:    }
                   2812:    foreach (keys %allitems) {
                   2813:        $allitems{$_} =~ s/\:$//;
                   2814:        $items.= $_.'='.$allitems{$_}.'&';
                   2815:    }
                   2816:    $items=~s/\&$//;
                   2817:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   2818: }
                   2819: 
1.47      www      2820: # ------------------------------------------------------ critical put interface
                   2821: 
                   2822: sub cput {
1.134     albertel 2823:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2824:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2825:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 2826:    my $uhome=&homeserver($uname,$udomain);
1.47      www      2827:    my $items='';
1.191     harris41 2828:    foreach (keys %$storehash) {
1.557     albertel 2829:        $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2830:    }
1.47      www      2831:    $items=~s/\&$//;
1.134     albertel 2832:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2833: }
                   2834: 
                   2835: # -------------------------------------------------------------- eget interface
                   2836: 
                   2837: sub eget {
1.133     albertel 2838:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2839:    my $items='';
1.191     harris41 2840:    foreach (@$storearr) {
1.12      www      2841:        $items.=escape($_).'&';
1.191     harris41 2842:    }
1.12      www      2843:    $items=~s/\&$//;
1.620     albertel 2844:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2845:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2846:    my $uhome=&homeserver($uname,$udomain);
                   2847:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2848:    my @pairs=split(/\&/,$rep);
                   2849:    my %returnhash=();
1.42      www      2850:    my $i=0;
1.191     harris41 2851:    foreach (@$storearr) {
1.557     albertel 2852:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2853:       $i++;
1.191     harris41 2854:    }
1.12      www      2855:    return %returnhash;
                   2856: }
                   2857: 
1.341     www      2858: # ---------------------------------------------- Custom access rule evaluation
                   2859: 
                   2860: sub customaccess {
                   2861:     my ($priv,$uri)=@_;
1.620     albertel 2862:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      2863:     $urealm=~s/^\W//;
                   2864:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      2865:     my $access=0;
                   2866:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      2867: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      2868:         if ($role) {
                   2869: 	   if ($role ne $urole) { next; }
                   2870:         }
                   2871:         foreach (split(/\s*\,\s*/,$realm)) {
                   2872:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   2873:             if ($tdom) {
                   2874: 		if ($tdom ne $udom) { next; }
                   2875:             }
                   2876:             if ($tcrs) {
                   2877: 		if ($tcrs ne $ucrs) { next; }
                   2878:             }
                   2879:             if ($tsec) {
                   2880: 		if ($tsec ne $usec) { next; }
                   2881:             }
                   2882:             $access=($effect eq 'allow');
                   2883:             last;
1.342     www      2884:         }
1.402     bowersj2 2885: 	if ($realm eq '' && $role eq '') {
                   2886:             $access=($effect eq 'allow');
                   2887: 	}
1.341     www      2888:     }
                   2889:     return $access;
                   2890: }
                   2891: 
1.103     harris41 2892: # ------------------------------------------------- Check for a user privilege
1.12      www      2893: 
                   2894: sub allowed {
1.579     albertel 2895:     my ($priv,$uri,$symb)=@_;
1.439     www      2896:     $uri=&deversion($uri);
1.152     www      2897:     my $orguri=$uri;
1.52      www      2898:     $uri=&declutter($uri);
1.545     banghart 2899:     
                   2900:     
                   2901:     
1.620     albertel 2902:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      2903: # Free bre access to adm and meta resources
1.529     albertel 2904:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   2905: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      2906: 	return 'F';
1.159     www      2907:     }
                   2908: 
1.545     banghart 2909: # Free bre access to user's own portfolio contents
1.546     albertel 2910:     my ($space,$domain,$name,$dir)=split('/',$uri);
1.647     raeburn  2911:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.620     albertel 2912: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
1.545     banghart 2913:         return 'F';
                   2914:     }
                   2915: 
1.159     www      2916: # Free bre to public access
                   2917: 
                   2918:     if ($priv eq 'bre') {
1.238     www      2919:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 2920: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      2921:            return 'F'; 
                   2922:         }
1.238     www      2923:         if ($copyright eq 'priv') {
                   2924:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 2925: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      2926: 		return '';
                   2927:             }
                   2928:         }
                   2929:         if ($copyright eq 'domain') {
                   2930:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 2931: 	    unless (($env{'user.domain'} eq $1) ||
                   2932:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      2933: 		return '';
                   2934:             }
1.262     matthew  2935:         }
1.620     albertel 2936:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  2937:             # Library role, so allow browsing of resources in this domain.
                   2938:             return 'F';
1.238     www      2939:         }
1.341     www      2940:         if ($copyright eq 'custom') {
                   2941: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   2942:         }
1.14      www      2943:     }
1.264     matthew  2944:     # Domain coordinator is trying to create a course
1.620     albertel 2945:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  2946:         # uri is the requested domain in this case.
                   2947:         # comparison to 'request.role.domain' shows if the user has selected
                   2948:         # a role of dc for the domain in question. 
1.620     albertel 2949:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  2950:     }
1.29      www      2951: 
1.52      www      2952:     my $thisallowed='';
                   2953:     my $statecond=0;
                   2954:     my $courseprivid='';
                   2955: 
                   2956: # Course
                   2957: 
1.620     albertel 2958:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      2959:        $thisallowed.=$1;
                   2960:     }
1.29      www      2961: 
1.52      www      2962: # Domain
                   2963: 
1.620     albertel 2964:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 2965:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      2966:        $thisallowed.=$1;
                   2967:     }
1.52      www      2968: 
                   2969: # Course: uri itself is a course
1.66      www      2970:     my $courseuri=$uri;
                   2971:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      2972:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      2973: 
1.620     albertel 2974:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 2975:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      2976:        $thisallowed.=$1;
                   2977:     }
1.29      www      2978: 
1.314     www      2979: # URI is an uploaded document for this course
1.611     albertel 2980: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 2981:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.620     albertel 2982: 	my $refuri=$env{'httpref.'.$orguri};
1.492     albertel 2983: 	if ($refuri) {
                   2984: 	    if ($refuri =~ m|^/adm/|) {
                   2985: 		$thisallowed='F';
                   2986: 	    }
                   2987: 	}
1.314     www      2988:     }
1.492     albertel 2989: 
1.52      www      2990: # Full access at system, domain or course-wide level? Exit.
1.29      www      2991: 
                   2992:     if ($thisallowed=~/F/) {
                   2993: 	return 'F';
                   2994:     }
                   2995: 
1.52      www      2996: # If this is generating or modifying users, exit with special codes
1.29      www      2997: 
1.643     www      2998:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   2999: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3000: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3001: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3002: 	    unless ($auname) { return $thisallowed; }
                   3003: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3004: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3005: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3006: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3007: 	}
1.52      www      3008: 	return $thisallowed;
                   3009:     }
                   3010: #
1.103     harris41 3011: # Gathered so far: system, domain and course wide privileges
1.52      www      3012: #
                   3013: # Course: See if uri or referer is an individual resource that is part of 
                   3014: # the course
                   3015: 
1.620     albertel 3016:     if ($env{'request.course.id'}) {
1.232     www      3017: 
1.620     albertel 3018:        $courseprivid=$env{'request.course.id'};
                   3019:        if ($env{'request.course.sec'}) {
                   3020:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3021:        }
                   3022:        $courseprivid=~s/\_/\//;
                   3023:        my $checkreferer=1;
1.232     www      3024:        my ($match,$cond)=&is_on_map($uri);
                   3025:        if ($match) {
                   3026:            $statecond=$cond;
1.620     albertel 3027:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3028:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3029:                $thisallowed.=$1;
                   3030:                $checkreferer=0;
                   3031:            }
1.29      www      3032:        }
1.83      www      3033:        
1.148     www      3034:        if ($checkreferer) {
1.620     albertel 3035: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3036:             unless ($refuri) {
1.620     albertel 3037:                 foreach (keys %env) {
1.148     www      3038: 		    if ($_=~/^httpref\..*\*/) {
                   3039: 			my $pattern=$_;
1.156     www      3040:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3041:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3042:                         $pattern=~s/\//\\\//g;
1.152     www      3043:                         if ($orguri=~/$pattern/) {
1.620     albertel 3044: 			    $refuri=$env{$_};
1.148     www      3045:                         }
                   3046:                     }
1.191     harris41 3047:                 }
1.148     www      3048:             }
1.232     www      3049: 
1.148     www      3050:          if ($refuri) { 
1.152     www      3051: 	  $refuri=&declutter($refuri);
1.232     www      3052:           my ($match,$cond)=&is_on_map($refuri);
                   3053:             if ($match) {
                   3054:               my $refstatecond=$cond;
1.620     albertel 3055:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3056:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3057:                   $thisallowed.=$1;
1.53      www      3058:                   $uri=$refuri;
                   3059:                   $statecond=$refstatecond;
1.52      www      3060:               }
                   3061:           }
1.148     www      3062:         }
1.29      www      3063:        }
1.52      www      3064:    }
1.29      www      3065: 
1.52      www      3066: #
1.103     harris41 3067: # Gathered now: all privileges that could apply, and condition number
1.52      www      3068: # 
                   3069: #
                   3070: # Full or no access?
                   3071: #
1.29      www      3072: 
1.52      www      3073:     if ($thisallowed=~/F/) {
                   3074: 	return 'F';
                   3075:     }
1.29      www      3076: 
1.52      www      3077:     unless ($thisallowed) {
                   3078:         return '';
                   3079:     }
1.29      www      3080: 
1.52      www      3081: # Restrictions exist, deal with them
                   3082: #
                   3083: #   C:according to course preferences
                   3084: #   R:according to resource settings
                   3085: #   L:unless locked
                   3086: #   X:according to user session state
                   3087: #
                   3088: 
                   3089: # Possibly locked functionality, check all courses
1.54      www      3090: # Locks might take effect only after 10 minutes cache expiration for other
                   3091: # courses, and 2 minutes for current course
1.52      www      3092: 
                   3093:     my $envkey;
                   3094:     if ($thisallowed=~/L/) {
1.620     albertel 3095:         foreach $envkey (keys %env) {
1.54      www      3096:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3097:                my $courseid=$2;
                   3098:                my $roleid=$1.'.'.$2;
1.92      www      3099:                $courseid=~s/^\///;
1.54      www      3100:                my $expiretime=600;
1.620     albertel 3101:                if ($env{'request.role'} eq $roleid) {
1.54      www      3102: 		  $expiretime=120;
                   3103:                }
                   3104: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3105:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3106:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.54      www      3107: 		   &coursedescription($courseid);
                   3108:                }
1.620     albertel 3109:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3110:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3111: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3112:                        &log($env{'user.domain'},$env{'user.name'},
                   3113:                             $env{'user.home'},
1.57      www      3114:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3115:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3116:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3117: 		       return '';
                   3118:                    }
                   3119:                }
1.620     albertel 3120:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3121:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3122: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3123:                        &log($env{'user.domain'},$env{'user.name'},
                   3124:                             $env{'user.home'},
1.57      www      3125:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3126:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3127:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3128: 		       return '';
                   3129:                    }
                   3130:                }
                   3131: 	   }
1.29      www      3132:        }
1.52      www      3133:     }
                   3134:    
                   3135: #
                   3136: # Rest of the restrictions depend on selected course
                   3137: #
                   3138: 
1.620     albertel 3139:     unless ($env{'request.course.id'}) {
1.52      www      3140:        return '1';
                   3141:     }
1.29      www      3142: 
1.52      www      3143: #
                   3144: # Now user is definitely in a course
                   3145: #
1.53      www      3146: 
                   3147: 
                   3148: # Course preferences
                   3149: 
                   3150:    if ($thisallowed=~/C/) {
1.620     albertel 3151:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3152:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3153:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3154: 	   =~/\Q$rolecode\E/) {
1.620     albertel 3155:            &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.57      www      3156:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.620     albertel 3157:                 $env{'request.course.id'});
1.237     www      3158:            return '';
                   3159:        }
                   3160: 
1.620     albertel 3161:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3162: 	   =~/\Q$unamedom\E/) {
1.620     albertel 3163:            &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.237     www      3164:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.620     albertel 3165:                 $env{'request.course.id'});
1.54      www      3166:            return '';
                   3167:        }
1.53      www      3168:    }
                   3169: 
                   3170: # Resource preferences
                   3171: 
                   3172:    if ($thisallowed=~/R/) {
1.620     albertel 3173:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3174:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.620     albertel 3175: 	  &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.57      www      3176:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341     www      3177:           return '';
1.54      www      3178:        }
1.53      www      3179:    }
1.30      www      3180: 
1.246     www      3181: # Restricted by state or randomout?
1.30      www      3182: 
1.52      www      3183:    if ($thisallowed=~/X/) {
1.620     albertel 3184:       if ($env{'acc.randomout'}) {
1.579     albertel 3185: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3186:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3187:             return ''; 
                   3188:          }
1.247     www      3189:       }
                   3190:       if (&condval($statecond)) {
1.52      www      3191: 	 return '2';
                   3192:       } else {
                   3193:          return '';
                   3194:       }
                   3195:    }
1.30      www      3196: 
1.52      www      3197:    return 'F';
1.232     www      3198: }
                   3199: 
                   3200: # --------------------------------------------------- Is a resource on the map?
                   3201: 
                   3202: sub is_on_map {
                   3203:     my $uri=&declutter(shift);
1.435     www      3204:     $uri=~s/\.\d+\.(\w+)$/\.$1/;
1.232     www      3205:     my @uriparts=split(/\//,$uri);
                   3206:     my $filename=$uriparts[$#uriparts];
                   3207:     my $pathname=$uri;
1.289     bowersj2 3208:     $pathname=~s|/\Q$filename\E$||;
1.332     www      3209:     $pathname=~s/^adm\/wrapper\///;    
1.289     bowersj2 3210:     #Trying to find the conditional for the file
1.620     albertel 3211:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3212: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3213:     if ($match) {
1.289     bowersj2 3214: 	return (1,$1);
                   3215:     } else {
1.434     www      3216: 	return (0,0);
1.289     bowersj2 3217:     }
1.12      www      3218: }
                   3219: 
1.427     www      3220: # --------------------------------------------------------- Get symb from alias
                   3221: 
                   3222: sub get_symb_from_alias {
                   3223:     my $symb=shift;
                   3224:     my ($map,$resid,$url)=&decode_symb($symb);
                   3225: # Already is a symb
                   3226:     if ($url) { return $symb; }
                   3227: # Must be an alias
                   3228:     my $aliassymb='';
                   3229:     my %bighash;
1.620     albertel 3230:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3231:                             &GDBM_READER(),0640)) {
                   3232:         my $rid=$bighash{'mapalias_'.$symb};
                   3233: 	if ($rid) {
                   3234: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3235: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3236: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3237: 	}
                   3238:         untie %bighash;
                   3239:     }
                   3240:     return $aliassymb;
                   3241: }
                   3242: 
1.12      www      3243: # ----------------------------------------------------------------- Define Role
                   3244: 
                   3245: sub definerole {
                   3246:   if (allowed('mcr','/')) {
                   3247:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3248:     foreach (split(':',$sysrole)) {
1.21      www      3249: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3250:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3251:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3252: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3253:                return "refused:s:$crole&$cqual"; 
                   3254:             }
                   3255:         }
1.191     harris41 3256:     }
1.392     www      3257:     foreach (split(':',$domrole)) {
1.21      www      3258: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3259:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3260:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3261: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3262:                return "refused:d:$crole&$cqual"; 
                   3263:             }
                   3264:         }
1.191     harris41 3265:     }
1.392     www      3266:     foreach (split(':',$courole)) {
1.21      www      3267: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3268:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3269:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3270: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3271:                return "refused:c:$crole&$cqual"; 
                   3272:             }
                   3273:         }
1.191     harris41 3274:     }
1.620     albertel 3275:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3276:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3277: 	        "rolesdef_$rolename=".
                   3278:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3279:     return reply($command,$env{'user.home'});
1.12      www      3280:   } else {
                   3281:     return 'refused';
                   3282:   }
1.105     harris41 3283: }
                   3284: 
                   3285: # ---------------- Make a metadata query against the network of library servers
                   3286: 
                   3287: sub metadata_query {
1.244     matthew  3288:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3289:     my %rhash;
1.244     matthew  3290:     my @server_list = (defined($server_array) ? @$server_array
                   3291:                                               : keys(%libserv) );
                   3292:     for my $server (@server_list) {
1.118     harris41 3293: 	unless ($custom or $customshow) {
                   3294: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3295: 	    $rhash{$server}=$reply;
                   3296: 	}
                   3297: 	else {
                   3298: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3299: 			     &escape($custom).':'.&escape($customshow),
                   3300: 			     $server);
                   3301: 	    $rhash{$server}=$reply;
                   3302: 	}
1.112     harris41 3303:     }
1.118     harris41 3304:     return \%rhash;
1.240     www      3305: }
                   3306: 
                   3307: # ----------------------------------------- Send log queries and wait for reply
                   3308: 
                   3309: sub log_query {
                   3310:     my ($uname,$udom,$query,%filters)=@_;
                   3311:     my $uhome=&homeserver($uname,$udom);
                   3312:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3313:     my $uhost=$hostname{$uhome};
1.241     www      3314:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3315:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3316:                        $uhome);
1.479     albertel 3317:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3318:     return get_query_reply($queryid);
                   3319: }
                   3320: 
1.508     raeburn  3321: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3322: 
                   3323: sub fetch_enrollment_query {
1.511     raeburn  3324:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3325:     my $homeserver;
1.547     raeburn  3326:     my $maxtries = 1;
1.508     raeburn  3327:     if ($context eq 'automated') {
                   3328:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3329:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3330:     } else {
                   3331:         $homeserver = &homeserver($cnum,$dom);
                   3332:     }
1.506     raeburn  3333:     my $host=$hostname{$homeserver};
                   3334:     my $cmd = '';
                   3335:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3336:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3337:     }
                   3338:     $cmd =~ s/%%$//;
                   3339:     $cmd = &escape($cmd);
                   3340:     my $query = 'fetchenrollment';
1.620     albertel 3341:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3342:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3343:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3344:         return 'error: '.$queryid;
                   3345:     }
1.506     raeburn  3346:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3347:     my $tries = 1;
                   3348:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3349:         $reply = &get_query_reply($queryid);
                   3350:         $tries ++;
                   3351:     }
1.526     raeburn  3352:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3353:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3354:     } else {
1.515     raeburn  3355:         my @responses = split/:/,$reply;
                   3356:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3357:             foreach (@responses) {
                   3358:                 my ($key,$value) = split/=/,$_;
                   3359:                 $$replyref{$key} = $value;
                   3360:             }
                   3361:         } else {
1.506     raeburn  3362:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3363:             foreach (@responses) {
                   3364:                 my ($key,$value) = split/=/,$_;
                   3365:                 $$replyref{$key} = $value;
                   3366:                 if ($value > 0) {
                   3367:                     foreach (@{$$affiliatesref{$key}}) {
                   3368:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3369:                         my $destname = $pathname.'/'.$filename;
                   3370:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3371:                         if ($xml_classlist =~ /^error/) {
                   3372:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3373:                         } else {
1.506     raeburn  3374:                             if ( open(FILE,">$destname") ) {
                   3375:                                 print FILE &unescape($xml_classlist);
                   3376:                                 close(FILE);
1.526     raeburn  3377:                             } else {
                   3378:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3379:                             }
                   3380:                         }
                   3381:                     }
                   3382:                 }
                   3383:             }
                   3384:         }
                   3385:         return 'ok';
                   3386:     }
                   3387:     return 'error';
                   3388: }
                   3389: 
1.242     www      3390: sub get_query_reply {
                   3391:     my $queryid=shift;
1.240     www      3392:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3393:     my $reply='';
                   3394:     for (1..100) {
                   3395: 	sleep 2;
                   3396:         if (-e $replyfile.'.end') {
1.448     albertel 3397: 	    if (open(my $fh,$replyfile)) {
1.240     www      3398:                $reply.=<$fh>;
1.448     albertel 3399:                close($fh);
1.240     www      3400: 	   } else { return 'error: reply_file_error'; }
1.242     www      3401:            return &unescape($reply);
                   3402: 	}
1.240     www      3403:     }
1.242     www      3404:     return 'timeout:'.$queryid;
1.240     www      3405: }
                   3406: 
                   3407: sub courselog_query {
1.241     www      3408: #
                   3409: # possible filters:
                   3410: # url: url or symb
                   3411: # username
                   3412: # domain
                   3413: # action: view, submit, grade
                   3414: # start: timestamp
                   3415: # end: timestamp
                   3416: #
1.240     www      3417:     my (%filters)=@_;
1.620     albertel 3418:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3419:     if ($filters{'url'}) {
                   3420: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3421:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3422:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3423:     }
1.620     albertel 3424:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3425:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3426:     return &log_query($cname,$cdom,'courselog',%filters);
                   3427: }
                   3428: 
                   3429: sub userlog_query {
                   3430:     my ($uname,$udom,%filters)=@_;
                   3431:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3432: }
                   3433: 
1.506     raeburn  3434: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3435: 
                   3436: sub auto_run {
1.508     raeburn  3437:     my ($cnum,$cdom) = @_;
                   3438:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3439:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3440:     return $response;
                   3441: }
                   3442:                                                                                    
                   3443: sub auto_get_sections {
1.508     raeburn  3444:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3445:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3446:     my @secs = ();
1.511     raeburn  3447:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3448:     unless ($response eq 'refused') {
                   3449:         @secs = split/:/,$response;
                   3450:     }
                   3451:     return @secs;
                   3452: }
                   3453:                                                                                    
                   3454: sub auto_new_course {
1.508     raeburn  3455:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3456:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3457:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3458:     return $response;
                   3459: }
                   3460:                                                                                    
                   3461: sub auto_validate_courseID {
1.508     raeburn  3462:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3463:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3464:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3465:     return $response;
                   3466: }
                   3467:                                                                                    
                   3468: sub auto_create_password {
1.508     raeburn  3469:     my ($cnum,$cdom,$authparam) = @_;
                   3470:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3471:     my $create_passwd = 0;
                   3472:     my $authchk = '';
1.511     raeburn  3473:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3474:     if ($response eq 'refused') {
                   3475:         $authchk = 'refused';
                   3476:     } else {
                   3477:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3478:     }
                   3479:     return ($authparam,$create_passwd,$authchk);
                   3480: }
                   3481: 
1.521     raeburn  3482: sub auto_instcode_format {
                   3483:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3484:     my $courses = '';
                   3485:     my $homeserver;
                   3486:     if ($caller eq 'global') {
1.584     raeburn  3487:         foreach my $tryserver (keys %libserv) {
                   3488:             if ($hostdom{$tryserver} eq $codedom) {
                   3489:                 $homeserver = $tryserver;
                   3490:                 last;
                   3491:             }
                   3492:         }
1.620     albertel 3493:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3494:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3495:         }
1.521     raeburn  3496:     } else {
                   3497:         $homeserver = &homeserver($caller,$codedom);
                   3498:     }
                   3499:     foreach (keys %{$instcodes}) {
                   3500:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3501:     }
                   3502:     chop($courses);
                   3503:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3504:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3505:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3506:         %{$codes} = &str2hash($codes_str);
                   3507:         @{$codetitles} = &str2array($codetitles_str);
                   3508:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3509:         %{$cat_order} = &str2hash($cat_order_str);
                   3510:         return 'ok';
                   3511:     }
                   3512:     return $response;
                   3513: }
                   3514: 
1.12      www      3515: # ------------------------------------------------------------------ Plain Text
                   3516: 
                   3517: sub plaintext {
1.22      www      3518:     my $short=shift;
1.414     www      3519:     return &mt($prp{$short});
1.12      www      3520: }
                   3521: 
                   3522: # ----------------------------------------------------------------- Assign Role
                   3523: 
                   3524: sub assignrole {
1.357     www      3525:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      3526:     my $mrole;
                   3527:     if ($role =~ /^cr\//) {
1.393     www      3528:         my $cwosec=$url;
                   3529:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   3530: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      3531:            &logthis('Refused custom assignrole: '.
                   3532:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3533: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3534:            return 'refused'; 
                   3535:         }
1.21      www      3536:         $mrole='cr';
                   3537:     } else {
1.82      www      3538:         my $cwosec=$url;
1.83      www      3539:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      3540:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      3541:            &logthis('Refused assignrole: '.
                   3542:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3543: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3544:            return 'refused'; 
                   3545:         }
1.21      www      3546:         $mrole=$role;
                   3547:     }
1.620     albertel 3548:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3549:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      3550:     if ($end) { $command.='_'.$end; }
1.21      www      3551:     if ($start) {
                   3552: 	if ($end) { 
1.81      www      3553:            $command.='_'.$start; 
1.21      www      3554:         } else {
1.81      www      3555:            $command.='_0_'.$start;
1.21      www      3556:         }
                   3557:     }
1.357     www      3558: # actually delete
                   3559:     if ($deleteflag) {
1.373     www      3560: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      3561: # modify command to delete the role
1.620     albertel 3562:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      3563:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 3564: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      3565: # set start and finish to negative values for userrolelog
                   3566:            $start=-1;
                   3567:            $end=-1;
                   3568:         }
                   3569:     }
                   3570: # send command
1.349     www      3571:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      3572: # log new user role if status is ok
1.349     www      3573:     if ($answer eq 'ok') {
                   3574: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
                   3575:     }
                   3576:     return $answer;
1.169     harris41 3577: }
                   3578: 
                   3579: # -------------------------------------------------- Modify user authentication
1.197     www      3580: # Overrides without validation
                   3581: 
1.169     harris41 3582: sub modifyuserauth {
                   3583:     my ($udom,$uname,$umode,$upass)=@_;
                   3584:     my $uhome=&homeserver($uname,$udom);
1.197     www      3585:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   3586:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 3587:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   3588:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 3589:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   3590: 		     &escape($upass),$uhome);
1.620     albertel 3591:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      3592:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   3593:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   3594:     &log($udom,,$uname,$uhome,
1.620     albertel 3595:         'Authentication changed by '.$env{'user.domain'}.', '.
                   3596:                                      $env{'user.name'}.', '.$umode.
1.197     www      3597:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 3598:     unless ($reply eq 'ok') {
1.197     www      3599:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 3600: 	return 'error: '.$reply;
                   3601:     }   
1.170     harris41 3602:     return 'ok';
1.80      www      3603: }
                   3604: 
1.81      www      3605: # --------------------------------------------------------------- Modify a user
1.80      www      3606: 
1.81      www      3607: sub modifyuser {
1.206     matthew  3608:     my ($udom,    $uname, $uid,
                   3609:         $umode,   $upass, $first,
                   3610:         $middle,  $last,  $gene,
1.387     www      3611:         $forceid, $desiredhome, $email)=@_;
1.198     www      3612:     $udom=~s/\W//g;
                   3613:     $uname=~s/\W//g;
1.81      www      3614:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3615:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  3616: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   3617:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   3618:                                      ' desiredhome not specified'). 
1.620     albertel 3619:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   3620:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 3621:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      3622: # ----------------------------------------------------------------- Create User
1.406     albertel 3623:     if (($uhome eq 'no_host') && 
                   3624: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      3625:         my $unhome='';
1.209     matthew  3626:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   3627:             $unhome = $desiredhome;
1.620     albertel 3628: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   3629: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  3630:         } else { # load balancing routine for determining $unhome
1.80      www      3631:             my $tryserver;
1.81      www      3632:             my $loadm=10000000;
1.80      www      3633:             foreach $tryserver (keys %libserv) {
                   3634: 	       if ($hostdom{$tryserver} eq $udom) {
                   3635:                   my $answer=reply('load',$tryserver);
                   3636:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   3637: 		      $loadm=$answer;
                   3638:                       $unhome=$tryserver;
                   3639:                   }
                   3640: 	       }
                   3641: 	    }
                   3642:         }
                   3643:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  3644: 	    return 'error: unable to find a home server for '.$uname.
                   3645:                    ' in domain '.$udom;
1.80      www      3646:         }
                   3647:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   3648:                          &escape($upass),$unhome);
                   3649: 	unless ($reply eq 'ok') {
                   3650:             return 'error: '.$reply;
                   3651:         }   
1.230     stredwic 3652:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      3653:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  3654: 	    return 'error: unable verify users home machine.';
1.80      www      3655:         }
1.209     matthew  3656:     }   # End of creation of new user
1.80      www      3657: # ---------------------------------------------------------------------- Add ID
                   3658:     if ($uid) {
                   3659:        $uid=~tr/A-Z/a-z/;
                   3660:        my %uidhash=&idrget($udom,$uname);
1.196     www      3661:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   3662:          && (!$forceid)) {
1.80      www      3663: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  3664: 	      return 'error: user id "'.$uid.'" does not match '.
                   3665:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      3666:           }
                   3667:        } else {
                   3668: 	  &idput($udom,($uname => $uid));
                   3669:        }
                   3670:     }
                   3671: # -------------------------------------------------------------- Add names, etc
1.313     matthew  3672:     my @tmp=&get('environment',
1.134     albertel 3673: 		   ['firstname','middlename','lastname','generation'],
                   3674: 		   $udom,$uname);
1.313     matthew  3675:     my %names;
                   3676:     if ($tmp[0] =~ m/^error:.*/) { 
                   3677:         %names=(); 
                   3678:     } else {
                   3679:         %names = @tmp;
                   3680:     }
1.388     www      3681: #
                   3682: # Make sure to not trash student environment if instructor does not bother
                   3683: # to supply name and email information
                   3684: #
                   3685:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  3686:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      3687:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  3688:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      3689:     if ($email) {
                   3690:        $email=~s/[^\w\@\.\-\,]//gs;
                   3691:        if ($email=~/\@/) { $names{'notification'} = $email;
                   3692: 			   $names{'critnotification'} = $email;
                   3693: 			   $names{'permanentemail'} = $email; }
                   3694:     }
1.134     albertel 3695:     my $reply = &put('environment', \%names, $udom,$uname);
                   3696:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      3697:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3698:              $umode.', '.$first.', '.$middle.', '.
                   3699: 	     $last.', '.$gene.' by '.
1.620     albertel 3700:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 3701:     return 'ok';
1.80      www      3702: }
                   3703: 
1.81      www      3704: # -------------------------------------------------------------- Modify student
1.80      www      3705: 
1.81      www      3706: sub modifystudent {
                   3707:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  3708:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 3709:     if (!$cid) {
1.620     albertel 3710: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 3711: 	    return 'not_in_class';
                   3712: 	}
1.80      www      3713:     }
                   3714: # --------------------------------------------------------------- Make the user
1.81      www      3715:     my $reply=&modifyuser
1.209     matthew  3716: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      3717:          $desiredhome,$email);
1.80      www      3718:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  3719:     # This will cause &modify_student_enrollment to get the uid from the
                   3720:     # students environment
                   3721:     $uid = undef if (!$forceid);
1.455     albertel 3722:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  3723: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  3724:     return $reply;
                   3725: }
                   3726: 
                   3727: sub modify_student_enrollment {
1.515     raeburn  3728:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 3729:     my ($cdom,$cnum,$chome);
                   3730:     if (!$cid) {
1.620     albertel 3731: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 3732: 	    return 'not_in_class';
                   3733: 	}
1.620     albertel 3734: 	$cdom=$env{'course.'.$cid.'.domain'};
                   3735: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 3736:     } else {
                   3737: 	($cdom,$cnum)=split(/_/,$cid);
                   3738:     }
1.620     albertel 3739:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 3740:     if (!$chome) {
1.457     raeburn  3741: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  3742:     }
1.455     albertel 3743:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  3744:     # Make sure the user exists
1.81      www      3745:     my $uhome=&homeserver($uname,$udom);
                   3746:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3747: 	return 'error: no such user';
                   3748:     }
1.297     matthew  3749:     # Get student data if we were not given enough information
                   3750:     if (!defined($first)  || $first  eq '' || 
                   3751:         !defined($last)   || $last   eq '' || 
                   3752:         !defined($uid)    || $uid    eq '' || 
                   3753:         !defined($middle) || $middle eq '' || 
                   3754:         !defined($gene)   || $gene   eq '') {
1.294     matthew  3755:         # They did not supply us with enough data to enroll the student, so
                   3756:         # we need to pick up more information.
1.297     matthew  3757:         my %tmp = &get('environment',
1.294     matthew  3758:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  3759:                        ,$udom,$uname);
                   3760: 
1.455     albertel 3761:         #foreach (keys(%tmp)) {
                   3762:         #    &logthis("key $_ = ".$tmp{$_});
                   3763:         #}
1.294     matthew  3764:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   3765:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   3766:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  3767:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  3768:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   3769:     }
1.556     albertel 3770:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 3771:     my $reply=cput('classlist',
                   3772: 		   {"$uname:$udom" => 
1.515     raeburn  3773: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 3774: 		   $cdom,$cnum);
1.81      www      3775:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   3776: 	return 'error: '.$reply;
1.652   ! albertel 3777:     } else {
        !          3778: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      3779:     }
1.297     matthew  3780:     # Add student role to user
1.83      www      3781:     my $uurl='/'.$cid;
1.81      www      3782:     $uurl=~s/\_/\//g;
                   3783:     if ($usec) {
                   3784: 	$uurl.='/'.$usec;
                   3785:     }
                   3786:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      3787: }
                   3788: 
1.556     albertel 3789: sub format_name {
                   3790:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   3791:     my $name;
                   3792:     if ($first ne 'lastname') {
                   3793: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   3794:     } else {
                   3795: 	if ($lastname=~/\S/) {
                   3796: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   3797: 	    $name=~s/\s+,/,/;
                   3798: 	} else {
                   3799: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   3800: 	}
                   3801:     }
                   3802:     $name=~s/^\s+//;
                   3803:     $name=~s/\s+$//;
                   3804:     $name=~s/\s+/ /g;
                   3805:     return $name;
                   3806: }
                   3807: 
1.84      www      3808: # ------------------------------------------------- Write to course preferences
                   3809: 
                   3810: sub writecoursepref {
                   3811:     my ($courseid,%prefs)=@_;
                   3812:     $courseid=~s/^\///;
                   3813:     $courseid=~s/\_/\//g;
                   3814:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   3815:     my $chome=homeserver($cnum,$cdomain);
                   3816:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   3817: 	return 'error: no such course';
                   3818:     }
                   3819:     my $cstring='';
1.191     harris41 3820:     foreach (keys %prefs) {
1.84      www      3821: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 3822:     }
1.84      www      3823:     $cstring=~s/\&$//;
                   3824:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   3825: }
                   3826: 
                   3827: # ---------------------------------------------------------- Make/modify course
                   3828: 
                   3829: sub createcourse {
1.571     raeburn  3830:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      3831:     $url=&declutter($url);
                   3832:     my $cid='';
1.264     matthew  3833:     unless (&allowed('ccc',$udom)) {
1.84      www      3834:         return 'refused';
                   3835:     }
                   3836: # ------------------------------------------------------------------- Create ID
                   3837:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3838:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   3839: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 3840:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      3841:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3842:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3843:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 3844:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      3845:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3846:            return 'error: unable to generate unique course-ID';
                   3847:        } 
                   3848:    }
1.264     matthew  3849: # ------------------------------------------------ Check supplied server name
1.620     albertel 3850:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  3851:     if (! exists($libserv{$course_server})) {
                   3852:         return 'error:bad server name '.$course_server;
                   3853:     }
1.84      www      3854: # ------------------------------------------------------------- Make the course
                   3855:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  3856:                       $course_server);
1.84      www      3857:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 3858:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      3859:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3860: 	return 'error: no such course';
                   3861:     }
1.271     www      3862: # ----------------------------------------------------------------- Course made
1.516     raeburn  3863: # log existence
                   3864:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  3865:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      3866:     &flushcourselogs();
                   3867: # set toplevel url
1.271     www      3868:     my $topurl=$url;
                   3869:     unless ($nonstandard) {
                   3870: # ------------------------------------------ For standard courses, make top url
                   3871:         my $mapurl=&clutter($url);
1.278     www      3872:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 3873:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      3874: <map>
                   3875: <resource id="1" type="start"></resource>
                   3876: <resource id="2" src="$mapurl"></resource>
                   3877: <resource id="3" type="finish"></resource>
                   3878: <link index="1" from="1" to="2"></link>
                   3879: <link index="2" from="2" to="3"></link>
                   3880: </map>
                   3881: ENDINITMAP
                   3882:         $topurl=&declutter(
1.638     albertel 3883:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      3884:                           );
                   3885:     }
                   3886: # ----------------------------------------------------------- Write preferences
1.84      www      3887:     &writecoursepref($udom.'_'.$uname,
                   3888:                      ('description' => $description,
1.271     www      3889:                       'url'         => $topurl));
1.84      www      3890:     return '/'.$udom.'/'.$uname;
                   3891: }
                   3892: 
1.21      www      3893: # ---------------------------------------------------------- Assign Custom Role
                   3894: 
                   3895: sub assigncustomrole {
1.357     www      3896:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      3897:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      3898:                        $end,$start,$deleteflag);
1.21      www      3899: }
                   3900: 
                   3901: # ----------------------------------------------------------------- Revoke Role
                   3902: 
                   3903: sub revokerole {
1.357     www      3904:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      3905:     my $now=time;
1.357     www      3906:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      3907: }
                   3908: 
                   3909: # ---------------------------------------------------------- Revoke Custom Role
                   3910: 
                   3911: sub revokecustomrole {
1.357     www      3912:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      3913:     my $now=time;
1.357     www      3914:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   3915:            $deleteflag);
1.17      www      3916: }
                   3917: 
1.533     banghart 3918: # ------------------------------------------------------------ Disk usage
1.535     albertel 3919: sub diskusage {
1.533     banghart 3920:     my ($udom,$uname,$directoryRoot)=@_;
                   3921:     $directoryRoot =~ s/\/$//;
1.535     albertel 3922:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 3923:     return $listing;
1.512     banghart 3924: }
                   3925: 
1.566     banghart 3926: sub is_locked {
                   3927:     my ($file_name, $domain, $user) = @_;
                   3928:     my @check;
                   3929:     my $is_locked;
                   3930:     push @check, $file_name;
1.613     albertel 3931:     my %locked = &get('file_permissions',\@check,
1.620     albertel 3932: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 3933:     my ($tmp)=keys(%locked);
                   3934:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 3935: 
1.566     banghart 3936:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   3937:         $is_locked = 'true';
                   3938:     } else {
                   3939:         $is_locked = 'false';
                   3940:     }
                   3941: }
                   3942: 
1.559     banghart 3943: # ------------------------------------------------------------- Mark as Read Only
                   3944: 
                   3945: sub mark_as_readonly {
                   3946:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 3947:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 3948:     my ($tmp)=keys(%current_permissions);
                   3949:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 3950:     foreach my $file (@{$files}) {
1.561     banghart 3951:         push(@{$current_permissions{$file}},$what);
1.559     banghart 3952:     }
1.613     albertel 3953:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 3954:     return;
                   3955: }
                   3956: 
1.572     banghart 3957: # ------------------------------------------------------------Save Selected Files
                   3958: 
                   3959: sub save_selected_files {
                   3960:     my ($user, $path, @files) = @_;
                   3961:     my $filename = $user."savedfiles";
1.573     banghart 3962:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 3963:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 3964:     foreach my $file (@files) {
1.620     albertel 3965:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 3966:     }
                   3967:     foreach my $file (@other_files) {
1.574     banghart 3968:         print (OUT $file."\n");
1.572     banghart 3969:     }
1.574     banghart 3970:     close (OUT);
1.572     banghart 3971:     return 'ok';
                   3972: }
                   3973: 
1.574     banghart 3974: sub clear_selected_files {
                   3975:     my ($user) = @_;
                   3976:     my $filename = $user."savedfiles";
                   3977:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   3978:     print (OUT undef);
                   3979:     close (OUT);
                   3980:     return ("ok");    
                   3981: }
                   3982: 
1.572     banghart 3983: sub files_in_path {
                   3984:     my ($user, $path) = @_;
                   3985:     my $filename = $user."savedfiles";
                   3986:     my %return_files;
1.574     banghart 3987:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 3988:     while (my $line_in = <IN>) {
1.574     banghart 3989:         chomp ($line_in);
                   3990:         my @paths_and_file = split (m!/!, $line_in);
                   3991:         my $file_part = pop (@paths_and_file);
                   3992:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 3993:         $path_part.='/';
                   3994:         my $path_and_file = $path_part.$file_part;
                   3995:         if ($path_part eq $path) {
                   3996:             $return_files{$file_part}= 'selected';
                   3997:         }
                   3998:     }
1.574     banghart 3999:     close (IN);
                   4000:     return (\%return_files);
1.572     banghart 4001: }
                   4002: 
                   4003: # called in portfolio select mode, to show files selected NOT in current directory
                   4004: sub files_not_in_path {
                   4005:     my ($user, $path) = @_;
                   4006:     my $filename = $user."savedfiles";
                   4007:     my @return_files;
                   4008:     my $path_part;
1.574     banghart 4009:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4010:     while (<IN>) {
                   4011:         #ok, I know it's clunky, but I want it to work
                   4012:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4013:         my $file_part = pop (@paths_and_file);
                   4014:         chomp ($file_part);
                   4015:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4016:         $path_part .= '/';
                   4017:         my $path_and_file = $path_part.$file_part;
                   4018:         if ($path_part ne $path) {
1.574     banghart 4019:             push (@return_files, ($path_and_file));
1.572     banghart 4020:         }
                   4021:     }
1.574     banghart 4022:     close (OUT);
                   4023:     return (@return_files);
1.572     banghart 4024: }
                   4025: 
1.561     banghart 4026: #--------------------------------------------------------------Get Marked as Read Only
                   4027: 
1.629     banghart 4028: 
1.561     banghart 4029: sub get_marked_as_readonly {
                   4030:     my ($domain,$user,$what) = @_;
1.613     albertel 4031:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4032:     my ($tmp)=keys(%current_permissions);
                   4033:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563     banghart 4034:     my @readonly_files;
1.629     banghart 4035:     my $cmp1=$what;
                   4036:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.563     banghart 4037:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 4038:         if (ref($value) eq "ARRAY"){
                   4039:             foreach my $stored_what (@{$value}) {
1.629     banghart 4040:                 my $cmp2=$stored_what;
                   4041:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
                   4042:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4043:                     push(@readonly_files, $file_name);
1.563     banghart 4044:                 } elsif (!defined($what)) {
                   4045:                     push(@readonly_files, $file_name);
1.561     banghart 4046:                 }
                   4047:             }
                   4048:         } 
                   4049:     }
                   4050:     return @readonly_files;
                   4051: }
1.577     banghart 4052: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4053: 
1.577     banghart 4054: sub get_marked_as_readonly_hash {
                   4055:     my ($domain,$user,$what) = @_;
1.613     albertel 4056:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4057:     my ($tmp)=keys(%current_permissions);
                   4058:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4059: 
1.577     banghart 4060:     my %readonly_files;
                   4061:     while (my ($file_name,$value) = each(%current_permissions)) {
                   4062:         if (ref($value) eq "ARRAY"){
                   4063:             foreach my $stored_what (@{$value}) {
                   4064:                 if ($stored_what eq $what) {
                   4065:                     $readonly_files{$file_name} = 'locked';
                   4066:                 } elsif (!defined($what)) {
                   4067:                     $readonly_files{$file_name} = 'locked';
                   4068:                 }
                   4069:             }
                   4070:         } 
                   4071:     }
                   4072:     return %readonly_files;
                   4073: }
1.559     banghart 4074: # ------------------------------------------------------------ Unmark as Read Only
                   4075: 
                   4076: sub unmark_as_readonly {
1.629     banghart 4077:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4078:     # for portfolio submissions, $what contains [$symb,$crsid] 
                   4079:     my ($domain,$user,$what,$file_name) = @_;
1.634     albertel 4080:     my $symb_crs = $what;
                   4081:     if (ref($what)) { $symb_crs=join('',@$what); }
1.613     albertel 4082:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4083:     my ($tmp)=keys(%current_permissions);
                   4084:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4085:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.650     albertel 4086:     foreach my $file (@readonly_files) {
                   4087: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4088: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4089:         my @new_locks;
                   4090:         my @del_keys;
                   4091:         if (ref($current_locks) eq "ARRAY"){
                   4092:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4093:                 my $compare=$locker;
                   4094:                 if (ref($locker)) { $compare=join('',@{$locker}) };
1.650     albertel 4095:                 if ($compare ne $symb_crs) {
                   4096:                     push(@new_locks, $locker);
1.563     banghart 4097:                 }
                   4098:             }
1.650     albertel 4099:             if (scalar(@new_locks) > 0) {
1.563     banghart 4100:                 $current_permissions{$file} = \@new_locks;
                   4101:             } else {
                   4102:                 push(@del_keys, $file);
1.613     albertel 4103:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4104:                 delete($current_permissions{$file});
1.563     banghart 4105:             }
                   4106:         }
1.561     banghart 4107:     }
1.613     albertel 4108:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4109:     return;
                   4110: }
1.512     banghart 4111: 
1.17      www      4112: # ------------------------------------------------------------ Directory lister
                   4113: 
                   4114: sub dirlist {
1.253     stredwic 4115:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4116: 
1.18      www      4117:     $uri=~s/^\///;
                   4118:     $uri=~s/\/$//;
1.253     stredwic 4119:     my ($udom, $uname);
                   4120:     (undef,$udom,$uname)=split(/\//,$uri);
                   4121:     if(defined($userdomain)) {
                   4122:         $udom = $userdomain;
                   4123:     }
                   4124:     if(defined($username)) {
                   4125:         $uname = $username;
                   4126:     }
                   4127: 
                   4128:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4129:     if(defined($alternateDirectoryRoot)) {
                   4130:         $dirRoot = $alternateDirectoryRoot;
                   4131:         $dirRoot =~ s/\/$//;
                   4132:     }
                   4133: 
                   4134:     if($udom) {
                   4135:         if($uname) {
1.605     matthew  4136:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4137:                               homeserver($uname,$udom));
1.605     matthew  4138:             my @listing_results;
                   4139:             if ($listing eq 'unknown_cmd') {
                   4140:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4141:                                homeserver($uname,$udom));
                   4142:                 @listing_results = split(/:/,$listing);
                   4143:             } else {
                   4144:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4145:             }
                   4146:             return @listing_results;
1.253     stredwic 4147:         } elsif(!defined($alternateDirectoryRoot)) {
                   4148:             my $tryserver;
                   4149:             my %allusers=();
                   4150:             foreach $tryserver (keys %libserv) {
                   4151:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4152:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4153:                                       $udom, $tryserver);
1.605     matthew  4154:                     my @listing_results;
                   4155:                     if ($listing eq 'unknown_cmd') {
                   4156:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4157:                                        $udom, $tryserver);
                   4158:                         @listing_results = split(/:/,$listing);
                   4159:                     } else {
                   4160:                         @listing_results =
                   4161:                             map { &unescape($_); } split(/:/,$listing);
                   4162:                     }
                   4163:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4164:                         $listing_results[0] ne 'empty'       &&
                   4165:                         $listing_results[0] ne 'con_lost') {
                   4166:                         foreach (@listing_results) {
1.253     stredwic 4167:                             my ($entry,@stat)=split(/&/,$_);
                   4168:                             $allusers{$entry}=1;
                   4169:                         }
                   4170:                     }
1.191     harris41 4171:                 }
1.253     stredwic 4172:             }
                   4173:             my $alluserstr='';
                   4174:             foreach (sort keys %allusers) {
                   4175:                 $alluserstr.=$_.'&user:';
                   4176:             }
                   4177:             $alluserstr=~s/:$//;
                   4178:             return split(/:/,$alluserstr);
                   4179:         } else {
                   4180:             my @emptyResults = ();
                   4181:             push(@emptyResults, 'missing user name');
                   4182:             return split(':',@emptyResults);
                   4183:         }
                   4184:     } elsif(!defined($alternateDirectoryRoot)) {
                   4185:         my $tryserver;
                   4186:         my %alldom=();
                   4187:         foreach $tryserver (keys %libserv) {
                   4188:             $alldom{$hostdom{$tryserver}}=1;
                   4189:         }
                   4190:         my $alldomstr='';
                   4191:         foreach (sort keys %alldom) {
1.397     albertel 4192:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4193:         }
                   4194:         $alldomstr=~s/:$//;
                   4195:         return split(/:/,$alldomstr);       
                   4196:     } else {
                   4197:         my @emptyResults = ();
                   4198:         push(@emptyResults, 'missing domain');
                   4199:         return split(':',@emptyResults);
1.275     stredwic 4200:     }
                   4201: }
                   4202: 
                   4203: # --------------------------------------------- GetFileTimestamp
                   4204: # This function utilizes dirlist and returns the date stamp for
                   4205: # when it was last modified.  It will also return an error of -1
                   4206: # if an error occurs
                   4207: 
1.410     matthew  4208: ##
                   4209: ## FIXME: This subroutine assumes its caller knows something about the
                   4210: ## directory structure of the home server for the student ($root).
                   4211: ## Not a good assumption to make.  Since this is for looking up files
                   4212: ## in user directories, the full path should be constructed by lond, not
                   4213: ## whatever machine we request data from.
                   4214: ##
1.275     stredwic 4215: sub GetFileTimestamp {
                   4216:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4217:     $studentDomain=~s/\W//g;
                   4218:     $studentName=~s/\W//g;
                   4219:     my $subdir=$studentName.'__';
                   4220:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4221:     my $proname="$studentDomain/$subdir/$studentName";
                   4222:     $proname .= '/'.$filename;
1.375     matthew  4223:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4224:                                               $studentName, $root);
1.275     stredwic 4225:     my @stats = split('&', $fileStat);
                   4226:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4227:         # @stats contains first the filename, then the stat output
                   4228:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4229:     } else {
                   4230:         return -1;
1.253     stredwic 4231:     }
1.26      www      4232: }
                   4233: 
                   4234: # -------------------------------------------------------- Value of a Condition
                   4235: 
1.40      www      4236: sub directcondval {
                   4237:     my $number=shift;
1.620     albertel 4238:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4239: 	&Apache::lonuserstate::evalstate();
                   4240:     }
1.620     albertel 4241:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4242:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4243:     } else {
                   4244:        return 2;
                   4245:     }
                   4246: }
                   4247: 
1.26      www      4248: sub condval {
                   4249:     my $condidx=shift;
                   4250:     my $result=0;
1.54      www      4251:     my $allpathcond='';
1.191     harris41 4252:     foreach (split(/\|/,$condidx)) {
1.620     albertel 4253:        if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$_})) {
1.54      www      4254: 	   $allpathcond.=
1.620     albertel 4255:                '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$_}.')|';
1.54      www      4256:        }
1.191     harris41 4257:     }
1.54      www      4258:     $allpathcond=~s/\|$//;
1.620     albertel 4259:     if ($env{'request.course.id'}) {
1.54      www      4260:        if ($allpathcond) {
1.26      www      4261:           my $operand='|';
                   4262: 	  my @stack;
1.191     harris41 4263:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      4264:               if ($_ eq '(') {
                   4265:                  push @stack,($operand,$result)
                   4266:               } elsif ($_ eq ')') {
                   4267:                   my $before=pop @stack;
                   4268: 		  if (pop @stack eq '&') {
                   4269: 		      $result=$result>$before?$before:$result;
                   4270:                   } else {
                   4271:                       $result=$result>$before?$result:$before;
                   4272:                   }
                   4273:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   4274:                   $operand=$_;
                   4275:               } else {
1.40      www      4276:                   my $new=directcondval($_);
1.26      www      4277:                   if ($operand eq '&') {
                   4278:                      $result=$result>$new?$new:$result;
                   4279:                   } else {
                   4280:                      $result=$result>$new?$result:$new;
1.191     harris41 4281:                   }
1.26      www      4282:               }
1.191     harris41 4283:           }
1.26      www      4284:        }
                   4285:     }
                   4286:     return $result;
1.421     albertel 4287: }
                   4288: 
                   4289: # ---------------------------------------------------- Devalidate courseresdata
                   4290: 
                   4291: sub devalidatecourseresdata {
                   4292:     my ($coursenum,$coursedomain)=@_;
                   4293:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4294:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4295: }
                   4296: 
1.200     www      4297: # --------------------------------------------------- Course Resourcedata Query
                   4298: 
1.624     albertel 4299: sub get_courseresdata {
                   4300:     my ($coursenum,$coursedomain)=@_;
1.200     www      4301:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4302:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4303:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4304:     my %dumpreply;
1.417     albertel 4305:     unless (defined($cached)) {
1.624     albertel 4306: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4307: 	$result=\%dumpreply;
1.251     albertel 4308: 	my ($tmp) = keys(%dumpreply);
                   4309: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4310: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4311: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4312: 	    return $tmp;
1.416     albertel 4313: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4314: 	    $result=undef;
1.599     albertel 4315: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4316: 	}
                   4317:     }
1.624     albertel 4318:     return $result;
                   4319: }
                   4320: 
1.633     albertel 4321: sub devalidateuserresdata {
                   4322:     my ($uname,$udom)=@_;
                   4323:     my $hashid="$udom:$uname";
                   4324:     &devalidate_cache_new('userres',$hashid);
                   4325: }
                   4326: 
1.624     albertel 4327: sub get_userresdata {
                   4328:     my ($uname,$udom)=@_;
                   4329:     #most student don\'t have any data set, check if there is some data
                   4330:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4331: 
                   4332:     my $hashid="$udom:$uname";
                   4333:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4334:     if (!defined($cached)) {
                   4335: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4336: 	$result=\%resourcedata;
                   4337: 	&do_cache_new('userres',$hashid,$result,600);
                   4338:     }
                   4339:     my ($tmp)=keys(%$result);
                   4340:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4341: 	return $result;
                   4342:     }
                   4343:     #error 2 occurs when the .db doesn't exist
                   4344:     if ($tmp!~/error: 2 /) {
                   4345: 	&logthis("<font color=blue>WARNING:".
                   4346: 		 " Trying to get resource data for ".
                   4347: 		 $uname." at ".$udom.": ".
                   4348: 		 $tmp."</font>");
                   4349:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 4350: 	#&EXT_cache_set($udom,$uname);
                   4351: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 4352: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 4353:     }
                   4354:     return $tmp;
                   4355: }
                   4356: 
                   4357: sub resdata {
                   4358:     my ($name,$domain,$type,@which)=@_;
                   4359:     my $result;
                   4360:     if ($type eq 'course') {
                   4361: 	$result=&get_courseresdata($name,$domain);
                   4362:     } elsif ($type eq 'user') {
                   4363: 	$result=&get_userresdata($name,$domain);
                   4364:     }
                   4365:     if (!ref($result)) { return $result; }    
1.251     albertel 4366:     foreach my $item (@which) {
1.417     albertel 4367: 	if (defined($result->{$item})) {
                   4368: 	    return $result->{$item};
1.251     albertel 4369: 	}
1.250     albertel 4370:     }
1.291     albertel 4371:     return undef;
1.200     www      4372: }
                   4373: 
1.379     matthew  4374: #
                   4375: # EXT resource caching routines
                   4376: #
                   4377: 
                   4378: sub clear_EXT_cache_status {
1.383     albertel 4379:     &delenv('cache.EXT.');
1.379     matthew  4380: }
                   4381: 
                   4382: sub EXT_cache_status {
                   4383:     my ($target_domain,$target_user) = @_;
1.383     albertel 4384:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 4385:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  4386:         # We know already the user has no data
                   4387:         return 1;
                   4388:     } else {
                   4389:         return 0;
                   4390:     }
                   4391: }
                   4392: 
                   4393: sub EXT_cache_set {
                   4394:     my ($target_domain,$target_user) = @_;
1.383     albertel 4395:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 4396:     #&appenv($cachename => time);
1.379     matthew  4397: }
                   4398: 
1.28      www      4399: # --------------------------------------------------------- Value of a Variable
1.58      www      4400: sub EXT {
1.395     albertel 4401:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218     albertel 4402: 
1.68      www      4403:     unless ($varname) { return ''; }
1.218     albertel 4404:     #get real user name/domain, courseid and symb
                   4405:     my $courseid;
1.359     albertel 4406:     my $publicuser;
1.427     www      4407:     if ($symbparm) {
                   4408: 	$symbparm=&get_symb_from_alias($symbparm);
                   4409:     }
1.218     albertel 4410:     if (!($uname && $udom)) {
1.360     albertel 4411:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  4412: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 4413:       if (!$symbparm) {	$symbparm=$cursymb; }
                   4414:     } else {
1.620     albertel 4415: 	$courseid=$env{'request.course.id'};
1.218     albertel 4416:     }
1.48      www      4417:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   4418:     my $rest;
1.320     albertel 4419:     if (defined($therest[0])) {
1.48      www      4420:        $rest=join('.',@therest);
                   4421:     } else {
                   4422:        $rest='';
                   4423:     }
1.320     albertel 4424: 
1.57      www      4425:     my $qualifierrest=$qualifier;
                   4426:     if ($rest) { $qualifierrest.='.'.$rest; }
                   4427:     my $spacequalifierrest=$space;
                   4428:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      4429:     if ($realm eq 'user') {
1.48      www      4430: # --------------------------------------------------------------- user.resource
                   4431: 	if ($space eq 'resource') {
1.651     albertel 4432: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   4433: 		  || defined($Apache::lonhomework::parsing_a_task))
                   4434: 		 &&
                   4435: 		 ($symbparm eq &symbread()) ) {
1.335     albertel 4436: 		return $Apache::lonhomework::history{$qualifierrest};
                   4437: 	    } else {
1.359     albertel 4438: 		my %restored;
1.620     albertel 4439: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 4440: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   4441: 		} else {
                   4442: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   4443: 		}
1.335     albertel 4444: 		return $restored{$qualifierrest};
                   4445: 	    }
1.48      www      4446: # ----------------------------------------------------------------- user.access
                   4447:         } elsif ($space eq 'access') {
1.218     albertel 4448: 	    # FIXME - not supporting calls for a specific user
1.48      www      4449:             return &allowed($qualifier,$rest);
                   4450: # ------------------------------------------ user.preferences, user.environment
                   4451:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 4452: 	    if (($uname eq $env{'user.name'}) &&
                   4453: 		($udom eq $env{'user.domain'})) {
                   4454: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 4455: 	    } else {
1.359     albertel 4456: 		my %returnhash;
                   4457: 		if (!$publicuser) {
                   4458: 		    %returnhash=&userenvironment($udom,$uname,
                   4459: 						 $qualifierrest);
                   4460: 		}
1.218     albertel 4461: 		return $returnhash{$qualifierrest};
                   4462: 	    }
1.48      www      4463: # ----------------------------------------------------------------- user.course
                   4464:         } elsif ($space eq 'course') {
1.218     albertel 4465: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4466:             return $env{join('.',('request.course',$qualifier))};
1.48      www      4467: # ------------------------------------------------------------------- user.role
                   4468:         } elsif ($space eq 'role') {
1.218     albertel 4469: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4470:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      4471:             if ($qualifier eq 'value') {
                   4472: 		return $role;
                   4473:             } elsif ($qualifier eq 'extent') {
                   4474:                 return $where;
                   4475:             }
                   4476: # ----------------------------------------------------------------- user.domain
                   4477:         } elsif ($space eq 'domain') {
1.218     albertel 4478:             return $udom;
1.48      www      4479: # ------------------------------------------------------------------- user.name
                   4480:         } elsif ($space eq 'name') {
1.218     albertel 4481:             return $uname;
1.48      www      4482: # ---------------------------------------------------- Any other user namespace
1.29      www      4483:         } else {
1.359     albertel 4484: 	    my %reply;
                   4485: 	    if (!$publicuser) {
                   4486: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   4487: 	    }
                   4488: 	    return $reply{$qualifierrest};
1.48      www      4489:         }
1.236     www      4490:     } elsif ($realm eq 'query') {
                   4491: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 4492:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   4493: 						[$spacequalifierrest]);
1.620     albertel 4494: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      4495:    } elsif ($realm eq 'request') {
1.48      www      4496: # ------------------------------------------------------------- request.browser
                   4497:         if ($space eq 'browser') {
1.430     www      4498: 	    if ($qualifier eq 'textremote') {
                   4499: 		if (&mt('textual_remote_display') eq 'on') {
                   4500: 		    return 1;
                   4501: 		} else {
                   4502: 		    return 0;
                   4503: 		}
                   4504: 	    } else {
1.620     albertel 4505: 		return $env{'browser.'.$qualifier};
1.430     www      4506: 	    }
1.57      www      4507: # ------------------------------------------------------------ request.filename
                   4508:         } else {
1.620     albertel 4509:             return $env{'request.'.$spacequalifierrest};
1.29      www      4510:         }
1.28      www      4511:     } elsif ($realm eq 'course') {
1.48      www      4512: # ---------------------------------------------------------- course.description
1.620     albertel 4513:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      4514:     } elsif ($realm eq 'resource') {
1.165     www      4515: 
1.395     albertel 4516: 	my $section;
1.620     albertel 4517: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 4518: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   4519: 	}
1.593     albertel 4520: 	my ($courselevelm,$courselevel);
1.539     albertel 4521: 	if ($symbparm && defined($courseid) && 
1.620     albertel 4522: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      4523: 
1.218     albertel 4524: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      4525: 
1.60      www      4526: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 4527: 	    my $symbp=$symbparm;
1.409     www      4528: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 4529: 
                   4530: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   4531: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   4532: 
1.620     albertel 4533: 	    if (($env{'user.name'} eq $uname) &&
                   4534: 		($env{'user.domain'} eq $udom)) {
                   4535: 		$section=$env{'request.course.sec'};
1.218     albertel 4536: 	    } else {
1.539     albertel 4537: 		if (! defined($usection)) {
1.551     albertel 4538: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 4539: 		} else {
                   4540: 		    $section = $usection;
                   4541: 		}
1.218     albertel 4542: 	    }
                   4543: 
                   4544: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   4545: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   4546: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   4547: 
1.593     albertel 4548: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 4549: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 4550: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      4551: 
1.60      www      4552: # ----------------------------------------------------------- first, check user
1.624     albertel 4553: 
                   4554: 	    my $userreply=&resdata($uname,$udom,'user',
                   4555: 				       ($courselevelr,$courselevelm,
                   4556: 					$courselevel));
                   4557: 
                   4558: 	    if (defined($userreply)) { return $userreply; }
1.95      www      4559: 
1.594     albertel 4560: # ------------------------------------------------ second, check some of course
1.96      www      4561: 
1.624     albertel 4562: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   4563: 				     $env{'course.'.$courseid.'.domain'},
                   4564: 				     'course',
                   4565: 				     ($seclevelr,$seclevelm,$seclevel,
                   4566: 				      $courselevelr));
1.287     albertel 4567: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      4568: 
1.60      www      4569: # ------------------------------------------------------ third, check map parms
1.218     albertel 4570: 	    my %parmhash=();
                   4571: 	    my $thisparm='';
                   4572: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 4573: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 4574: 		    &GDBM_READER(),0640)) {
1.218     albertel 4575: 		$thisparm=$parmhash{$symbparm};
                   4576: 		untie(%parmhash);
                   4577: 	    }
                   4578: 	    if ($thisparm) { return $thisparm; }
                   4579: 	}
1.594     albertel 4580: # ------------------------------------------ fourth, look in resource metadata
1.71      www      4581: 
1.218     albertel 4582: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 4583: 	my $filename;
                   4584: 	if (!$symbparm) { $symbparm=&symbread(); }
                   4585: 	if ($symbparm) {
1.409     www      4586: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 4587: 	} else {
1.620     albertel 4588: 	    $filename=$env{'request.filename'};
1.282     albertel 4589: 	}
                   4590: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 4591: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 4592: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 4593: 	if (defined($metadata)) { return $metadata; }
1.142     www      4594: 
1.594     albertel 4595: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 4596: 	if ($symbparm && defined($courseid) && 
1.620     albertel 4597: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 4598: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   4599: 				     $env{'course.'.$courseid.'.domain'},
                   4600: 				     'course',
                   4601: 				     ($courselevelm,$courselevel));
1.593     albertel 4602: 	    if (defined($coursereply)) { return $coursereply; }
                   4603: 	}
1.145     www      4604: # ------------------------------------------------------------------ Cascade up
1.218     albertel 4605: 	unless ($space eq '0') {
1.336     albertel 4606: 	    my @parts=split(/_/,$space);
                   4607: 	    my $id=pop(@parts);
                   4608: 	    my $part=join('_',@parts);
                   4609: 	    if ($part eq '') { $part='0'; }
                   4610: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 4611: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 4612: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 4613: 	}
1.395     albertel 4614: 	if ($recurse) { return undef; }
                   4615: 	my $pack_def=&packages_tab_default($filename,$varname);
                   4616: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      4617: 
1.48      www      4618: # ---------------------------------------------------- Any other user namespace
                   4619:     } elsif ($realm eq 'environment') {
                   4620: # ----------------------------------------------------------------- environment
1.620     albertel 4621: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   4622: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 4623: 	} else {
                   4624: 	    my %returnhash=&userenvironment($udom,$uname,
                   4625: 					    $spacequalifierrest);
                   4626: 	    return $returnhash{$spacequalifierrest};
                   4627: 	}
1.28      www      4628:     } elsif ($realm eq 'system') {
1.48      www      4629: # ----------------------------------------------------------------- system.time
                   4630: 	if ($space eq 'time') {
                   4631: 	    return time;
                   4632:         }
1.28      www      4633:     }
1.48      www      4634:     return '';
1.61      www      4635: }
                   4636: 
1.395     albertel 4637: sub packages_tab_default {
                   4638:     my ($uri,$varname)=@_;
                   4639:     my (undef,$part,$name)=split(/\./,$varname);
                   4640:     my $packages=&metadata($uri,'packages');
                   4641:     foreach my $package (split(/,/,$packages)) {
                   4642: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 4643: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   4644: 	    return $packagetab{"$pack_type&$name&default"};
                   4645: 	}
1.585     albertel 4646: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 4647: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   4648: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 4649: 	}
                   4650:     }
                   4651:     return undef;
                   4652: }
                   4653: 
1.334     albertel 4654: sub add_prefix_and_part {
                   4655:     my ($prefix,$part)=@_;
                   4656:     my $keyroot;
                   4657:     if (defined($prefix) && $prefix !~ /^__/) {
                   4658: 	# prefix that has a part already
                   4659: 	$keyroot=$prefix;
                   4660:     } elsif (defined($prefix)) {
                   4661: 	# prefix that is missing a part
                   4662: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   4663:     } else {
                   4664: 	# no prefix at all
                   4665: 	if (defined($part)) { $keyroot='_'.$part; }
                   4666:     }
                   4667:     return $keyroot;
                   4668: }
                   4669: 
1.71      www      4670: # ---------------------------------------------------------------- Get metadata
                   4671: 
1.599     albertel 4672: my %metaentry;
1.71      www      4673: sub metadata {
1.176     www      4674:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      4675:     $uri=&declutter($uri);
1.288     albertel 4676:     # if it is a non metadata possible uri return quickly
1.529     albertel 4677:     if (($uri eq '') || 
                   4678: 	(($uri =~ m|^/*adm/|) && 
                   4679: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 4680:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 4681: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 4682: 	return undef;
1.288     albertel 4683:     }
1.73      www      4684:     my $filename=$uri;
                   4685:     $uri=~s/\.meta$//;
1.172     www      4686: #
                   4687: # Is the metadata already cached?
1.177     www      4688: # Look at timestamp of caching
1.172     www      4689: # Everything is cached by the main uri, libraries are never directly cached
                   4690: #
1.428     albertel 4691:     if (!defined($liburi)) {
1.599     albertel 4692: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 4693: 	if (defined($cached)) { return $result->{':'.$what}; }
                   4694:     }
                   4695:     {
1.172     www      4696: #
                   4697: # Is this a recursive call for a library?
                   4698: #
1.599     albertel 4699: #	if (! exists($metacache{$uri})) {
                   4700: #	    $metacache{$uri}={};
                   4701: #	}
1.171     www      4702:         if ($liburi) {
                   4703: 	    $liburi=&declutter($liburi);
                   4704:             $filename=$liburi;
1.401     bowersj2 4705:         } else {
1.599     albertel 4706: 	    &devalidate_cache_new('meta',$uri);
                   4707: 	    undef(%metaentry);
1.401     bowersj2 4708: 	}
1.140     www      4709:         my %metathesekeys=();
1.73      www      4710:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 4711: 	my $metastring;
1.609     banghart 4712: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 4713: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 4714: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 4715: 	    $metastring=&getfile($file);
1.489     albertel 4716: 	}
1.208     albertel 4717:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      4718:         my $token;
1.140     www      4719:         undef %metathesekeys;
1.71      www      4720:         while ($token=$parser->get_token) {
1.339     albertel 4721: 	    if ($token->[0] eq 'S') {
                   4722: 		if (defined($token->[2]->{'package'})) {
1.172     www      4723: #
                   4724: # This is a package - get package info
                   4725: #
1.339     albertel 4726: 		    my $package=$token->[2]->{'package'};
                   4727: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   4728: 		    if (defined($token->[2]->{'id'})) { 
                   4729: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   4730: 		    }
1.599     albertel 4731: 		    if ($metaentry{':packages'}) {
                   4732: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 4733: 		    } else {
1.599     albertel 4734: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 4735: 		    }
1.613     albertel 4736: 		    foreach (sort keys %packagetab) {
1.432     albertel 4737: 			my $part=$keyroot;
                   4738: 			$part=~s/^\_//;
                   4739: 			if ($_=~/^\Q$package\E\&/ || 
                   4740: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 4741: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 4742: 			    # ignore package.tab specified default values
                   4743:                             # here &package_tab_default() will fetch those
                   4744: 			    if ($subp eq 'default') { next; }
1.339     albertel 4745: 			    my $value=$packagetab{$_};
1.432     albertel 4746: 			    my $unikey;
                   4747: 			    if ($pack =~ /_0$/) {
                   4748: 				$unikey='parameter_0_'.$name;
                   4749: 				$part=0;
                   4750: 			    } else {
                   4751: 				$unikey='parameter'.$keyroot.'_'.$name;
                   4752: 			    }
1.339     albertel 4753: 			    if ($subp eq 'display') {
                   4754: 				$value.=' [Part: '.$part.']';
                   4755: 			    }
1.599     albertel 4756: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 4757: 			    $metathesekeys{$unikey}=1;
1.599     albertel 4758: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   4759: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 4760: 			    }
1.599     albertel 4761: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   4762: 				$metaentry{':'.$unikey}=
                   4763: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 4764: 			    }
1.339     albertel 4765: 			}
                   4766: 		    }
                   4767: 		} else {
1.172     www      4768: #
                   4769: # This is not a package - some other kind of start tag
1.339     albertel 4770: #
                   4771: 		    my $entry=$token->[1];
                   4772: 		    my $unikey;
                   4773: 		    if ($entry eq 'import') {
                   4774: 			$unikey='';
                   4775: 		    } else {
                   4776: 			$unikey=$entry;
                   4777: 		    }
                   4778: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   4779: 
                   4780: 		    if (defined($token->[2]->{'id'})) { 
                   4781: 			$unikey.='_'.$token->[2]->{'id'}; 
                   4782: 		    }
1.175     www      4783: 
1.339     albertel 4784: 		    if ($entry eq 'import') {
1.175     www      4785: #
                   4786: # Importing a library here
1.339     albertel 4787: #
                   4788: 			if ($depthcount<20) {
                   4789: 			    my $location=$parser->get_text('/import');
                   4790: 			    my $dir=$filename;
                   4791: 			    $dir=~s|[^/]*$||;
                   4792: 			    $location=&filelocation($dir,$location);
                   4793: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   4794: 							       $location,$unikey,
                   4795: 							       $depthcount+1)))) {
1.599     albertel 4796: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 4797: 				$metathesekeys{$_}=1;
                   4798: 			    }
                   4799: 			}
                   4800: 		    } else { 
                   4801: 			
                   4802: 			if (defined($token->[2]->{'name'})) { 
                   4803: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   4804: 			}
                   4805: 			$metathesekeys{$unikey}=1;
                   4806: 			foreach (@{$token->[3]}) {
1.599     albertel 4807: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 4808: 			}
                   4809: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 4810: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 4811: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   4812: 		 # only ws inside the tag, and not in default, so use default
                   4813: 		 # as value
1.599     albertel 4814: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 4815: 			} else {
1.321     albertel 4816: 		  # either something interesting inside the tag or default
                   4817:                   # uninteresting
1.599     albertel 4818: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 4819: 			}
1.172     www      4820: # end of not-a-package not-a-library import
1.339     albertel 4821: 		    }
1.172     www      4822: # end of not-a-package start tag
1.339     albertel 4823: 		}
1.172     www      4824: # the next is the end of "start tag"
1.339     albertel 4825: 	    }
                   4826: 	}
1.483     albertel 4827: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   4828: 	foreach my $key (sort(keys(%packagetab))) {
                   4829: 	    #no specific packages #how's our extension
                   4830: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 4831: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 4832: 					 \%metathesekeys);
                   4833: 	}
1.599     albertel 4834: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 4835: 	    foreach my $key (sort(keys(%packagetab))) {
                   4836: 		#no specific packages well let's get default then
                   4837: 		if ($key!~/^default&/) { next; }
1.488     albertel 4838: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 4839: 					     \%metathesekeys);
                   4840: 	    }
                   4841: 	}
1.338     www      4842: # are there custom rights to evaluate
1.599     albertel 4843: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 4844: 
1.338     www      4845:     #
                   4846:     # Importing a rights file here
1.339     albertel 4847:     #
                   4848: 	    unless ($depthcount) {
1.599     albertel 4849: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 4850: 		my $dir=$filename;
                   4851: 		$dir=~s|[^/]*$||;
                   4852: 		$location=&filelocation($dir,$location);
                   4853: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   4854: 						   $location,'_rights',
                   4855: 						   $depthcount+1)))) {
1.599     albertel 4856: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 4857: 		    $metathesekeys{$_}=1;
                   4858: 		}
                   4859: 	    }
                   4860: 	}
1.599     albertel 4861: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   4862: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   4863: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.623     albertel 4864: 	&do_cache_new('meta',$uri,\%metaentry,60*60*24);
1.177     www      4865: # this is the end of "was not already recently cached
1.71      www      4866:     }
1.599     albertel 4867:     return $metaentry{':'.$what};
1.261     albertel 4868: }
                   4869: 
1.488     albertel 4870: sub metadata_create_package_def {
1.483     albertel 4871:     my ($uri,$key,$package,$metathesekeys)=@_;
                   4872:     my ($pack,$name,$subp)=split(/\&/,$key);
                   4873:     if ($subp eq 'default') { next; }
                   4874:     
1.599     albertel 4875:     if (defined($metaentry{':packages'})) {
                   4876: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 4877:     } else {
1.599     albertel 4878: 	$metaentry{':packages'}=$package;
1.483     albertel 4879:     }
                   4880:     my $value=$packagetab{$key};
                   4881:     my $unikey;
                   4882:     $unikey='parameter_0_'.$name;
1.599     albertel 4883:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 4884:     $$metathesekeys{$unikey}=1;
1.599     albertel 4885:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   4886: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 4887:     }
1.599     albertel 4888:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   4889: 	$metaentry{':'.$unikey}=
                   4890: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 4891:     }
                   4892: }
                   4893: 
1.261     albertel 4894: sub metadata_generate_part0 {
                   4895:     my ($metadata,$metacache,$uri) = @_;
                   4896:     my %allnames;
                   4897:     foreach my $metakey (sort keys %$metadata) {
                   4898: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 4899: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   4900: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 4901: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 4902: 	    $allnames{$name}=$part;
                   4903: 	  }
                   4904: 	}
                   4905:     }
                   4906:     foreach my $name (keys(%allnames)) {
                   4907:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 4908:       my $key=":parameter_0_$name";
1.261     albertel 4909:       $$metacache{"$key.part"}='0';
                   4910:       $$metacache{"$key.name"}=$name;
1.428     albertel 4911:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 4912: 					   $allnames{$name}.'_'.$name.
                   4913: 					   '.type'};
1.428     albertel 4914:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 4915: 			     '.display'};
1.644     www      4916:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 4917:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 4918:       $$metacache{"$key.display"}=$olddis;
                   4919:     }
1.71      www      4920: }
                   4921: 
1.301     www      4922: # ------------------------------------------------- Get the title of a resource
                   4923: 
                   4924: sub gettitle {
                   4925:     my $urlsymb=shift;
                   4926:     my $symb=&symbread($urlsymb);
1.534     albertel 4927:     if ($symb) {
1.620     albertel 4928: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 4929: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 4930: 	if (defined($cached)) { 
                   4931: 	    return $result;
                   4932: 	}
1.534     albertel 4933: 	my ($map,$resid,$url)=&decode_symb($symb);
                   4934: 	my $title='';
                   4935: 	my %bighash;
1.620     albertel 4936: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 4937: 		&GDBM_READER(),0640)) {
                   4938: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   4939: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   4940: 	    untie %bighash;
                   4941: 	}
                   4942: 	$title=~s/\&colon\;/\:/gs;
                   4943: 	if ($title) {
1.599     albertel 4944: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 4945: 	}
                   4946: 	$urlsymb=$url;
                   4947:     }
                   4948:     my $title=&metadata($urlsymb,'title');
                   4949:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   4950:     return $title;
1.301     www      4951: }
1.613     albertel 4952: 
1.614     albertel 4953: sub get_slot {
                   4954:     my ($which,$cnum,$cdom)=@_;
                   4955:     if (!$cnum || !$cdom) {
                   4956: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 4957: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   4958: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 4959:     }
                   4960:     my %slotinfo=&get('slots',[$which],$cdom,$cnum);
                   4961:     &Apache::lonhomework::showhash(%slotinfo);
                   4962:     my ($tmp)=keys(%slotinfo);
                   4963:     if ($tmp=~/^error:/) { return (); }
1.616     albertel 4964:     if (ref($slotinfo{$which}) eq 'HASH') {
                   4965: 	return %{$slotinfo{$which}};
                   4966:     }
                   4967:     return $slotinfo{$which};
1.614     albertel 4968: }
1.31      www      4969: # ------------------------------------------------- Update symbolic store links
                   4970: 
                   4971: sub symblist {
                   4972:     my ($mapname,%newhash)=@_;
1.438     www      4973:     $mapname=&deversion(&declutter($mapname));
1.31      www      4974:     my %hash;
1.620     albertel 4975:     if (($env{'request.course.fn'}) && (%newhash)) {
                   4976:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 4977:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 4978: 	    foreach (keys %newhash) {
1.601     albertel 4979:                 $hash{declutter($_)}=&encode_symb($mapname,$newhash{$_}->[1],
                   4980: 						  $newhash{$_}->[0]);
1.191     harris41 4981:             }
1.31      www      4982:             if (untie(%hash)) {
                   4983: 		return 'ok';
                   4984:             }
                   4985:         }
                   4986:     }
                   4987:     return 'error';
1.212     www      4988: }
                   4989: 
                   4990: # --------------------------------------------------------------- Verify a symb
                   4991: 
                   4992: sub symbverify {
1.510     www      4993:     my ($symb,$thisurl)=@_;
                   4994:     my $thisfn=$thisurl;
                   4995: # wrapper not part of symbs
                   4996:     $thisfn=~s/^\/adm\/wrapper//;
1.439     www      4997:     $thisfn=&declutter($thisfn);
1.215     www      4998: # direct jump to resource in page or to a sequence - will construct own symbs
                   4999:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5000: # check URL part
1.409     www      5001:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5002: 
1.431     www      5003:     unless ($url eq $thisfn) { return 0; }
1.213     www      5004: 
1.216     www      5005:     $symb=&symbclean($symb);
1.510     www      5006:     $thisurl=&deversion($thisurl);
1.439     www      5007:     $thisfn=&deversion($thisfn);
1.213     www      5008: 
                   5009:     my %bighash;
                   5010:     my $okay=0;
1.431     www      5011: 
1.620     albertel 5012:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5013:                             &GDBM_READER(),0640)) {
1.510     www      5014:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5015:         unless ($ids) { 
1.510     www      5016:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5017:         }
                   5018:         if ($ids) {
                   5019: # ------------------------------------------------------------------- Has ID(s)
                   5020: 	    foreach (split(/\,/,$ids)) {
1.644     www      5021: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5022:                if (
                   5023:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5024:    eq $symb) { 
1.620     albertel 5025: 		   if (($env{'request.role.adv'}) ||
                   5026: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5027: 		       $okay=1; 
                   5028: 		   }
                   5029: 	       }
1.216     www      5030: 	   }
                   5031:         }
1.213     www      5032: 	untie(%bighash);
                   5033:     }
                   5034:     return $okay;
1.31      www      5035: }
                   5036: 
1.210     www      5037: # --------------------------------------------------------------- Clean-up symb
                   5038: 
                   5039: sub symbclean {
                   5040:     my $symb=shift;
1.568     albertel 5041:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5042: # remove version from map
                   5043:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      5044: 
1.210     www      5045: # remove version from URL
                   5046:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      5047: 
1.507     www      5048: # remove wrapper
                   5049: 
1.510     www      5050:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.210     www      5051:     return $symb;
1.409     www      5052: }
                   5053: 
                   5054: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 5055: 
                   5056: sub encode_symb {
                   5057:     my ($map,$resid,$url)=@_;
                   5058:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   5059: }
1.409     www      5060: 
                   5061: sub decode_symb {
1.568     albertel 5062:     my $symb=shift;
                   5063:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   5064:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      5065:     return (&fixversion($map),$resid,&fixversion($url));
                   5066: }
                   5067: 
                   5068: sub fixversion {
                   5069:     my $fn=shift;
1.609     banghart 5070:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      5071:     my %bighash;
                   5072:     my $uri=&clutter($fn);
1.620     albertel 5073:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      5074: # is this cached?
1.599     albertel 5075:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      5076:     if (defined($cached)) { return $result; }
                   5077: # unfortunately not cached, or expired
1.620     albertel 5078:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      5079: 	    &GDBM_READER(),0640)) {
                   5080:  	if ($bighash{'version_'.$uri}) {
                   5081:  	    my $version=$bighash{'version_'.$uri};
1.444     www      5082:  	    unless (($version eq 'mostrecent') || 
                   5083: 		    ($version==&getversion($uri))) {
1.440     www      5084:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   5085:  	    }
                   5086:  	}
                   5087:  	untie %bighash;
1.413     www      5088:     }
1.599     albertel 5089:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      5090: }
                   5091: 
                   5092: sub deversion {
                   5093:     my $url=shift;
                   5094:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   5095:     return $url;
1.210     www      5096: }
                   5097: 
1.31      www      5098: # ------------------------------------------------------ Return symb list entry
                   5099: 
                   5100: sub symbread {
1.249     www      5101:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 5102:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 5103:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      5104: # no filename provided? try from environment
1.44      www      5105:     unless ($thisfn) {
1.620     albertel 5106:         if ($env{'request.symb'}) {
                   5107: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 5108: 	}
1.620     albertel 5109: 	$thisfn=$env{'request.filename'};
1.44      www      5110:     }
1.569     albertel 5111:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      5112: # is that filename actually a symb? Verify, clean, and return
                   5113:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 5114: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 5115: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 5116: 	}
1.242     www      5117:     }
1.44      www      5118:     $thisfn=declutter($thisfn);
1.31      www      5119:     my %hash;
1.37      www      5120:     my %bighash;
                   5121:     my $syval='';
1.620     albertel 5122:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  5123:         my $targetfn = $thisfn;
1.609     banghart 5124:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  5125:             $targetfn = 'adm/wrapper/'.$thisfn;
                   5126:         }
1.620     albertel 5127:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5128:                       &GDBM_READER(),0640)) {
1.481     raeburn  5129: 	    $syval=$hash{$targetfn};
1.37      www      5130:             untie(%hash);
                   5131:         }
                   5132: # ---------------------------------------------------------- There was an entry
                   5133:         if ($syval) {
1.601     albertel 5134: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 5135: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 5136: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 5137: 		    #return $env{$cache_str}='';
1.601     albertel 5138: 		#}    
                   5139: 		#$syval.=$1;
                   5140: 	    #}
1.37      www      5141:         } else {
                   5142: # ------------------------------------------------------- Was not in symb table
1.620     albertel 5143:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5144:                             &GDBM_READER(),0640)) {
1.37      www      5145: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      5146:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      5147:               unless ($ids) { 
                   5148:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      5149:               }
                   5150:               unless ($ids) {
                   5151: # alias?
                   5152: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      5153:               }
1.37      www      5154:               if ($ids) {
                   5155: # ------------------------------------------------------------------- Has ID(s)
                   5156:                  my @possibilities=split(/\,/,$ids);
1.39      www      5157:                  if ($#possibilities==0) {
                   5158: # ----------------------------------------------- There is only one possibility
1.37      www      5159: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 5160: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5161: 						    $resid,$thisfn);
1.249     www      5162:                  } elsif (!$donotrecurse) {
1.39      www      5163: # ------------------------------------------ There is more than one possibility
                   5164:                      my $realpossible=0;
1.191     harris41 5165:                      foreach (@possibilities) {
1.39      www      5166: 			 my $file=$bighash{'src_'.$_};
                   5167:                          if (&allowed('bre',$file)) {
                   5168:          		    my ($mapid,$resid)=split(/\./,$_);
                   5169:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   5170: 				$realpossible++;
1.626     albertel 5171:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5172: 						    $resid,$thisfn);
1.39      www      5173:                             }
                   5174: 			 }
1.191     harris41 5175:                      }
1.39      www      5176: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      5177:                  } else {
                   5178:                      $syval='';
1.37      www      5179:                  }
                   5180: 	      }
                   5181:               untie(%bighash)
1.481     raeburn  5182:            }
1.31      www      5183:         }
1.62      www      5184:         if ($syval) {
1.620     albertel 5185: 	    return $env{$cache_str}=$syval;
1.62      www      5186:         }
1.31      www      5187:     }
1.44      www      5188:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 5189:     return $env{$cache_str}='';
1.31      www      5190: }
                   5191: 
                   5192: # ---------------------------------------------------------- Return random seed
                   5193: 
1.32      www      5194: sub numval {
                   5195:     my $txt=shift;
                   5196:     $txt=~tr/A-J/0-9/;
                   5197:     $txt=~tr/a-j/0-9/;
                   5198:     $txt=~tr/K-T/0-9/;
                   5199:     $txt=~tr/k-t/0-9/;
                   5200:     $txt=~tr/U-Z/0-5/;
                   5201:     $txt=~tr/u-z/0-5/;
                   5202:     $txt=~s/\D//g;
1.564     albertel 5203:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      5204:     return int($txt);
1.368     albertel 5205: }
                   5206: 
1.484     albertel 5207: sub numval2 {
                   5208:     my $txt=shift;
                   5209:     $txt=~tr/A-J/0-9/;
                   5210:     $txt=~tr/a-j/0-9/;
                   5211:     $txt=~tr/K-T/0-9/;
                   5212:     $txt=~tr/k-t/0-9/;
                   5213:     $txt=~tr/U-Z/0-5/;
                   5214:     $txt=~tr/u-z/0-5/;
                   5215:     $txt=~s/\D//g;
                   5216:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5217:     my $total;
                   5218:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5219:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5220:     return int($total);
                   5221: }
                   5222: 
1.575     albertel 5223: sub numval3 {
                   5224:     use integer;
                   5225:     my $txt=shift;
                   5226:     $txt=~tr/A-J/0-9/;
                   5227:     $txt=~tr/a-j/0-9/;
                   5228:     $txt=~tr/K-T/0-9/;
                   5229:     $txt=~tr/k-t/0-9/;
                   5230:     $txt=~tr/U-Z/0-5/;
                   5231:     $txt=~tr/u-z/0-5/;
                   5232:     $txt=~s/\D//g;
                   5233:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5234:     my $total;
                   5235:     foreach my $val (@txts) { $total+=$val; }
                   5236:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5237:     return $total;
                   5238: }
                   5239: 
1.368     albertel 5240: sub latest_rnd_algorithm_id {
1.575     albertel 5241:     return '64bit4';
1.366     albertel 5242: }
1.32      www      5243: 
1.503     albertel 5244: sub get_rand_alg {
                   5245:     my ($courseid)=@_;
                   5246:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   5247:     if ($courseid) {
1.620     albertel 5248: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 5249:     }
                   5250:     return &latest_rnd_algorithm_id();
                   5251: }
                   5252: 
1.562     albertel 5253: sub validCODE {
                   5254:     my ($CODE)=@_;
                   5255:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5256:     return 0;
                   5257: }
                   5258: 
1.491     albertel 5259: sub getCODE {
1.620     albertel 5260:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 5261:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   5262: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   5263: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5264: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5265:     }
                   5266:     return undef;
                   5267: }
                   5268: 
1.31      www      5269: sub rndseed {
1.155     albertel 5270:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5271: 
                   5272:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5273:     if (!$symb) {
1.366     albertel 5274: 	unless ($symb=$wsymb) { return time; }
                   5275:     }
                   5276:     if (!$courseid) { $courseid=$wcourseid; }
                   5277:     if (!$domain) { $domain=$wdomain; }
                   5278:     if (!$username) { $username=$wusername }
1.503     albertel 5279:     my $which=&get_rand_alg();
1.491     albertel 5280:     if (defined(&getCODE())) {
1.575     albertel 5281: 	if ($which eq '64bit4') {
                   5282: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5283: 	} else {
                   5284: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5285: 	}
                   5286:     } elsif ($which eq '64bit4') {
                   5287: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 5288:     } elsif ($which eq '64bit3') {
                   5289: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 5290:     } elsif ($which eq '64bit2') {
                   5291: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 5292:     } elsif ($which eq '64bit') {
                   5293: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   5294:     }
                   5295:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   5296: }
                   5297: 
                   5298: sub rndseed_32bit {
                   5299:     my ($symb,$courseid,$domain,$username)=@_;
                   5300:     {
                   5301: 	use integer;
                   5302: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   5303: 	my $symbseed=numval($symb) << 22;
                   5304: 	my $namechck=unpack("%32C*",$username) << 17;
                   5305: 	my $nameseed=numval($username) << 12;
                   5306: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   5307: 	my $courseseed=unpack("%32C*",$courseid);
                   5308: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   5309: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5310: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5311: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 5312: 	return $num;
                   5313:     }
                   5314: }
                   5315: 
                   5316: sub rndseed_64bit {
                   5317:     my ($symb,$courseid,$domain,$username)=@_;
                   5318:     {
                   5319: 	use integer;
                   5320: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   5321: 	my $symbseed=numval($symb) << 10;
                   5322: 	my $namechck=unpack("%32S*",$username);
                   5323: 	
                   5324: 	my $nameseed=numval($username) << 21;
                   5325: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   5326: 	my $courseseed=unpack("%32S*",$courseid);
                   5327: 	
                   5328: 	my $num1=$symbchck+$symbseed+$namechck;
                   5329: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5330: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5331: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5332: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5333: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 5334: 	return "$num1,$num2";
1.155     albertel 5335:     }
1.366     albertel 5336: }
                   5337: 
1.443     albertel 5338: sub rndseed_64bit2 {
                   5339:     my ($symb,$courseid,$domain,$username)=@_;
                   5340:     {
                   5341: 	use integer;
                   5342: 	# strings need to be an even # of cahracters long, it it is odd the
                   5343:         # last characters gets thrown away
                   5344: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5345: 	my $symbseed=numval($symb) << 10;
                   5346: 	my $namechck=unpack("%32S*",$username.' ');
                   5347: 	
                   5348: 	my $nameseed=numval($username) << 21;
1.501     albertel 5349: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5350: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5351: 	
                   5352: 	my $num1=$symbchck+$symbseed+$namechck;
                   5353: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5354: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5355: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   5356: 	return "$num1,$num2";
                   5357:     }
                   5358: }
                   5359: 
                   5360: sub rndseed_64bit3 {
                   5361:     my ($symb,$courseid,$domain,$username)=@_;
                   5362:     {
                   5363: 	use integer;
                   5364: 	# strings need to be an even # of cahracters long, it it is odd the
                   5365:         # last characters gets thrown away
                   5366: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5367: 	my $symbseed=numval2($symb) << 10;
                   5368: 	my $namechck=unpack("%32S*",$username.' ');
                   5369: 	
                   5370: 	my $nameseed=numval2($username) << 21;
1.443     albertel 5371: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5372: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5373: 	
                   5374: 	my $num1=$symbchck+$symbseed+$namechck;
                   5375: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5376: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 5377: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5378: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5379: 	
1.503     albertel 5380: 	return "$num1:$num2";
1.443     albertel 5381:     }
                   5382: }
                   5383: 
1.575     albertel 5384: sub rndseed_64bit4 {
                   5385:     my ($symb,$courseid,$domain,$username)=@_;
                   5386:     {
                   5387: 	use integer;
                   5388: 	# strings need to be an even # of cahracters long, it it is odd the
                   5389:         # last characters gets thrown away
                   5390: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5391: 	my $symbseed=numval3($symb) << 10;
                   5392: 	my $namechck=unpack("%32S*",$username.' ');
                   5393: 	
                   5394: 	my $nameseed=numval3($username) << 21;
                   5395: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5396: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5397: 	
                   5398: 	my $num1=$symbchck+$symbseed+$namechck;
                   5399: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5400: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5401: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5402: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5403: 	
                   5404: 	return "$num1:$num2";
                   5405:     }
                   5406: }
                   5407: 
1.366     albertel 5408: sub rndseed_CODE_64bit {
                   5409:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 5410:     {
1.366     albertel 5411: 	use integer;
1.443     albertel 5412: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 5413: 	my $symbseed=numval2($symb);
1.491     albertel 5414: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5415: 	my $CODEseed=numval(&getCODE());
1.443     albertel 5416: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 5417: 	my $num1=$symbseed+$CODEchck;
                   5418: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5419: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 5420: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 5421: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5422: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 5423: 	return "$num1:$num2";
1.366     albertel 5424:     }
                   5425: }
                   5426: 
1.575     albertel 5427: sub rndseed_CODE_64bit4 {
                   5428:     my ($symb,$courseid,$domain,$username)=@_;
                   5429:     {
                   5430: 	use integer;
                   5431: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   5432: 	my $symbseed=numval3($symb);
                   5433: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5434: 	my $CODEseed=numval3(&getCODE());
                   5435: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5436: 	my $num1=$symbseed+$CODEchck;
                   5437: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5438: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   5439: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   5440: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5441: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   5442: 	return "$num1:$num2";
                   5443:     }
                   5444: }
                   5445: 
1.366     albertel 5446: sub setup_random_from_rndseed {
                   5447:     my ($rndseed)=@_;
1.503     albertel 5448:     if ($rndseed =~/([,:])/) {
                   5449: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 5450: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   5451:     } else {
                   5452: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 5453:     }
1.36      albertel 5454: }
                   5455: 
1.474     albertel 5456: sub latest_receipt_algorithm_id {
                   5457:     return 'receipt2';
                   5458: }
                   5459: 
1.480     www      5460: sub recunique {
                   5461:     my $fucourseid=shift;
                   5462:     my $unique;
1.620     albertel 5463:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5464: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      5465:     } else {
                   5466: 	$unique=$perlvar{'lonReceipt'};
                   5467:     }
                   5468:     return unpack("%32C*",$unique);
                   5469: }
                   5470: 
                   5471: sub recprefix {
                   5472:     my $fucourseid=shift;
                   5473:     my $prefix;
1.620     albertel 5474:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5475: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      5476:     } else {
                   5477: 	$prefix=$perlvar{'lonHostID'};
                   5478:     }
                   5479:     return unpack("%32C*",$prefix);
                   5480: }
                   5481: 
1.76      www      5482: sub ireceipt {
1.474     albertel 5483:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      5484:     my $cuname=unpack("%32C*",$funame);
                   5485:     my $cudom=unpack("%32C*",$fudom);
                   5486:     my $cucourseid=unpack("%32C*",$fucourseid);
                   5487:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      5488:     my $cunique=&recunique($fucourseid);
1.474     albertel 5489:     my $cpart=unpack("%32S*",$part);
1.480     www      5490:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 5491:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   5492: 	$env{'request.state'} eq 'construct') {
1.474     albertel 5493: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   5494: 			       " and ".($cpart%$cudom));
                   5495: 			       
                   5496: 	$return.= ($cunique%$cuname+
                   5497: 		   $cunique%$cudom+
                   5498: 		   $cusymb%$cuname+
                   5499: 		   $cusymb%$cudom+
                   5500: 		   $cucourseid%$cuname+
                   5501: 		   $cucourseid%$cudom+
                   5502: 		   $cpart%$cuname+
                   5503: 		   $cpart%$cudom);
                   5504:     } else {
                   5505: 	$return.= ($cunique%$cuname+
                   5506: 		   $cunique%$cudom+
                   5507: 		   $cusymb%$cuname+
                   5508: 		   $cusymb%$cudom+
                   5509: 		   $cucourseid%$cuname+
                   5510: 		   $cucourseid%$cudom);
                   5511:     }
                   5512:     return $return;
1.76      www      5513: }
                   5514: 
                   5515: sub receipt {
1.474     albertel 5516:     my ($part)=@_;
                   5517:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   5518:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      5519: }
1.260     ng       5520: 
1.36      albertel 5521: # ------------------------------------------------------------ Serves up a file
1.472     albertel 5522: # returns either the contents of the file or 
                   5523: # -1 if the file doesn't exist
1.481     raeburn  5524: #
                   5525: # if the target is a file that was uploaded via DOCS, 
                   5526: # a check will be made to see if a current copy exists on the local server,
                   5527: # if it does this will be served, otherwise a copy will be retrieved from
                   5528: # the home server for the course and stored in /home/httpd/html/userfiles on
                   5529: # the local server.   
1.472     albertel 5530: 
1.36      albertel 5531: sub getfile {
1.538     albertel 5532:     my ($file) = @_;
1.609     banghart 5533:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 5534:     &repcopy($file);
                   5535:     return &readfile($file);
                   5536: }
                   5537: 
                   5538: sub repcopy_userfile {
                   5539:     my ($file)=@_;
1.609     banghart 5540:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 5541:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 5542:     my ($cdom,$cnum,$filename) = 
                   5543: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   5544:     my ($info,$rtncode);
                   5545:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   5546:     if (-e "$file") {
                   5547: 	my @fileinfo = stat($file);
                   5548: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5549: 	if ($lwpresp ne 'ok') {
                   5550: 	    if ($rtncode eq '404') {
1.538     albertel 5551: 		unlink($file);
1.482     albertel 5552: 	    }
1.517     albertel 5553: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 5554: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5555: 	    #my $response=$ua->request($request);
                   5556: 	    #if ($response->is_success()) {
                   5557: 	#	return $response->content;
                   5558: 	#    } else {
                   5559: 	#	return -1;
                   5560: 	#    }
1.482     albertel 5561: 	    return -1;
                   5562: 	}
                   5563: 	if ($info < $fileinfo[9]) {
1.607     raeburn  5564: 	    return 'ok';
1.482     albertel 5565: 	}
                   5566: 	$info = '';
1.538     albertel 5567: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5568: 	if ($lwpresp ne 'ok') {
                   5569: 	    return -1;
                   5570: 	}
                   5571:     } else {
1.538     albertel 5572: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5573: 	if ($lwpresp ne 'ok') {
1.517     albertel 5574: 	    my $ua=new LWP::UserAgent;
1.538     albertel 5575: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5576: 	    my $response=$ua->request($request);
                   5577: 	    if ($response->is_success()) {
1.538     albertel 5578: 		$info=$response->content;
1.517     albertel 5579: 	    } else {
                   5580: 		return -1;
                   5581: 	    }
1.482     albertel 5582: 	}
                   5583: 	my @parts = ($cdom,$cnum); 
                   5584: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   5585: 	    push @parts, split(/\//,$1);
1.518     albertel 5586: 	}
1.538     albertel 5587: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 5588: 	foreach my $part (@parts) {
                   5589: 	    $path .= '/'.$part;
                   5590: 	    if (!-e $path) {
                   5591: 		mkdir($path,0770);
                   5592: 	    }
                   5593: 	}
                   5594:     }
1.538     albertel 5595:     open(FILE,">$file");
1.482     albertel 5596:     print FILE $info;
                   5597:     close(FILE);
1.607     raeburn  5598:     return 'ok';
1.481     raeburn  5599: }
                   5600: 
1.517     albertel 5601: sub tokenwrapper {
                   5602:     my $uri=shift;
1.552     albertel 5603:     $uri=~s|^http\://([^/]+)||;
                   5604:     $uri=~s|^/||;
1.620     albertel 5605:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 5606:     my $token=$1;
1.552     albertel 5607:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   5608:     if ($udom && $uname && $file) {
                   5609: 	$file=~s|(\?\.*)*$||;
1.620     albertel 5610:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 5611:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 5612:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   5613:                                '&tokenissued='.$perlvar{'lonHostID'};
                   5614:     } else {
                   5615:         return '/adm/notfound.html';
                   5616:     }
                   5617: }
                   5618: 
1.481     raeburn  5619: sub getuploaded {
                   5620:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   5621:     $uri=~s/^\///;
                   5622:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   5623:     my $ua=new LWP::UserAgent;
                   5624:     my $request=new HTTP::Request($reqtype,$uri);
                   5625:     my $response=$ua->request($request);
                   5626:     $$rtncode = $response->code;
1.482     albertel 5627:     if (! $response->is_success()) {
                   5628: 	return 'failed';
                   5629:     }      
                   5630:     if ($reqtype eq 'HEAD') {
1.486     www      5631: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 5632:     } elsif ($reqtype eq 'GET') {
                   5633: 	$$info = $response->content;
1.472     albertel 5634:     }
1.482     albertel 5635:     return 'ok';
1.36      albertel 5636: }
                   5637: 
1.481     raeburn  5638: sub readfile {
                   5639:     my $file = shift;
                   5640:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   5641:     my $fh;
                   5642:     open($fh,"<$file");
                   5643:     my $a='';
                   5644:     while (<$fh>) { $a .=$_; }
                   5645:     return $a;
                   5646: }
                   5647: 
1.36      albertel 5648: sub filelocation {
1.590     banghart 5649:     my ($dir,$file) = @_;
                   5650:     my $location;
                   5651:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
                   5652:     if ($file=~m:^/~:) { # is a contruction space reference
                   5653:         $location = $file;
                   5654:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 5655:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   5656: 	# is a correct contruction space reference
                   5657:         $location = $file;
1.609     banghart 5658:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 5659:         my ($udom,$uname,$filename)=
1.609     banghart 5660:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 5661:         my $home=&homeserver($uname,$udom);
                   5662:         my $is_me=0;
                   5663:         my @ids=&current_machine_ids();
                   5664:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   5665:         if ($is_me) {
                   5666:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   5667:   	      '/userfiles/'.$filename;
                   5668:         } else {
                   5669:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   5670:   	      $udom.'/'.$uname.'/'.$filename;
                   5671:         }
                   5672:     } else {
                   5673:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   5674:         $file=~s:^/res/:/:;
                   5675:         if ( !( $file =~ m:^/:) ) {
                   5676:             $location = $dir. '/'.$file;
                   5677:         } else {
                   5678:             $location = '/home/httpd/html/res'.$file;
                   5679:         }
1.59      albertel 5680:     }
1.590     banghart 5681:     $location=~s://+:/:g; # remove duplicate /
                   5682:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   5683:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   5684:     return $location;
1.46      www      5685: }
1.36      albertel 5686: 
1.46      www      5687: sub hreflocation {
                   5688:     my ($dir,$file)=@_;
1.460     albertel 5689:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
                   5690: 	my $finalpath=filelocation($dir,$file);
                   5691: 	$finalpath=~s-^/home/httpd/html--;
1.462     albertel 5692: 	$finalpath=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460     albertel 5693: 	return $finalpath;
                   5694:     } elsif ($file=~m-^/home-) {
                   5695: 	$file=~s-^/home/httpd/html--;
1.462     albertel 5696: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460     albertel 5697: 	return $file;
1.46      www      5698:     }
1.462     albertel 5699:     return $file;
1.465     albertel 5700: }
                   5701: 
                   5702: sub current_machine_domains {
                   5703:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   5704:     my @domains;
                   5705:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  5706: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 5707: 	if ($hostname eq $name) {
                   5708: 	    push(@domains,$hostdom{$id});
                   5709: 	}
                   5710:     }
                   5711:     return @domains;
                   5712: }
                   5713: 
                   5714: sub current_machine_ids {
                   5715:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   5716:     my @ids;
                   5717:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  5718: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 5719: 	if ($hostname eq $name) {
                   5720: 	    push(@ids,$id);
                   5721: 	}
                   5722:     }
                   5723:     return @ids;
1.31      www      5724: }
                   5725: 
                   5726: # ------------------------------------------------------------- Declutters URLs
                   5727: 
                   5728: sub declutter {
                   5729:     my $thisfn=shift;
1.569     albertel 5730:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 5731:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      5732:     $thisfn=~s/^\///;
                   5733:     $thisfn=~s/^res\///;
1.235     www      5734:     $thisfn=~s/\?.+$//;
1.268     www      5735:     return $thisfn;
                   5736: }
                   5737: 
                   5738: # ------------------------------------------------------------- Clutter up URLs
                   5739: 
                   5740: sub clutter {
                   5741:     my $thisfn='/'.&declutter(shift);
1.609     banghart 5742:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      5743:        $thisfn='/res'.$thisfn; 
                   5744:     }
1.31      www      5745:     return $thisfn;
1.12      www      5746: }
                   5747: 
1.557     albertel 5748: sub freeze_escape {
                   5749:     my ($value)=@_;
                   5750:     if (ref($value)) {
                   5751: 	$value=&nfreeze($value);
                   5752: 	return '__FROZEN__'.&escape($value);
                   5753:     }
                   5754:     return &escape($value);
                   5755: }
                   5756: 
1.12      www      5757: # -------------------------------------------------------- Escape Special Chars
                   5758: 
                   5759: sub escape {
                   5760:     my $str=shift;
                   5761:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   5762:     return $str;
                   5763: }
                   5764: 
                   5765: # ----------------------------------------------------- Un-Escape Special Chars
                   5766: 
                   5767: sub unescape {
                   5768:     my $str=shift;
                   5769:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   5770:     return $str;
                   5771: }
1.11      www      5772: 
1.557     albertel 5773: sub thaw_unescape {
                   5774:     my ($value)=@_;
                   5775:     if ($value =~ /^__FROZEN__/) {
                   5776: 	substr($value,0,10,undef);
                   5777: 	$value=&unescape($value);
                   5778: 	return &thaw($value);
                   5779:     }
                   5780:     return &unescape($value);
                   5781: }
                   5782: 
1.415     albertel 5783: sub mod_perl_version {
1.580     albertel 5784:     return 1;
1.415     albertel 5785:     if (defined($perlvar{'MODPERL2'})) {
                   5786: 	return 2;
                   5787:     }
1.436     albertel 5788: }
                   5789: 
                   5790: sub correct_line_ends {
                   5791:     my ($result)=@_;
                   5792:     $$result =~s/\r\n/\n/mg;
                   5793:     $$result =~s/\r/\n/mg;
1.415     albertel 5794: }
1.1       albertel 5795: # ================================================================ Main Program
                   5796: 
1.184     www      5797: sub goodbye {
1.204     albertel 5798:    &logthis("Starting Shut down");
1.443     albertel 5799: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 5800:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 5801: #converted
1.599     albertel 5802: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   5803:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   5804: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   5805: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 5806: #1.1 only
1.599     albertel 5807: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   5808: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   5809: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   5810: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   5811:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   5812:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   5813:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      5814:    &flushcourselogs();
                   5815:    &logthis("Shutting down");
1.362     albertel 5816:    return DONE;
1.184     www      5817: }
                   5818: 
1.179     www      5819: BEGIN {
1.228     harris41 5820: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      5821:     unless ($readit) {
1.217     harris41 5822: {
1.581     matthew  5823:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 5824:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 5825: 
                   5826:     while (my $configline=<$config>) {
1.484     albertel 5827:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 5828: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      5829:            chomp($varvalue);
1.1       albertel 5830:            $perlvar{$varname}=$varvalue;
                   5831:         }
                   5832:     }
1.448     albertel 5833:     close($config);
1.1       albertel 5834: }
1.227     harris41 5835: {
1.448     albertel 5836:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 5837: 
                   5838:     while (my $configline=<$config>) {
                   5839:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   5840: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   5841:            chomp($varvalue);
                   5842:            $perlvar{$varname}=$varvalue;
                   5843:         }
                   5844:     }
1.448     albertel 5845:     close($config);
1.227     harris41 5846: }
1.1       albertel 5847: 
1.327     albertel 5848: # ------------------------------------------------------------ Read domain file
                   5849: {
                   5850:     %domaindescription = ();
                   5851:     %domain_auth_def = ();
                   5852:     %domain_auth_arg_def = ();
1.448     albertel 5853:     my $fh;
                   5854:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 5855:        while (<$fh>) {
1.390     matthew  5856:            next if (/^(\#|\s*$)/);
                   5857: #           next if /^\#/;
1.327     albertel 5858:            chomp;
1.403     www      5859:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
                   5860: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
                   5861: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 5862:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      5863: 	   $domaindescription{$domain}=$domain_description;
                   5864: 	   $domain_lang_def{$domain}=$def_lang;
                   5865: 	   $domain_city{$domain}=$city;
                   5866: 	   $domain_longi{$domain}=$longi;
                   5867: 	   $domain_lati{$domain}=$lati;
                   5868: 
1.448     albertel 5869:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 5870: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 5871: 	}
1.327     albertel 5872:     }
1.448     albertel 5873:     close ($fh);
1.327     albertel 5874: }
                   5875: 
                   5876: 
1.1       albertel 5877: # ------------------------------------------------------------- Read hosts file
                   5878: {
1.448     albertel 5879:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 5880: 
                   5881:     while (my $configline=<$config>) {
1.303     matthew  5882:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      5883:        chomp($configline);
1.595     albertel 5884:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 5885:        $name=~s/\s//g;
1.595     albertel 5886:        if ($id && $domain && $role && $name) {
1.252     albertel 5887: 	 $hostname{$id}=$name;
                   5888: 	 $hostdom{$id}=$domain;
                   5889: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      5890:        }
1.1       albertel 5891:     }
1.448     albertel 5892:     close($config);
1.619     albertel 5893:     # FIXME: dev server don't want this, production servers _do_ want this
                   5894:     #&get_iphost();
1.1       albertel 5895: }
                   5896: 
1.598     albertel 5897: sub get_iphost {
                   5898:     if (%iphost) { return %iphost; }
                   5899:     foreach my $id (keys(%hostname)) {
                   5900: 	my $name=$hostname{$id};
                   5901: 	my $ip = gethostbyname($name);
                   5902: 	if (!$ip || length($ip) ne 4) {
                   5903: 	    &logthis("Skipping host $id name $name no IP found\n");
                   5904: 	    next;
                   5905: 	}
                   5906: 	$ip=inet_ntoa($ip);
                   5907: 	push(@{$iphost{$ip}},$id);
                   5908:     }
                   5909:     return %iphost;
                   5910: }
                   5911: 
1.1       albertel 5912: # ------------------------------------------------------ Read spare server file
                   5913: {
1.448     albertel 5914:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 5915: 
                   5916:     while (my $configline=<$config>) {
                   5917:        chomp($configline);
1.284     matthew  5918:        if ($configline) {
1.1       albertel 5919:           $spareid{$configline}=1;
                   5920:        }
                   5921:     }
1.448     albertel 5922:     close($config);
1.1       albertel 5923: }
1.11      www      5924: # ------------------------------------------------------------ Read permissions
                   5925: {
1.448     albertel 5926:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      5927: 
                   5928:     while (my $configline=<$config>) {
1.448     albertel 5929: 	chomp($configline);
                   5930: 	if ($configline) {
                   5931: 	    my ($role,$perm)=split(/ /,$configline);
                   5932: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   5933: 	}
1.11      www      5934:     }
1.448     albertel 5935:     close($config);
1.11      www      5936: }
                   5937: 
                   5938: # -------------------------------------------- Read plain texts for permissions
                   5939: {
1.448     albertel 5940:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      5941: 
                   5942:     while (my $configline=<$config>) {
1.448     albertel 5943: 	chomp($configline);
                   5944: 	if ($configline) {
                   5945: 	    my ($short,$plain)=split(/:/,$configline);
                   5946: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   5947: 	}
1.135     www      5948:     }
1.448     albertel 5949:     close($config);
1.135     www      5950: }
                   5951: 
                   5952: # ---------------------------------------------------------- Read package table
                   5953: {
1.448     albertel 5954:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      5955: 
                   5956:     while (my $configline=<$config>) {
1.483     albertel 5957: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 5958: 	chomp($configline);
                   5959: 	my ($short,$plain)=split(/:/,$configline);
                   5960: 	my ($pack,$name)=split(/\&/,$short);
                   5961: 	if ($plain ne '') {
                   5962: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   5963: 	    $packagetab{$short}=$plain; 
                   5964: 	}
1.11      www      5965:     }
1.448     albertel 5966:     close($config);
1.329     matthew  5967: }
                   5968: 
                   5969: # ------------- set up temporary directory
                   5970: {
                   5971:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   5972: 
1.11      www      5973: }
                   5974: 
1.599     albertel 5975: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      5976: 
1.281     www      5977: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      5978: $dumpcount=0;
1.22      www      5979: 
1.163     harris41 5980: &logtouch();
1.12      www      5981: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      5982: $readit=1;
1.564     albertel 5983:     {
                   5984: 	use integer;
                   5985: 	my $test=(2**32)+1;
1.568     albertel 5986: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 5987: 	&logthis(" Detected 64bit platform ($_64bit)");
                   5988:     }
1.195     www      5989: }
1.1       albertel 5990: }
1.179     www      5991: 
1.1       albertel 5992: 1;
1.191     harris41 5993: __END__
                   5994: 
1.243     albertel 5995: =pod
                   5996: 
1.191     harris41 5997: =head1 NAME
                   5998: 
1.243     albertel 5999: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 6000: 
                   6001: =head1 SYNOPSIS
                   6002: 
1.243     albertel 6003: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 6004: 
                   6005:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   6006: 
1.243     albertel 6007: Common parameters:
                   6008: 
                   6009: =over 4
                   6010: 
                   6011: =item *
                   6012: 
                   6013: $uname : an internal username (if $cname expecting a course Id specifically)
                   6014: 
                   6015: =item *
                   6016: 
                   6017: $udom : a domain (if $cdom expecting a course's domain specifically)
                   6018: 
                   6019: =item *
                   6020: 
                   6021: $symb : a resource instance identifier
                   6022: 
                   6023: =item *
                   6024: 
                   6025: $namespace : the name of a .db file that contains the data needed or
                   6026: being set.
                   6027: 
                   6028: =back
                   6029: 
1.394     bowersj2 6030: =head1 OVERVIEW
1.191     harris41 6031: 
1.394     bowersj2 6032: lonnet provides subroutines which interact with the
                   6033: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   6034: about classes, users, and resources.
1.243     albertel 6035: 
                   6036: For many of these objects you can also use this to store data about
                   6037: them or modify them in various ways.
1.191     harris41 6038: 
1.394     bowersj2 6039: =head2 Symbs
1.191     harris41 6040: 
1.394     bowersj2 6041: To identify a specific instance of a resource, LON-CAPA uses symbols
                   6042: or "symbs"X<symb>. These identifiers are built from the URL of the
                   6043: map, the resource number of the resource in the map, and the URL of
                   6044: the resource itself. The latter is somewhat redundant, but might help
                   6045: if maps change.
                   6046: 
                   6047: An example is
                   6048: 
                   6049:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   6050: 
                   6051: The respective map entry is
                   6052: 
                   6053:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   6054:   title="Problem 2">
                   6055:  </resource>
                   6056: 
                   6057: Symbs are used by the random number generator, as well as to store and
                   6058: restore data specific to a certain instance of for example a problem.
                   6059: 
                   6060: =head2 Storing And Retrieving Data
                   6061: 
                   6062: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   6063: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   6064: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   6065: is is the non-critical message twin of cstore. These functions are for
                   6066: handlers to store a perl hash to a user's permanent data space in an
                   6067: easy manner, and to retrieve it again on another call. It is expected
                   6068: that a handler would use this once at the beginning to retrieve data,
                   6069: and then again once at the end to send only the new data back.
                   6070: 
                   6071: The data is stored in the user's data directory on the user's
                   6072: homeserver under the ID of the course.
                   6073: 
                   6074: The hash that is returned by restore will have all of the previous
                   6075: value for all of the elements of the hash.
                   6076: 
                   6077: Example:
                   6078: 
                   6079:  #creating a hash
                   6080:  my %hash;
                   6081:  $hash{'foo'}='bar';
                   6082: 
                   6083:  #storing it
                   6084:  &Apache::lonnet::cstore(\%hash);
                   6085: 
                   6086:  #changing a value
                   6087:  $hash{'foo'}='notbar';
                   6088: 
                   6089:  #adding a new value
                   6090:  $hash{'bar'}='foo';
                   6091:  &Apache::lonnet::cstore(\%hash);
                   6092: 
                   6093:  #retrieving the hash
                   6094:  my %history=&Apache::lonnet::restore();
                   6095: 
                   6096:  #print the hash
                   6097:  foreach my $key (sort(keys(%history))) {
                   6098:    print("\%history{$key} = $history{$key}");
                   6099:  }
                   6100: 
                   6101: Will print out:
1.191     harris41 6102: 
1.394     bowersj2 6103:  %history{1:foo} = bar
                   6104:  %history{1:keys} = foo:timestamp
                   6105:  %history{1:timestamp} = 990455579
                   6106:  %history{2:bar} = foo
                   6107:  %history{2:foo} = notbar
                   6108:  %history{2:keys} = foo:bar:timestamp
                   6109:  %history{2:timestamp} = 990455580
                   6110:  %history{bar} = foo
                   6111:  %history{foo} = notbar
                   6112:  %history{timestamp} = 990455580
                   6113:  %history{version} = 2
                   6114: 
                   6115: Note that the special hash entries C<keys>, C<version> and
                   6116: C<timestamp> were added to the hash. C<version> will be equal to the
                   6117: total number of versions of the data that have been stored. The
                   6118: C<timestamp> attribute will be the UNIX time the hash was
                   6119: stored. C<keys> is available in every historical section to list which
                   6120: keys were added or changed at a specific historical revision of a
                   6121: hash.
                   6122: 
                   6123: B<Warning>: do not store the hash that restore returns directly. This
                   6124: will cause a mess since it will restore the historical keys as if the
                   6125: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 6126: 
1.394     bowersj2 6127: Calling convention:
1.191     harris41 6128: 
1.394     bowersj2 6129:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   6130:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 6131: 
1.394     bowersj2 6132: For more detailed information, see lonnet specific documentation.
1.191     harris41 6133: 
1.394     bowersj2 6134: =head1 RETURN MESSAGES
1.191     harris41 6135: 
1.394     bowersj2 6136: =over 4
1.191     harris41 6137: 
1.394     bowersj2 6138: =item * B<con_lost>: unable to contact remote host
1.191     harris41 6139: 
1.394     bowersj2 6140: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   6141: when the connection is brought back up
1.191     harris41 6142: 
1.394     bowersj2 6143: =item * B<con_failed>: unable to contact remote host and unable to save message
                   6144: for later delivery
1.191     harris41 6145: 
1.394     bowersj2 6146: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 6147: 
1.394     bowersj2 6148: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 6149: that was requested
1.191     harris41 6150: 
1.243     albertel 6151: =back
1.191     harris41 6152: 
1.243     albertel 6153: =head1 PUBLIC SUBROUTINES
1.191     harris41 6154: 
1.243     albertel 6155: =head2 Session Environment Functions
1.191     harris41 6156: 
1.243     albertel 6157: =over 4
1.191     harris41 6158: 
1.394     bowersj2 6159: =item * 
                   6160: X<appenv()>
                   6161: B<appenv(%hash)>: the value of %hash is written to
                   6162: the user envirnoment file, and will be restored for each access this
1.620     albertel 6163: user makes during this session, also modifies the %env for the current
1.394     bowersj2 6164: process
1.191     harris41 6165: 
                   6166: =item *
1.394     bowersj2 6167: X<delenv()>
                   6168: B<delenv($regexp)>: removes all items from the session
                   6169: environment file that matches the regular expression in $regexp. The
1.620     albertel 6170: values are also delted from the current processes %env.
1.191     harris41 6171: 
1.243     albertel 6172: =back
                   6173: 
                   6174: =head2 User Information
1.191     harris41 6175: 
1.243     albertel 6176: =over 4
1.191     harris41 6177: 
                   6178: =item *
1.394     bowersj2 6179: X<queryauthenticate()>
                   6180: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 6181: authentication scheme
                   6182: 
                   6183: =item *
1.394     bowersj2 6184: X<authenticate()>
                   6185: B<authenticate($uname,$upass,$udom)>: try to
                   6186: authenticate user from domain's lib servers (first use the current
                   6187: one). C<$upass> should be the users password.
1.191     harris41 6188: 
                   6189: =item *
1.394     bowersj2 6190: X<homeserver()>
                   6191: B<homeserver($uname,$udom)>: find the server which has
                   6192: the user's directory and files (there must be only one), this caches
                   6193: the answer, and also caches if there is a borken connection.
1.191     harris41 6194: 
                   6195: =item *
1.394     bowersj2 6196: X<idget()>
                   6197: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   6198: (IDs are a unique resource in a domain, there must be only 1 ID per
                   6199: username, and only 1 username per ID in a specific domain) (returns
                   6200: hash: id=>name,id=>name)
1.191     harris41 6201: 
                   6202: =item *
1.394     bowersj2 6203: X<idrget()>
                   6204: B<idrget($udom,@unames)>: find the IDs behind a list of
                   6205: usernames (returns hash: name=>id,name=>id)
1.191     harris41 6206: 
                   6207: =item *
1.394     bowersj2 6208: X<idput()>
                   6209: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 6210: 
                   6211: =item *
1.394     bowersj2 6212: X<rolesinit()>
                   6213: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 6214: 
                   6215: =item *
1.551     albertel 6216: X<getsection()>
                   6217: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 6218: course $cname, return section name/number or '' for "not in course"
                   6219: and '-1' for "no section"
                   6220: 
                   6221: =item *
1.394     bowersj2 6222: X<userenvironment()>
                   6223: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 6224: passed in @what from the requested user's environment, returns a hash
                   6225: 
                   6226: =back
                   6227: 
                   6228: =head2 User Roles
                   6229: 
                   6230: =over 4
                   6231: 
                   6232: =item *
                   6233: 
                   6234: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   6235: actions
                   6236:  F: full access
                   6237:  U,I,K: authentication modes (cxx only)
                   6238:  '': forbidden
                   6239:  1: user needs to choose course
                   6240:  2: browse allowed
                   6241: 
                   6242: =item *
                   6243: 
                   6244: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   6245: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   6246: and course level
                   6247: 
                   6248: =item *
                   6249: 
                   6250: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   6251: explanation of a user role term
                   6252: 
                   6253: =back
                   6254: 
                   6255: =head2 User Modification
                   6256: 
                   6257: =over 4
                   6258: 
                   6259: =item *
                   6260: 
                   6261: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   6262: user for the level given by URL.  Optional start and end dates (leave empty
                   6263: string or zero for "no date")
1.191     harris41 6264: 
                   6265: =item *
                   6266: 
1.243     albertel 6267: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   6268: change a users, password, possible return values are: ok,
                   6269: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   6270: refused
1.191     harris41 6271: 
                   6272: =item *
                   6273: 
1.243     albertel 6274: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 6275: 
                   6276: =item *
                   6277: 
1.243     albertel 6278: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   6279: modify user
1.191     harris41 6280: 
                   6281: =item *
                   6282: 
1.286     matthew  6283: modifystudent
                   6284: 
                   6285: modify a students enrollment and identification information.
                   6286: The course id is resolved based on the current users environment.  
                   6287: This means the envoking user must be a course coordinator or otherwise
                   6288: associated with a course.
                   6289: 
1.297     matthew  6290: This call is essentially a wrapper for lonnet::modifyuser and
                   6291: lonnet::modify_student_enrollment
1.286     matthew  6292: 
                   6293: Inputs: 
                   6294: 
                   6295: =over 4
                   6296: 
                   6297: =item B<$udom> Students loncapa domain
                   6298: 
                   6299: =item B<$uname> Students loncapa login name
                   6300: 
                   6301: =item B<$uid> Students id/student number
                   6302: 
                   6303: =item B<$umode> Students authentication mode
                   6304: 
                   6305: =item B<$upass> Students password
                   6306: 
                   6307: =item B<$first> Students first name
                   6308: 
                   6309: =item B<$middle> Students middle name
                   6310: 
                   6311: =item B<$last> Students last name
                   6312: 
                   6313: =item B<$gene> Students generation
                   6314: 
                   6315: =item B<$usec> Students section in course
                   6316: 
                   6317: =item B<$end> Unix time of the roles expiration
                   6318: 
                   6319: =item B<$start> Unix time of the roles start date
                   6320: 
                   6321: =item B<$forceid> If defined, allow $uid to be changed
                   6322: 
                   6323: =item B<$desiredhome> server to use as home server for student
                   6324: 
                   6325: =back
1.297     matthew  6326: 
                   6327: =item *
                   6328: 
                   6329: modify_student_enrollment
                   6330: 
                   6331: Change a students enrollment status in a class.  The environment variable
                   6332: 'role.request.course' must be defined for this function to proceed.
                   6333: 
                   6334: Inputs:
                   6335: 
                   6336: =over 4
                   6337: 
                   6338: =item $udom, students domain
                   6339: 
                   6340: =item $uname, students name
                   6341: 
                   6342: =item $uid, students user id
                   6343: 
                   6344: =item $first, students first name
                   6345: 
                   6346: =item $middle
                   6347: 
                   6348: =item $last
                   6349: 
                   6350: =item $gene
                   6351: 
                   6352: =item $usec
                   6353: 
                   6354: =item $end
                   6355: 
                   6356: =item $start
                   6357: 
                   6358: =back
                   6359: 
1.191     harris41 6360: 
                   6361: =item *
                   6362: 
1.243     albertel 6363: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   6364: custom role; give a custom role to a user for the level given by URL.  Specify
                   6365: name and domain of role author, and role name
1.191     harris41 6366: 
                   6367: =item *
                   6368: 
1.243     albertel 6369: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 6370: 
                   6371: =item *
                   6372: 
1.243     albertel 6373: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   6374: 
                   6375: =back
                   6376: 
                   6377: =head2 Course Infomation
                   6378: 
                   6379: =over 4
1.191     harris41 6380: 
                   6381: =item *
                   6382: 
1.631     albertel 6383: coursedescription($courseid) : returns a hash of information about the
                   6384: specified course id, including all environment settings for the
                   6385: course, the description of the course will be in the hash under the
                   6386: key 'description'
1.191     harris41 6387: 
                   6388: =item *
                   6389: 
1.624     albertel 6390: resdata($name,$domain,$type,@which) : request for current parameter
                   6391: setting for a specific $type, where $type is either 'course' or 'user',
                   6392: @what should be a list of parameters to ask about. This routine caches
                   6393: answers for 5 minutes.
1.243     albertel 6394: 
                   6395: =back
                   6396: 
                   6397: =head2 Course Modification
                   6398: 
                   6399: =over 4
1.191     harris41 6400: 
                   6401: =item *
                   6402: 
1.243     albertel 6403: writecoursepref($courseid,%prefs) : write preferences (environment
                   6404: database) for a course
1.191     harris41 6405: 
                   6406: =item *
                   6407: 
1.243     albertel 6408: createcourse($udom,$description,$url) : make/modify course
                   6409: 
                   6410: =back
                   6411: 
                   6412: =head2 Resource Subroutines
                   6413: 
                   6414: =over 4
1.191     harris41 6415: 
                   6416: =item *
                   6417: 
1.243     albertel 6418: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 6419: 
                   6420: =item *
                   6421: 
1.243     albertel 6422: repcopy($filename) : subscribes to the requested file, and attempts to
                   6423: replicate from the owning library server, Might return
1.607     raeburn  6424: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   6425: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 6426: resource. Expects the local filesystem pathname
                   6427: (/home/httpd/html/res/....)
                   6428: 
                   6429: =back
                   6430: 
                   6431: =head2 Resource Information
                   6432: 
                   6433: =over 4
1.191     harris41 6434: 
                   6435: =item *
                   6436: 
1.243     albertel 6437: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   6438: a vairety of different possible values, $varname should be a request
                   6439: string, and the other parameters can be used to specify who and what
                   6440: one is asking about.
                   6441: 
                   6442: Possible values for $varname are environment.lastname (or other item
                   6443: from the envirnment hash), user.name (or someother aspect about the
                   6444: user), resource.0.maxtries (or some other part and parameter of a
                   6445: resource)
1.204     albertel 6446: 
                   6447: =item *
                   6448: 
1.243     albertel 6449: directcondval($number) : get current value of a condition; reads from a state
                   6450: string
1.204     albertel 6451: 
                   6452: =item *
                   6453: 
1.243     albertel 6454: condval($condidx) : value of condition index based on state
1.204     albertel 6455: 
                   6456: =item *
                   6457: 
1.243     albertel 6458: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   6459: resource's metadata, $what should be either a specific key, or either
                   6460: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   6461: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   6462: 
                   6463: this function automatically caches all requests
1.191     harris41 6464: 
                   6465: =item *
                   6466: 
1.243     albertel 6467: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   6468: network of library servers; returns file handle of where SQL and regex results
                   6469: will be stored for query
1.191     harris41 6470: 
                   6471: =item *
                   6472: 
1.243     albertel 6473: symbread($filename) : return symbolic list entry (filename argument optional);
                   6474: returns the data handle
1.191     harris41 6475: 
                   6476: =item *
                   6477: 
1.243     albertel 6478: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 6479: a possible symb for the URL in $thisfn, and if is an encryypted
                   6480: resource that the user accessed using /enc/ returns a 1 on success, 0
                   6481: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 6482: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 6483: 
1.191     harris41 6484: 
                   6485: =item *
                   6486: 
1.243     albertel 6487: symbclean($symb) : removes versions numbers from a symb, returns the
                   6488: cleaned symb
1.191     harris41 6489: 
                   6490: =item *
                   6491: 
1.243     albertel 6492: is_on_map($uri) : checks if the $uri is somewhere on the current
                   6493: course map, user must be in a course for it to work.
1.191     harris41 6494: 
                   6495: =item *
                   6496: 
1.243     albertel 6497: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 6498: 
                   6499: =item *
                   6500: 
1.243     albertel 6501: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   6502: a random seed, all arguments are optional, if they aren't sent it uses the
                   6503: environment to derive them. Note: if symb isn't sent and it can't get one
                   6504: from &symbread it will use the current time as its return value
1.191     harris41 6505: 
                   6506: =item *
                   6507: 
1.243     albertel 6508: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   6509: unfakeable, receipt
1.191     harris41 6510: 
                   6511: =item *
                   6512: 
1.620     albertel 6513: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 6514: 
                   6515: =item *
                   6516: 
1.243     albertel 6517: countacc($url) : count the number of accesses to a given URL
1.191     harris41 6518: 
                   6519: =item *
                   6520: 
1.243     albertel 6521: 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 6522: 
                   6523: =item *
                   6524: 
1.243     albertel 6525: 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 6526: 
                   6527: =item *
                   6528: 
1.243     albertel 6529: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 6530: 
                   6531: =item *
                   6532: 
1.243     albertel 6533: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   6534: forcing spreadsheet to reevaluate the resource scores next time.
                   6535: 
                   6536: =back
                   6537: 
                   6538: =head2 Storing/Retreiving Data
                   6539: 
                   6540: =over 4
1.191     harris41 6541: 
                   6542: =item *
                   6543: 
1.243     albertel 6544: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   6545: for this url; hashref needs to be given and should be a \%hashname; the
                   6546: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 6547: be derived from the env
1.191     harris41 6548: 
                   6549: =item *
                   6550: 
1.243     albertel 6551: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   6552: uses critical subroutine
1.191     harris41 6553: 
                   6554: =item *
                   6555: 
1.243     albertel 6556: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   6557: all args are optional
1.191     harris41 6558: 
                   6559: =item *
                   6560: 
1.243     albertel 6561: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   6562: works very similar to store/cstore, but all data is stored in a
                   6563: temporary location and can be reset using tmpreset, $storehash should
                   6564: be a hash reference, returns nothing on success
1.191     harris41 6565: 
                   6566: =item *
                   6567: 
1.243     albertel 6568: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   6569: similar to restore, but all data is stored in a temporary location and
                   6570: can be reset using tmpreset. Returns a hash of values on success,
                   6571: error string otherwise.
1.191     harris41 6572: 
                   6573: =item *
                   6574: 
1.243     albertel 6575: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   6576: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 6577: 
                   6578: =item *
                   6579: 
1.243     albertel 6580: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6581: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 6582: 
                   6583: =item *
                   6584: 
1.243     albertel 6585: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   6586: namesp ($udom and $uname are optional)
1.191     harris41 6587: 
                   6588: =item *
                   6589: 
1.243     albertel 6590: dump($namespace,$udom,$uname,$regexp) : 
                   6591: dumps the complete (or key matching regexp) namespace into a hash
                   6592: ($udom, $uname and $regexp are optional)
1.449     matthew  6593: 
                   6594: =item *
                   6595: 
                   6596: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   6597: $store can be a scalar, an array reference, or if the amount to be 
                   6598: incremented is > 1, a hash reference.
                   6599: 
                   6600: ($udom and $uname are optional)
1.191     harris41 6601: 
                   6602: =item *
                   6603: 
1.243     albertel 6604: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   6605: ($udom and $uname are optional)
1.191     harris41 6606: 
                   6607: =item *
                   6608: 
1.524     raeburn  6609: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
                   6610: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
                   6611: used in records written by &store and retrieved by &restore.  This function 
                   6612: was created for use in editing discussion posts, without incrementing the
                   6613: version number included in the key for a particular post. The colon 
                   6614: separated list of attribute names (e.g., the value associated with the key 
                   6615: 1:keys:$symb) is also generated and passed in the ampersand separated 
                   6616: items sent to lonnet::reply().  
                   6617: 
                   6618: =item *
                   6619: 
1.243     albertel 6620: cput($namespace,$storehash,$udom,$uname) : critical put
                   6621: ($udom and $uname are optional)
1.191     harris41 6622: 
                   6623: =item *
                   6624: 
1.243     albertel 6625: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6626: reference filled in from namesp (encrypts the return communication)
                   6627: ($udom and $uname are optional)
1.191     harris41 6628: 
                   6629: =item *
                   6630: 
1.243     albertel 6631: log($udom,$name,$home,$message) : write to permanent log for user; use
                   6632: critical subroutine
                   6633: 
                   6634: =back
                   6635: 
                   6636: =head2 Network Status Functions
                   6637: 
                   6638: =over 4
1.191     harris41 6639: 
                   6640: =item *
                   6641: 
                   6642: dirlist($uri) : return directory list based on URI
                   6643: 
                   6644: =item *
                   6645: 
1.243     albertel 6646: spareserver() : find server with least workload from spare.tab
                   6647: 
                   6648: =back
                   6649: 
                   6650: =head2 Apache Request
                   6651: 
                   6652: =over 4
1.191     harris41 6653: 
                   6654: =item *
                   6655: 
1.243     albertel 6656: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   6657: localhost, posts hash
                   6658: 
                   6659: =back
                   6660: 
                   6661: =head2 Data to String to Data
                   6662: 
                   6663: =over 4
1.191     harris41 6664: 
                   6665: =item *
                   6666: 
1.243     albertel 6667: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   6668: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 6669: 
                   6670: =item *
                   6671: 
1.243     albertel 6672: hashref2str($hashref) : convert a hashref into a string complete with
                   6673: escaping and '=' and '&' separators, supports elements that are
                   6674: arrayrefs and hashrefs
1.191     harris41 6675: 
                   6676: =item *
                   6677: 
1.243     albertel 6678: arrayref2str($arrayref) : convert an arrayref into a string complete
                   6679: with escaping and '&' separators, supports elements that are arrayrefs
                   6680: and hashrefs
1.191     harris41 6681: 
                   6682: =item *
                   6683: 
1.243     albertel 6684: str2hash($string) : convert string to hash using unescaping and
                   6685: splitting on '=' and '&', supports elements that are arrayrefs and
                   6686: hashrefs
1.191     harris41 6687: 
                   6688: =item *
                   6689: 
1.243     albertel 6690: str2array($string) : convert string to hash using unescaping and
                   6691: splitting on '&', supports elements that are arrayrefs and hashrefs
                   6692: 
                   6693: =back
                   6694: 
                   6695: =head2 Logging Routines
                   6696: 
                   6697: =over 4
                   6698: 
                   6699: These routines allow one to make log messages in the lonnet.log and
                   6700: lonnet.perm logfiles.
1.191     harris41 6701: 
                   6702: =item *
                   6703: 
1.243     albertel 6704: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 6705: 
                   6706: =item *
                   6707: 
1.243     albertel 6708: logthis() : append message to the normal lonnet.log file, it gets
                   6709: preiodically rolled over and deleted.
1.191     harris41 6710: 
                   6711: =item *
                   6712: 
1.243     albertel 6713: logperm() : append a permanent message to lonnet.perm.log, this log
                   6714: file never gets deleted by any automated portion of the system, only
                   6715: messages of critical importance should go in here.
                   6716: 
                   6717: =back
                   6718: 
                   6719: =head2 General File Helper Routines
                   6720: 
                   6721: =over 4
1.191     harris41 6722: 
                   6723: =item *
                   6724: 
1.481     raeburn  6725: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   6726: (a) files in /uploaded
                   6727:   (i) If a local copy of the file exists - 
                   6728:       compares modification date of local copy with last-modified date for 
                   6729:       definitive version stored on home server for course. If local copy is 
                   6730:       stale, requests a new version from the home server and stores it. 
                   6731:       If the original has been removed from the home server, then local copy 
                   6732:       is unlinked.
                   6733:   (ii) If local copy does not exist -
                   6734:       requests the file from the home server and stores it. 
                   6735:   
                   6736:   If $caller is 'uploadrep':  
                   6737:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   6738:     for request for files originally uploaded via DOCS. 
                   6739:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   6740:   
                   6741:   Otherwise:
                   6742:      This indicates a call from the content generation phase of the request.
                   6743:      -  returns the entire contents of the file or -1.
                   6744:      
                   6745: (b) files in /res
                   6746:    - returns the entire contents of a file or -1; 
                   6747:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 6748: 
                   6749: =item *
                   6750: 
1.243     albertel 6751: filelocation($dir,$file) : returns file system location of a file
                   6752: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   6753: directory that relative $file lookups are to looked in ($dir of /a/dir
                   6754: and a file of ../bob will become /a/bob)
1.191     harris41 6755: 
                   6756: =item *
                   6757: 
                   6758: hreflocation($dir,$file) : returns file system location or a URL; same as
                   6759: filelocation except for hrefs
                   6760: 
                   6761: =item *
                   6762: 
                   6763: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   6764: 
1.243     albertel 6765: =back
                   6766: 
1.608     albertel 6767: =head2 Usererfile file routines (/uploaded*)
                   6768: 
                   6769: =over 4
                   6770: 
                   6771: =item *
                   6772: 
                   6773: userfileupload(): main rotine for putting a file in a user or course's
                   6774:                   filespace, arguments are,
                   6775: 
1.620     albertel 6776:  formname - required - this is the name of the element in $env where the
1.608     albertel 6777:            filename, and the contents of the file to create/modifed exist
1.620     albertel 6778:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   6779:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 6780:  coursedoc - if true, store the file in the course of the active role
                   6781:              of the current user
                   6782:  subdir - required - subdirectory to put the file in under ../userfiles/
                   6783:          if undefined, it will be placed in "unknown"
                   6784: 
                   6785:  (This routine calls clean_filename() to remove any dangerous
                   6786:  characters from the filename, and then calls finuserfileupload() to
                   6787:  complete the transaction)
                   6788: 
                   6789:  returns either the url of the uploaded file (/uploaded/....) if successful
                   6790:  and /adm/notfound.html if unsuccessful
                   6791: 
                   6792: =item *
                   6793: 
                   6794: clean_filename(): routine for cleaing a filename up for storage in
                   6795:                  userfile space, argument is:
                   6796: 
                   6797:  filename - proposed filename
                   6798: 
                   6799: returns: the new clean filename
                   6800: 
                   6801: =item *
                   6802: 
                   6803: finishuserfileupload(): routine that creaes and sends the file to
                   6804: userspace, probably shouldn't be called directly
                   6805: 
                   6806:   docuname: username or courseid of destination for the file
                   6807:   docudom: domain of user/course of destination for the file
                   6808:   formname: same as for userfileupload()
                   6809:   fname: filename (inculding subdirectories) for the file
                   6810: 
                   6811:  returns either the url of the uploaded file (/uploaded/....) if successful
                   6812:  and /adm/notfound.html if unsuccessful
                   6813: 
                   6814: =item *
                   6815: 
                   6816: renameuserfile(): renames an existing userfile to a new name
                   6817: 
                   6818:   Args:
                   6819:    docuname: username or courseid of destination for the file
                   6820:    docudom: domain of user/course of destination for the file
                   6821:    old: current file name (including any subdirs under userfiles)
                   6822:    new: desired file name (including any subdirs under userfiles)
                   6823: 
                   6824: =item *
                   6825: 
                   6826: mkdiruserfile(): creates a directory is a userfiles dir
                   6827: 
                   6828:   Args:
                   6829:    docuname: username or courseid of destination for the file
                   6830:    docudom: domain of user/course of destination for the file
                   6831:    dir: dir to create (including any subdirs under userfiles)
                   6832: 
                   6833: =item *
                   6834: 
                   6835: removeuserfile(): removes a file that exists in userfiles
                   6836: 
                   6837:   Args:
                   6838:    docuname: username or courseid of destination for the file
                   6839:    docudom: domain of user/course of destination for the file
                   6840:    fname: filname to delete (including any subdirs under userfiles)
                   6841: 
                   6842: =item *
                   6843: 
                   6844: removeuploadedurl(): convience function for removeuserfile()
                   6845: 
                   6846:   Args:
                   6847:    url:  a full /uploaded/... url to delete
                   6848: 
                   6849: =back
                   6850: 
1.243     albertel 6851: =head2 HTTP Helper Routines
                   6852: 
                   6853: =over 4
                   6854: 
1.191     harris41 6855: =item *
                   6856: 
                   6857: escape() : unpack non-word characters into CGI-compatible hex codes
                   6858: 
                   6859: =item *
                   6860: 
                   6861: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   6862: 
1.243     albertel 6863: =back
                   6864: 
                   6865: =head1 PRIVATE SUBROUTINES
                   6866: 
                   6867: =head2 Underlying communication routines (Shouldn't call)
                   6868: 
                   6869: =over 4
                   6870: 
                   6871: =item *
                   6872: 
                   6873: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   6874: 
                   6875: =item *
                   6876: 
                   6877: reply() : uses subreply to send a message to remote machine, logs all failures
                   6878: 
                   6879: =item *
                   6880: 
                   6881: critical() : passes a critical message to another server; if cannot
                   6882: get through then place message in connection buffer directory and
                   6883: returns con_delayed, if incapable of saving message, returns
                   6884: con_failed
                   6885: 
                   6886: =item *
                   6887: 
                   6888: reconlonc() : tries to reconnect lonc client processes.
                   6889: 
                   6890: =back
                   6891: 
                   6892: =head2 Resource Access Logging
                   6893: 
                   6894: =over 4
                   6895: 
                   6896: =item *
                   6897: 
                   6898: flushcourselogs() : flush (save) buffer logs and access logs
                   6899: 
                   6900: =item *
                   6901: 
                   6902: courselog($what) : save message for course in hash
                   6903: 
                   6904: =item *
                   6905: 
                   6906: courseacclog($what) : save message for course using &courselog().  Perform
                   6907: special processing for specific resource types (problems, exams, quizzes, etc).
                   6908: 
1.191     harris41 6909: =item *
                   6910: 
                   6911: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   6912: as a PerlChildExitHandler
1.243     albertel 6913: 
                   6914: =back
                   6915: 
                   6916: =head2 Other
                   6917: 
                   6918: =over 4
                   6919: 
                   6920: =item *
                   6921: 
                   6922: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 6923: 
                   6924: =back
                   6925: 
                   6926: =cut

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