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

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

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