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

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

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