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

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

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