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

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

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