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

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

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