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

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

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