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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.720   ! albertel    4: # $Id: lonnet.pm,v 1.719 2006/03/07 02:46:03 banghart Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.599     albertel   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
                     42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.8       www        48: use Apache::Constants qw(:common :http);
1.208     albertel   49: use HTML::LCParser;
1.637     raeburn    50: use HTML::Parser;
1.88      www        51: use Fcntl qw(:flock);
1.557     albertel   52: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   53: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   54: use Cache::Memcached;
1.676     albertel   55: use Digest::MD5;
                     56: 
1.195     www        57: my $readit;
1.550     foxr       58: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   59: 
1.619     albertel   60: require Exporter;
                     61: 
                     62: our @ISA = qw (Exporter);
                     63: our @EXPORT = qw(%env);
                     64: 
1.449     matthew    65: =pod
                     66: 
                     67: =head1 Package Variables
                     68: 
                     69: These are largely undocumented, so if you decipher one please note it here.
                     70: 
                     71: =over 4
                     72: 
                     73: =item $processmarker
                     74: 
                     75: Contains the time this process was started and this servers host id.
                     76: 
                     77: =item $dumpcount
                     78: 
                     79: Counts the number of times a message log flush has been attempted (regardless
                     80: of success) by this process.  Used as part of the filename when messages are
                     81: delayed.
                     82: 
                     83: =back
                     84: 
                     85: =cut
                     86: 
                     87: 
1.1       albertel   88: # --------------------------------------------------------------------- Logging
                     89: 
1.163     harris41   90: sub logtouch {
                     91:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel   92:     unless (-e "$execdir/logs/lonnet.log") {	
                     93: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41   94: 	close $fh;
                     95:     }
                     96:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                     97:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                     98: }
                     99: 
1.1       albertel  100: sub logthis {
                    101:     my $message=shift;
                    102:     my $execdir=$perlvar{'lonDaemons'};
                    103:     my $now=time;
                    104:     my $local=localtime($now);
1.448     albertel  105:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    106: 	print $fh "$local ($$): $message\n";
                    107: 	close($fh);
                    108:     }
1.1       albertel  109:     return 1;
                    110: }
                    111: 
                    112: sub logperm {
                    113:     my $message=shift;
                    114:     my $execdir=$perlvar{'lonDaemons'};
                    115:     my $now=time;
                    116:     my $local=localtime($now);
1.448     albertel  117:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    118: 	print $fh "$now:$message:$local\n";
                    119: 	close($fh);
                    120:     }
1.1       albertel  121:     return 1;
                    122: }
                    123: 
                    124: # -------------------------------------------------- Non-critical communication
                    125: sub subreply {
                    126:     my ($cmd,$server)=@_;
1.704     albertel  127:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      128:     #
                    129:     #  With loncnew process trimming, there's a timing hole between lonc server
                    130:     #  process exit and the master server picking up the listen on the AF_UNIX
                    131:     #  socket.  In that time interval, a lock file will exist:
                    132: 
                    133:     my $lockfile=$peerfile.".lock";
                    134:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    135: 	sleep(1);
                    136:     }
                    137:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      138:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      139:     #
1.550     foxr      140:     #   We'll give the connection a few tries before abandoning it.  If
                    141:     #   connection is not possible, we'll con_lost back to the client.
                    142:     #   
                    143:     my $client;
                    144:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    145: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    146: 				      Type    => SOCK_STREAM,
                    147: 				      Timeout => 10);
                    148: 	if($client) {
                    149: 	    last;		# Connected!
                    150: 	}
                    151: 	sleep(1);		# Try again later if failed connection.
                    152:     }
                    153:     my $answer;
                    154:     if ($client) {
1.704     albertel  155: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      156: 	$answer=<$client>;
                    157: 	if (!$answer) { $answer="con_lost"; }
                    158: 	chomp($answer);
                    159:     } else {
                    160: 	$answer = 'con_lost';	# Failed connection.
                    161:     }
1.1       albertel  162:     return $answer;
                    163: }
                    164: 
                    165: sub reply {
                    166:     my ($cmd,$server)=@_;
1.205     www       167:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  168:     my $answer=subreply($cmd,$server);
1.65      www       169:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  170:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       171:                 " $cmd to $server returned $answer</font>");
                    172:     }
1.1       albertel  173:     return $answer;
                    174: }
                    175: 
                    176: # ----------------------------------------------------------- Send USR1 to lonc
                    177: 
                    178: sub reconlonc {
                    179:     my $peerfile=shift;
                    180:     &logthis("Trying to reconnect for $peerfile");
                    181:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  182:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  183: 	my $loncpid=<$fh>;
                    184:         chomp($loncpid);
                    185:         if (kill 0 => $loncpid) {
                    186: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    187:             kill USR1 => $loncpid;
                    188:             sleep 1;
                    189:             if (-e "$peerfile") { return; }
                    190:             &logthis("$peerfile still not there, give it another try");
                    191:             sleep 5;
                    192:             if (-e "$peerfile") { return; }
1.12      www       193:             &logthis(
1.672     albertel  194:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  195:         } else {
1.12      www       196: 	    &logthis(
1.672     albertel  197:                "<font color=\"blue\">WARNING:".
1.12      www       198:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  199:         }
                    200:     } else {
1.672     albertel  201:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  202:     }
                    203: }
                    204: 
                    205: # ------------------------------------------------------ Critical communication
1.12      www       206: 
1.1       albertel  207: sub critical {
                    208:     my ($cmd,$server)=@_;
1.89      www       209:     unless ($hostname{$server}) {
1.672     albertel  210:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       211:                " Critical message to unknown server ($server)</font>");
                    212:         return 'no_such_host';
                    213:     }
1.1       albertel  214:     my $answer=reply($cmd,$server);
                    215:     if ($answer eq 'con_lost') {
                    216: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  217: 	my $answer=reply($cmd,$server);
1.1       albertel  218:         if ($answer eq 'con_lost') {
                    219:             my $now=time;
                    220:             my $middlename=$cmd;
1.5       www       221:             $middlename=substr($middlename,0,16);
1.1       albertel  222:             $middlename=~s/\W//g;
                    223:             my $dfilename=
1.305     www       224:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    225:             $dumpcount++;
1.1       albertel  226:             {
1.448     albertel  227: 		my $dfh;
                    228: 		if (open($dfh,">$dfilename")) {
                    229: 		    print $dfh "$cmd\n"; 
                    230: 		    close($dfh);
                    231: 		}
1.1       albertel  232:             }
                    233:             sleep 2;
                    234:             my $wcmd='';
                    235:             {
1.448     albertel  236: 		my $dfh;
                    237: 		if (open($dfh,"<$dfilename")) {
                    238: 		    $wcmd=<$dfh>; 
                    239: 		    close($dfh);
                    240: 		}
1.1       albertel  241:             }
                    242:             chomp($wcmd);
1.7       www       243:             if ($wcmd eq $cmd) {
1.672     albertel  244: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       245:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  246:                 &logperm("D:$server:$cmd");
                    247: 	        return 'con_delayed';
                    248:             } else {
1.672     albertel  249:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       250:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  251:                 &logperm("F:$server:$cmd");
                    252:                 return 'con_failed';
                    253:             }
                    254:         }
                    255:     }
                    256:     return $answer;
1.405     albertel  257: }
                    258: 
1.374     www       259: # ------------------------------------------- Transfer profile into environment
                    260: 
                    261: sub transfer_profile_to_env {
                    262:     my ($lonidsdir,$handle)=@_;
1.720   ! albertel  263:     if (!defined($lonidsdir)) {
        !           264: 	$lonidsdir = $perlvar{'lonIDsDir'};
        !           265:     }
        !           266:     if (!defined($handle)) {
        !           267:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
        !           268:     }
        !           269: 
1.374     www       270:     my @profile;
                    271:     {
1.448     albertel  272: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       273: 	flock($idf,LOCK_SH);
                    274: 	@profile=<$idf>;
1.448     albertel  275: 	close($idf);
1.374     www       276:     }
                    277:     my $envi;
1.433     matthew   278:     my %Remove;
1.374     www       279:     for ($envi=0;$envi<=$#profile;$envi++) {
                    280: 	chomp($profile[$envi]);
1.690     albertel  281: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.619     albertel  282: 	$env{$envname} = $envvalue;
1.433     matthew   283:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    284:             if ($time < time-300) {
                    285:                 $Remove{$key}++;
                    286:             }
                    287:         }
                    288:     }
1.619     albertel  289:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   290:     foreach my $expired_key (keys(%Remove)) {
                    291:         &delenv($expired_key);
1.374     www       292:     }
1.1       albertel  293: }
                    294: 
1.5       www       295: # ---------------------------------------------------------- Append Environment
                    296: 
                    297: sub appenv {
1.6       www       298:     my %newenv=@_;
1.692     albertel  299:     foreach my $key (keys(%newenv)) {
                    300: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  301:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  302:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       303:                 .'</font>');
1.692     albertel  304: 	    delete($newenv{$key});
1.35      www       305:         } else {
1.692     albertel  306:             $env{$key}=$newenv{$key};
1.35      www       307:         }
1.191     harris41  308:     }
1.95      www       309: 
                    310:     my $lockfh;
1.620     albertel  311:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  312: 	return 'error: '.$!;
1.95      www       313:     }
                    314:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  315:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       316:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  317:          close($lockfh);
1.95      www       318:          return 'error: '.$!;
                    319:     }
                    320: 
1.6       www       321:     my @oldenv;
                    322:     {
1.448     albertel  323: 	my $fh;
1.620     albertel  324: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  325: 	    return 'error: '.$!;
                    326: 	}
                    327: 	@oldenv=<$fh>;
                    328: 	close($fh);
1.6       www       329:     }
                    330:     for (my $i=0; $i<=$#oldenv; $i++) {
                    331:         chomp($oldenv[$i]);
1.9       www       332:         if ($oldenv[$i] ne '') {
1.690     albertel  333: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.448     albertel  334: 	    unless (defined($newenv{$name})) {
                    335: 		$newenv{$name}=$value;
                    336: 	    }
1.9       www       337:         }
1.6       www       338:     }
                    339:     {
1.448     albertel  340: 	my $fh;
1.620     albertel  341: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  342: 	    return 'error';
                    343: 	}
                    344: 	my $newname;
                    345: 	foreach $newname (keys %newenv) {
                    346: 	    print $fh "$newname=$newenv{$newname}\n";
                    347: 	}
                    348: 	close($fh);
1.56      www       349:     }
1.448     albertel  350: 	
                    351:     close($lockfh);
1.56      www       352:     return 'ok';
                    353: }
                    354: # ----------------------------------------------------- Delete from Environment
                    355: 
                    356: sub delenv {
                    357:     my $delthis=shift;
                    358:     my %newenv=();
                    359:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  360:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       361:                 "Attempt to delete from environment ".$delthis);
                    362:         return 'error';
                    363:     }
                    364:     my @oldenv;
                    365:     {
1.448     albertel  366: 	my $fh;
1.620     albertel  367: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  368: 	    return 'error';
                    369: 	}
                    370: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  371: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  372: 		     'Could not obtain shared lock in delenv: '.$!);
                    373: 	    close($fh);
                    374: 	    return 'error: '.$!;
                    375: 	}
                    376: 	@oldenv=<$fh>;
                    377: 	close($fh);
1.56      www       378:     }
                    379:     {
1.448     albertel  380: 	my $fh;
1.620     albertel  381: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  382: 	    return 'error';
                    383: 	}
                    384: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  385: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  386: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    387: 	    close($fh);
                    388: 	    return 'error: '.$!;
                    389: 	}
1.692     albertel  390: 	foreach my $cur_key (@oldenv) {
                    391: 	    if ($cur_key=~/^$delthis/) { 
                    392:                 my ($key,undef) = split('=',$cur_key,2);
1.619     albertel  393:                 delete($env{$key});
1.473     matthew   394:             } else {
1.692     albertel  395:                 print $fh $cur_key; 
1.473     matthew   396:             }
1.448     albertel  397: 	}
                    398: 	close($fh);
1.5       www       399:     }
                    400:     return 'ok';
1.369     albertel  401: }
                    402: 
                    403: # ------------------------------------------ Find out current server userload
                    404: # there is a copy in lond
                    405: sub userload {
                    406:     my $numusers=0;
                    407:     {
                    408: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    409: 	my $filename;
                    410: 	my $curtime=time;
                    411: 	while ($filename=readdir(LONIDS)) {
                    412: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  413: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  414: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  415: 	}
                    416: 	closedir(LONIDS);
                    417:     }
                    418:     my $userloadpercent=0;
                    419:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    420:     if ($maxuserload) {
1.371     albertel  421: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  422:     }
1.372     albertel  423:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  424:     return $userloadpercent;
1.283     www       425: }
                    426: 
                    427: # ------------------------------------------ Fight off request when overloaded
                    428: 
                    429: sub overloaderror {
                    430:     my ($r,$checkserver)=@_;
                    431:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    432:     my $loadavg;
                    433:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  434:        open(my $loadfile,'/proc/loadavg');
1.283     www       435:        $loadavg=<$loadfile>;
                    436:        $loadavg =~ s/\s.*//g;
1.285     matthew   437:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  438:        close($loadfile);
1.283     www       439:     } else {
                    440:        $loadavg=&reply('load',$checkserver);
                    441:     }
1.285     matthew   442:     my $overload=$loadavg-100;
1.283     www       443:     if ($overload>0) {
1.285     matthew   444: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       445:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       446:         return 413;
1.283     www       447:     }    
                    448:     return '';
1.5       www       449: }
1.1       albertel  450: 
                    451: # ------------------------------ Find server with least workload from spare.tab
1.11      www       452: 
1.1       albertel  453: sub spareserver {
1.670     albertel  454:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  455:     my $tryserver;
                    456:     my $spareserver='';
1.370     albertel  457:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    458:     my $lowestserver=$loadpercent > $userloadpercent?
                    459: 	             $loadpercent :  $userloadpercent;
1.670     albertel  460:     foreach $tryserver (keys(%spareid)) {
                    461: 	my $loadans=&reply('load',$tryserver);
                    462: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  463: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    464: 	    next; #didn't get a number from the server
                    465: 	}
                    466: 	my $answer;
                    467: 	if ($loadans =~ /\d/) {
                    468: 	    if ($userloadans =~ /\d/) {
                    469: 		#both are numbers, pick the bigger one
                    470: 		$answer=$loadans > $userloadans?
                    471: 		    $loadans :  $userloadans;
                    472: 	    } else {
                    473: 		$answer = $loadans;
                    474: 	    }
                    475: 	} else {
                    476: 	    $answer = $userloadans;
                    477: 	}
                    478: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  479: 	    if ($want_server_name) {
                    480: 		$spareserver=$tryserver;
                    481: 	    } else {
                    482: 		$spareserver="http://$hostname{$tryserver}";
                    483: 	    }
1.411     albertel  484: 	    $lowestserver=$answer;
                    485: 	}
1.370     albertel  486:     }
1.1       albertel  487:     return $spareserver;
1.202     matthew   488: }
                    489: 
                    490: # --------------------------------------------- Try to change a user's password
                    491: 
                    492: sub changepass {
                    493:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    494:     $currentpass = &escape($currentpass);
                    495:     $newpass     = &escape($newpass);
                    496:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    497: 		       $server);
                    498:     if (! $answer) {
                    499: 	&logthis("No reply on password change request to $server ".
                    500: 		 "by $uname in domain $udom.");
                    501:     } elsif ($answer =~ "^ok") {
                    502:         &logthis("$uname in $udom successfully changed their password ".
                    503: 		 "on $server.");
                    504:     } elsif ($answer =~ "^pwchange_failure") {
                    505: 	&logthis("$uname in $udom was unable to change their password ".
                    506: 		 "on $server.  The action was blocked by either lcpasswd ".
                    507: 		 "or pwchange");
                    508:     } elsif ($answer =~ "^non_authorized") {
                    509:         &logthis("$uname in $udom did not get their password correct when ".
                    510: 		 "attempting to change it on $server.");
                    511:     } elsif ($answer =~ "^auth_mode_error") {
                    512:         &logthis("$uname in $udom attempted to change their password despite ".
                    513: 		 "not being locally or internally authenticated on $server.");
                    514:     } elsif ($answer =~ "^unknown_user") {
                    515:         &logthis("$uname in $udom attempted to change their password ".
                    516: 		 "on $server but were unable to because $server is not ".
                    517: 		 "their home server.");
                    518:     } elsif ($answer =~ "^refused") {
                    519: 	&logthis("$server refused to change $uname in $udom password because ".
                    520: 		 "it was sent an unencrypted request to change the password.");
                    521:     }
                    522:     return $answer;
1.1       albertel  523: }
                    524: 
1.169     harris41  525: # ----------------------- Try to determine user's current authentication scheme
                    526: 
                    527: sub queryauthenticate {
                    528:     my ($uname,$udom)=@_;
1.456     albertel  529:     my $uhome=&homeserver($uname,$udom);
                    530:     if (!$uhome) {
                    531: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    532: 	return 'no_host';
                    533:     }
                    534:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    535:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    536: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  537:     }
1.456     albertel  538:     return $answer;
1.169     harris41  539: }
                    540: 
1.1       albertel  541: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       542: 
1.1       albertel  543: sub authenticate {
                    544:     my ($uname,$upass,$udom)=@_;
1.12      www       545:     $upass=escape($upass);
1.199     www       546:     $uname=~s/\W//g;
1.471     albertel  547:     my $uhome=&homeserver($uname,$udom);
                    548:     if (!$uhome) {
                    549: 	&logthis("User $uname at $udom is unknown in authenticate");
                    550: 	return 'no_host';
1.1       albertel  551:     }
1.471     albertel  552:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    553:     if ($answer eq 'authorized') {
                    554: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    555: 	return $uhome; 
                    556:     }
                    557:     if ($answer eq 'non_authorized') {
                    558: 	&logthis("User $uname at $udom rejected by $uhome");
                    559: 	return 'no_host'; 
1.9       www       560:     }
1.471     albertel  561:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  562:     return 'no_host';
                    563: }
                    564: 
                    565: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       566: 
1.599     albertel  567: my %homecache;
1.1       albertel  568: sub homeserver {
1.230     stredwic  569:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  570:     my $index="$uname:$udom";
1.426     albertel  571: 
1.599     albertel  572:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  573:     my $tryserver;
                    574:     foreach $tryserver (keys %libserv) {
1.230     stredwic  575:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  576: 		 exists($badServerCache{$tryserver}));
1.1       albertel  577: 	if ($hostdom{$tryserver} eq $udom) {
                    578:            my $answer=reply("home:$udom:$uname",$tryserver);
                    579:            if ($answer eq 'found') { 
1.599     albertel  580: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  581:            } elsif ($answer eq 'no_host') {
                    582: 	       $badServerCache{$tryserver}=1;
1.221     matthew   583:            }
1.1       albertel  584:        }
                    585:     }    
                    586:     return 'no_host';
1.70      www       587: }
                    588: 
                    589: # ------------------------------------- Find the usernames behind a list of IDs
                    590: 
                    591: sub idget {
                    592:     my ($udom,@ids)=@_;
                    593:     my %returnhash=();
                    594:     
                    595:     my $tryserver;
                    596:     foreach $tryserver (keys %libserv) {
                    597:        if ($hostdom{$tryserver} eq $udom) {
                    598: 	  my $idlist=join('&',@ids);
                    599:           $idlist=~tr/A-Z/a-z/; 
                    600: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    601:           my @answer=();
1.76      www       602:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       603: 	      @answer=split(/\&/,$reply);
                    604:           }                    ;
                    605:           my $i;
                    606:           for ($i=0;$i<=$#ids;$i++) {
                    607:               if ($answer[$i]) {
                    608: 		  $returnhash{$ids[$i]}=$answer[$i];
                    609:               } 
                    610:           }
                    611:        }
                    612:     }    
                    613:     return %returnhash;
                    614: }
                    615: 
                    616: # ------------------------------------- Find the IDs behind a list of usernames
                    617: 
                    618: sub idrget {
                    619:     my ($udom,@unames)=@_;
                    620:     my %returnhash=();
1.191     harris41  621:     foreach (@unames) {
1.70      www       622:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  623:     }
1.70      www       624:     return %returnhash;
                    625: }
                    626: 
                    627: # ------------------------------- Store away a list of names and associated IDs
                    628: 
                    629: sub idput {
                    630:     my ($udom,%ids)=@_;
                    631:     my %servers=();
1.191     harris41  632:     foreach (keys %ids) {
1.487     albertel  633: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       634:         my $uhom=&homeserver($_,$udom);
                    635:         if ($uhom ne 'no_host') {
                    636:             my $id=&escape($ids{$_});
                    637:             $id=~tr/A-Z/a-z/;
                    638:             my $unam=&escape($_);
                    639: 	    if ($servers{$uhom}) {
                    640: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    641:             } else {
                    642:                 $servers{$uhom}=$id.'='.$unam;
                    643:             }
                    644:         }
1.191     harris41  645:     }
                    646:     foreach (keys %servers) {
1.70      www       647:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  648:     }
1.344     www       649: }
                    650: 
                    651: # --------------------------------------------------- Assign a key to a student
                    652: 
                    653: sub assign_access_key {
1.364     www       654: #
                    655: # a valid key looks like uname:udom#comments
                    656: # comments are being appended
                    657: #
1.498     www       658:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    659:     $kdom=
1.620     albertel  660:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       661:     $knum=
1.620     albertel  662:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       663:     $cdom=
1.620     albertel  664:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       665:     $cnum=
1.620     albertel  666:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    667:     $udom=$env{'user.name'} unless (defined($udom));
                    668:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       669:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       670:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  671:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       672:                                                   # assigned to this person
                    673:                                                   # - this should not happen,
1.345     www       674:                                                   # unless something went wrong
                    675:                                                   # the first time around
                    676: # ready to assign
1.364     www       677:         $logentry=$1.'; '.$logentry;
1.496     www       678:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       679:                                                  $kdom,$knum) eq 'ok') {
1.345     www       680: # key now belongs to user
1.346     www       681: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       682:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    683:                 &appenv('environment.'.$envkey => $ckey);
                    684:                 return 'ok';
                    685:             } else {
                    686:                 return 
                    687:   'error: Count not permanently assign key, will need to be re-entered later.';
                    688: 	    }
                    689:         } else {
                    690:             return 'error: Could not assign key, try again later.';
                    691:         }
1.364     www       692:     } elsif (!$existing{$ckey}) {
1.345     www       693: # the key does not exist
                    694: 	return 'error: The key does not exist';
                    695:     } else {
                    696: # the key is somebody else's
                    697: 	return 'error: The key is already in use';
                    698:     }
1.344     www       699: }
                    700: 
1.364     www       701: # ------------------------------------------ put an additional comment on a key
                    702: 
                    703: sub comment_access_key {
                    704: #
                    705: # a valid key looks like uname:udom#comments
                    706: # comments are being appended
                    707: #
                    708:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    709:     $cdom=
1.620     albertel  710:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       711:     $cnum=
1.620     albertel  712:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       713:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    714:     if ($existing{$ckey}) {
                    715:         $existing{$ckey}.='; '.$logentry;
                    716: # ready to assign
1.367     www       717:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       718:                                                  $cdom,$cnum) eq 'ok') {
                    719: 	    return 'ok';
                    720:         } else {
                    721: 	    return 'error: Count not store comment.';
                    722:         }
                    723:     } else {
                    724: # the key does not exist
                    725: 	return 'error: The key does not exist';
                    726:     }
                    727: }
                    728: 
1.344     www       729: # ------------------------------------------------------ Generate a set of keys
                    730: 
                    731: sub generate_access_keys {
1.364     www       732:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       733:     $cdom=
1.620     albertel  734:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       735:     $cnum=
1.620     albertel  736:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       737:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       738:     unless (($cdom) && ($cnum)) { return 0; }
                    739:     if ($number>10000) { return 0; }
                    740:     sleep(2); # make sure don't get same seed twice
                    741:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    742:     my $total=0;
                    743:     for (my $i=1;$i<=$number;$i++) {
                    744:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    745:                   sprintf("%lx",int(100000*rand)).'-'.
                    746:                   sprintf("%lx",int(100000*rand));
                    747:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    748:        $newkey=~s/0/h/g; # and also 0 and O
                    749:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    750:        if ($existing{$newkey}) {
                    751:            $i--;
                    752:        } else {
1.364     www       753: 	  if (&put('accesskeys',
                    754:               { $newkey => '# generated '.localtime().
1.620     albertel  755:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       756:                            '; '.$logentry },
                    757: 		   $cdom,$cnum) eq 'ok') {
1.344     www       758:               $total++;
                    759: 	  }
                    760:        }
                    761:     }
1.620     albertel  762:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       763:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    764:     return $total;
                    765: }
                    766: 
                    767: # ------------------------------------------------------- Validate an accesskey
                    768: 
                    769: sub validate_access_key {
                    770:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    771:     $cdom=
1.620     albertel  772:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       773:     $cnum=
1.620     albertel  774:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    775:     $udom=$env{'user.domain'} unless (defined($udom));
                    776:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       777:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  778:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       779: }
                    780: 
                    781: # ------------------------------------- Find the section of student in a course
1.652     albertel  782: sub devalidate_getsection_cache {
                    783:     my ($udom,$unam,$courseid)=@_;
                    784:     $courseid=~s/\_/\//g;
                    785:     $courseid=~s/^(\w)/\/$1/;
                    786:     my $hashid="$udom:$unam:$courseid";
                    787:     &devalidate_cache_new('getsection',$hashid);
                    788: }
1.298     matthew   789: 
                    790: sub getsection {
                    791:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  792:     my $cachetime=1800;
1.298     matthew   793:     $courseid=~s/\_/\//g;
                    794:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  795: 
                    796:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  797:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  798:     if (defined($cached)) { return $result; }
                    799: 
1.298     matthew   800:     my %Pending; 
                    801:     my %Expired;
                    802:     #
                    803:     # Each role can either have not started yet (pending), be active, 
                    804:     #    or have expired.
                    805:     #
                    806:     # If there is an active role, we are done.
                    807:     #
                    808:     # If there is more than one role which has not started yet, 
                    809:     #     choose the one which will start sooner
                    810:     # If there is one role which has not started yet, return it.
                    811:     #
                    812:     # If there is more than one expired role, choose the one which ended last.
                    813:     # If there is a role which has expired, return it.
                    814:     #
                    815:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    816:                         &homeserver($unam,$udom)))) {
                    817:         my ($key,$value)=split(/\=/,$_);
                    818:         $key=&unescape($key);
1.479     albertel  819:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   820:         my $section=$1;
                    821:         if ($key eq $courseid.'_st') { $section=''; }
                    822:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    823:         my $now=time;
1.548     albertel  824:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   825:             $Expired{$end}=$section;
                    826:             next;
                    827:         }
1.548     albertel  828:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   829:             $Pending{$start}=$section;
                    830:             next;
                    831:         }
1.599     albertel  832:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   833:     }
                    834:     #
                    835:     # Presumedly there will be few matching roles from the above
                    836:     # loop and the sorting time will be negligible.
                    837:     if (scalar(keys(%Pending))) {
                    838:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  839:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   840:     } 
                    841:     if (scalar(keys(%Expired))) {
                    842:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    843:         my $time = pop(@sorted);
1.599     albertel  844:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   845:     }
1.599     albertel  846:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   847: }
1.70      www       848: 
1.599     albertel  849: sub save_cache {
1.628     albertel  850:     my ($r)=@_;
                    851:     if (! $r->is_initial_req()) { return DECLINED; }
1.599     albertel  852:     &purge_remembered();
1.620     albertel  853:     undef(%env);
1.628     albertel  854:     return OK;
1.599     albertel  855: }
1.452     albertel  856: 
1.599     albertel  857: my $to_remember=-1;
                    858: my %remembered;
                    859: my %accessed;
                    860: my $kicks=0;
                    861: my $hits=0;
                    862: sub devalidate_cache_new {
                    863:     my ($name,$id,$debug) = @_;
                    864:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    865:     $id=&escape($name.':'.$id);
                    866:     $memcache->delete($id);
                    867:     delete($remembered{$id});
                    868:     delete($accessed{$id});
                    869: }
                    870: 
                    871: sub is_cached_new {
                    872:     my ($name,$id,$debug) = @_;
                    873:     $id=&escape($name.':'.$id);
                    874:     if (exists($remembered{$id})) {
                    875: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    876: 	$accessed{$id}=[&gettimeofday()];
                    877: 	$hits++;
                    878: 	return ($remembered{$id},1);
                    879:     }
                    880:     my $value = $memcache->get($id);
                    881:     if (!(defined($value))) {
                    882: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  883: 	return (undef,undef);
1.416     albertel  884:     }
1.599     albertel  885:     if ($value eq '__undef__') {
                    886: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    887: 	$value=undef;
                    888:     }
                    889:     &make_room($id,$value,$debug);
                    890:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    891:     return ($value,1);
                    892: }
                    893: 
                    894: sub do_cache_new {
                    895:     my ($name,$id,$value,$time,$debug) = @_;
                    896:     $id=&escape($name.':'.$id);
                    897:     my $setvalue=$value;
                    898:     if (!defined($setvalue)) {
                    899: 	$setvalue='__undef__';
                    900:     }
1.623     albertel  901:     if (!defined($time) ) {
                    902: 	$time=600;
                    903:     }
1.599     albertel  904:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  905:     $memcache->set($id,$setvalue,$time);
                    906:     # need to make a copy of $value
                    907:     #&make_room($id,$value,$debug);
1.599     albertel  908:     return $value;
                    909: }
                    910: 
                    911: sub make_room {
                    912:     my ($id,$value,$debug)=@_;
                    913:     $remembered{$id}=$value;
                    914:     if ($to_remember<0) { return; }
                    915:     $accessed{$id}=[&gettimeofday()];
                    916:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    917:     my $to_kick;
                    918:     my $max_time=0;
                    919:     foreach my $other (keys(%accessed)) {
                    920: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    921: 	    $to_kick=$other;
                    922: 	    $max_time=&tv_interval($accessed{$other});
                    923: 	}
                    924:     }
                    925:     delete($remembered{$to_kick});
                    926:     delete($accessed{$to_kick});
                    927:     $kicks++;
                    928:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  929:     return;
                    930: }
                    931: 
1.599     albertel  932: sub purge_remembered {
1.604     albertel  933:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    934:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  935:     undef(%remembered);
                    936:     undef(%accessed);
1.428     albertel  937: }
1.70      www       938: # ------------------------------------- Read an entry from a user's environment
                    939: 
                    940: sub userenvironment {
                    941:     my ($udom,$unam,@what)=@_;
                    942:     my %returnhash=();
                    943:     my @answer=split(/\&/,
                    944:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    945:                       &homeserver($unam,$udom)));
                    946:     my $i;
                    947:     for ($i=0;$i<=$#what;$i++) {
                    948: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    949:     }
                    950:     return %returnhash;
1.1       albertel  951: }
                    952: 
1.617     albertel  953: # ---------------------------------------------------------- Get a studentphoto
                    954: sub studentphoto {
                    955:     my ($udom,$unam,$ext) = @_;
                    956:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   957:     if (defined($env{'request.course.id'})) {
1.708     raeburn   958:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   959:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    960:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    961:             } else {
                    962:                 my ($result,$perm_reqd)=
1.707     albertel  963: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   964:                 if ($result eq 'ok') {
                    965:                     if (!($perm_reqd eq 'yes')) {
                    966:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    967:                     }
                    968:                 }
                    969:             }
                    970:         }
                    971:     } else {
                    972:         my ($result,$perm_reqd) = 
1.707     albertel  973: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   974:         if ($result eq 'ok') {
                    975:             if (!($perm_reqd eq 'yes')) {
                    976:                 return(&retrievestudentphoto($udom,$unam,$ext));
                    977:             }
                    978:         }
                    979:     }
                    980:     return '/adm/lonKaputt/lonlogo_broken.gif';
                    981: }
                    982: 
                    983: sub retrievestudentphoto {
                    984:     my ($udom,$unam,$ext,$type) = @_;
                    985:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                    986:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                    987:     if ($ret eq 'ok') {
                    988:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                    989:         if ($type eq 'thumbnail') {
                    990:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                    991:         }
                    992:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                    993:         return $tokenurl;
                    994:     } else {
                    995:         if ($type eq 'thumbnail') {
                    996:             return '/adm/lonKaputt/genericstudent_tn.gif';
                    997:         } else { 
                    998:             return '/adm/lonKaputt/lonlogo_broken.gif';
                    999:         }
1.617     albertel 1000:     }
                   1001: }
                   1002: 
1.263     www      1003: # -------------------------------------------------------------------- New chat
                   1004: 
                   1005: sub chatsend {
                   1006:     my ($newentry,$anon)=@_;
1.620     albertel 1007:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1008:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1009:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1010:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1011: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.263     www      1012: 		   &escape($newentry)),$chome);
1.292     www      1013: }
                   1014: 
                   1015: # ------------------------------------------ Find current version of a resource
                   1016: 
                   1017: sub getversion {
                   1018:     my $fname=&clutter(shift);
                   1019:     unless ($fname=~/^\/res\//) { return -1; }
                   1020:     return &currentversion(&filelocation('',$fname));
                   1021: }
                   1022: 
                   1023: sub currentversion {
                   1024:     my $fname=shift;
1.599     albertel 1025:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1026:     if (defined($cached)) { return $result; }
1.292     www      1027:     my $author=$fname;
                   1028:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1029:     my ($udom,$uname)=split(/\//,$author);
                   1030:     my $home=homeserver($uname,$udom);
                   1031:     if ($home eq 'no_host') { 
                   1032:         return -1; 
                   1033:     }
                   1034:     my $answer=reply("currentversion:$fname",$home);
                   1035:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1036: 	return -1;
                   1037:     }
1.599     albertel 1038:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1039: }
                   1040: 
1.1       albertel 1041: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1042: 
1.1       albertel 1043: sub subscribe {
                   1044:     my $fname=shift;
1.312     www      1045:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1046:     $fname=~s/[\n\r]//g;
1.1       albertel 1047:     my $author=$fname;
                   1048:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1049:     my ($udom,$uname)=split(/\//,$author);
                   1050:     my $home=homeserver($uname,$udom);
1.335     albertel 1051:     if ($home eq 'no_host') {
                   1052:         return 'not_found';
1.1       albertel 1053:     }
                   1054:     my $answer=reply("sub:$fname",$home);
1.64      www      1055:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1056: 	$answer.=' by '.$home;
                   1057:     }
1.1       albertel 1058:     return $answer;
                   1059: }
                   1060:     
1.8       www      1061: # -------------------------------------------------------------- Replicate file
                   1062: 
                   1063: sub repcopy {
                   1064:     my $filename=shift;
1.23      www      1065:     $filename=~s/\/+/\//g;
1.607     raeburn  1066:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1067:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1068:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1069: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1070: 	return &repcopy_userfile($filename);
                   1071:     }
1.532     albertel 1072:     $filename=~s/[\n\r]//g;
1.8       www      1073:     my $transname="$filename.in.transfer";
1.607     raeburn  1074:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1075:     my $remoteurl=subscribe($filename);
1.64      www      1076:     if ($remoteurl =~ /^con_lost by/) {
                   1077: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1078:            return 'unavailable';
1.8       www      1079:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1080: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1081: 	   return 'not_found';
1.64      www      1082:     } elsif ($remoteurl =~ /^rejected by/) {
                   1083: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1084:            return 'forbidden';
1.20      www      1085:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1086:            return 'ok';
1.8       www      1087:     } else {
1.290     www      1088:         my $author=$filename;
                   1089:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1090:         my ($udom,$uname)=split(/\//,$author);
                   1091:         my $home=homeserver($uname,$udom);
                   1092:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1093:            my @parts=split(/\//,$filename);
                   1094:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1095:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1096:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1097: 	       return 'bad_request';
1.8       www      1098:            }
                   1099:            my $count;
                   1100:            for ($count=5;$count<$#parts;$count++) {
                   1101:                $path.="/$parts[$count]";
                   1102:                if ((-e $path)!=1) {
                   1103: 		   mkdir($path,0777);
                   1104:                }
                   1105:            }
                   1106:            my $ua=new LWP::UserAgent;
                   1107:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1108:            my $response=$ua->request($request,$transname);
                   1109:            if ($response->is_error()) {
                   1110: 	       unlink($transname);
                   1111:                my $message=$response->status_line;
1.672     albertel 1112:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1113:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1114:                return 'unavailable';
1.8       www      1115:            } else {
1.16      www      1116: 	       if ($remoteurl!~/\.meta$/) {
                   1117:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1118:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1119:                   if ($mresponse->is_error()) {
                   1120: 		      unlink($filename.'.meta');
                   1121:                       &logthis(
1.672     albertel 1122:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1123:                   }
                   1124: 	       }
1.8       www      1125:                rename($transname,$filename);
1.607     raeburn  1126:                return 'ok';
1.8       www      1127:            }
1.290     www      1128:        }
1.8       www      1129:     }
1.330     www      1130: }
                   1131: 
                   1132: # ------------------------------------------------ Get server side include body
                   1133: sub ssi_body {
1.381     albertel 1134:     my ($filelink,%form)=@_;
1.606     matthew  1135:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1136:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1137:     }
1.330     www      1138:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1139:                                      &ssi($filelink,%form));
1.565     albertel 1140:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1141:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1142:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1143:     return $output;
1.8       www      1144: }
                   1145: 
1.15      www      1146: # --------------------------------------------------------- Server Side Include
                   1147: 
                   1148: sub ssi {
                   1149: 
1.23      www      1150:     my ($fn,%form)=@_;
1.15      www      1151: 
                   1152:     my $ua=new LWP::UserAgent;
1.23      www      1153:     
                   1154:     my $request;
1.711     albertel 1155: 
                   1156:     $form{'no_update_last_known'}=1;
                   1157: 
1.23      www      1158:     if (%form) {
                   1159:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1160:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1161:     } else {
                   1162:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1163:     }
                   1164: 
1.15      www      1165:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1166:     my $response=$ua->request($request);
                   1167: 
1.324     www      1168:     return $response->content;
                   1169: }
                   1170: 
                   1171: sub externalssi {
                   1172:     my ($url)=@_;
                   1173:     my $ua=new LWP::UserAgent;
                   1174:     my $request=new HTTP::Request('GET',$url);
                   1175:     my $response=$ua->request($request);
1.15      www      1176:     return $response->content;
                   1177: }
1.254     www      1178: 
1.492     albertel 1179: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1180: 
                   1181: sub allowuploaded {
                   1182:     my ($srcurl,$url)=@_;
                   1183:     $url=&clutter(&declutter($url));
                   1184:     my $dir=$url;
                   1185:     $dir=~s/\/[^\/]+$//;
                   1186:     my %httpref=();
                   1187:     my $httpurl=&hreflocation('',$url);
                   1188:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1189:     &Apache::lonnet::appenv(%httpref);
1.254     www      1190: }
1.477     raeburn  1191: 
1.478     albertel 1192: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1193: # input: action, courseID, current domain, intended
1.637     raeburn  1194: #        path to file, source of file, instruction to parse file for objects,
                   1195: #        ref to hash for embedded objects,
                   1196: #        ref to hash for codebase of java objects.
                   1197: #
1.485     raeburn  1198: # output: url to file (if action was uploaddoc), 
                   1199: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1200: #
1.478     albertel 1201: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1202: # course.
1.477     raeburn  1203: #
1.478     albertel 1204: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1205: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1206: #          course's home server.
1.477     raeburn  1207: #
1.478     albertel 1208: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1209: #          be copied from $source (current location) to 
                   1210: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1211: #         and will then be copied to
                   1212: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1213: #         course's home server.
1.485     raeburn  1214: #
1.481     raeburn  1215: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1216: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1217: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1218: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1219: #         in course's home server.
1.637     raeburn  1220: #
1.477     raeburn  1221: 
                   1222: sub process_coursefile {
1.638     albertel 1223:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1224:     my $fetchresult;
1.638     albertel 1225:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1226:     if ($action eq 'propagate') {
1.638     albertel 1227:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1228: 			     $home);
1.481     raeburn  1229:     } else {
1.477     raeburn  1230:         my $fpath = '';
                   1231:         my $fname = $file;
1.478     albertel 1232:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1233:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1234:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1235:         if ($action eq 'copy') {
                   1236:             if ($source eq '') {
                   1237:                 $fetchresult = 'no source file';
                   1238:                 return $fetchresult;
                   1239:             } else {
                   1240:                 my $destination = $filepath.'/'.$fname;
                   1241:                 rename($source,$destination);
                   1242:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1243:                                  $home);
1.481     raeburn  1244:             }
                   1245:         } elsif ($action eq 'uploaddoc') {
                   1246:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1247:             print $fh $env{'form.'.$source};
1.481     raeburn  1248:             close($fh);
1.637     raeburn  1249:             if ($parser eq 'parse') {
                   1250:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1251:                 unless ($parse_result eq 'ok') {
                   1252:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1253:                 }
                   1254:             }
1.477     raeburn  1255:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1256:                                  $home);
1.481     raeburn  1257:             if ($fetchresult eq 'ok') {
                   1258:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1259:             } else {
                   1260:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1261:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1262:                 return '/adm/notfound.html';
                   1263:             }
1.477     raeburn  1264:         }
                   1265:     }
1.485     raeburn  1266:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1267:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1268:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1269:     }
                   1270:     return $fetchresult;
                   1271: }
                   1272: 
1.637     raeburn  1273: sub build_filepath {
                   1274:     my ($fpath) = @_;
                   1275:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1276:     unless ($fpath eq '') {
                   1277:         my @parts=split('/',$fpath);
                   1278:         foreach my $part (@parts) {
                   1279:             $filepath.= '/'.$part;
                   1280:             if ((-e $filepath)!=1) {
                   1281:                 mkdir($filepath,0777);
                   1282:             }
                   1283:         }
                   1284:     }
                   1285:     return $filepath;
                   1286: }
                   1287: 
                   1288: sub store_edited_file {
1.638     albertel 1289:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1290:     my $file = $primary_url;
                   1291:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1292:     my $fpath = '';
                   1293:     my $fname = $file;
                   1294:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1295:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1296:     my $filepath = &build_filepath($fpath);
                   1297:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1298:     print $fh $content;
                   1299:     close($fh);
1.638     albertel 1300:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1301:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1302: 			  $home);
1.637     raeburn  1303:     if ($$fetchresult eq 'ok') {
                   1304:         return '/uploaded/'.$fpath.'/'.$fname;
                   1305:     } else {
1.638     albertel 1306:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1307: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1308:         return '/adm/notfound.html';
                   1309:     }
                   1310: }
                   1311: 
1.531     albertel 1312: sub clean_filename {
                   1313:     my ($fname)=@_;
1.315     www      1314: # Replace Windows backslashes by forward slashes
1.257     www      1315:     $fname=~s/\\/\//g;
1.315     www      1316: # Get rid of everything but the actual filename
1.257     www      1317:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1318: # Replace spaces by underscores
                   1319:     $fname=~s/\s+/\_/g;
                   1320: # Replace all other weird characters by nothing
1.317     www      1321:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1322: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1323: # numbers
                   1324:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1325:     return $fname;
                   1326: }
                   1327: 
1.608     albertel 1328: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1329: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1330: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1331: #        $coursedoc - if true up to the current course
                   1332: #                     if false
                   1333: #        $subdir - directory in userfile to store the file into
                   1334: #        $parser, $allfiles, $codebase - unknown
                   1335: #
                   1336: # output: url of file in userspace, or error: <message> 
                   1337: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1338: 
                   1339: 
1.531     albertel 1340: sub userfileupload {
1.719     banghart 1341:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1342:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1343:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1344:     $fname=&clean_filename($fname);
1.315     www      1345: # See if there is anything left
1.257     www      1346:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1347:     chop($env{'form.'.$formname});
1.523     raeburn  1348:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1349:         my $now = time;
                   1350:         my $filepath = 'tmp/helprequests/'.$now;
                   1351:         my @parts=split(/\//,$filepath);
                   1352:         my $fullpath = $perlvar{'lonDaemons'};
                   1353:         for (my $i=0;$i<@parts;$i++) {
                   1354:             $fullpath .= '/'.$parts[$i];
                   1355:             if ((-e $fullpath)!=1) {
                   1356:                 mkdir($fullpath,0777);
                   1357:             }
                   1358:         }
                   1359:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1360:         print $fh $env{'form.'.$formname};
1.523     raeburn  1361:         close($fh);
                   1362:         return $fullpath.'/'.$fname; 
                   1363:     }
1.719     banghart 1364:     
1.258     www      1365: # Create the directory if not present
1.493     albertel 1366:     $fname="$subdir/$fname";
1.259     www      1367:     if ($coursedoc) {
1.638     albertel 1368: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1369: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1370:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1371:             return &finishuserfileupload($docuname,$docudom,
                   1372: 					 $formname,$fname,$parser,$allfiles,
                   1373: 					 $codebase);
1.481     raeburn  1374:         } else {
1.620     albertel 1375:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1376:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1377: 				       $fname,$formname,$parser,
                   1378: 				       $allfiles,$codebase);
1.481     raeburn  1379:         }
1.719     banghart 1380:     } elsif (defined($destuname)) {
                   1381:         my $docuname=$destuname;
                   1382:         my $docudom=$destudom;
                   1383: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1384: 				     $fname,$parser,$allfiles,$codebase);
                   1385:         
1.259     www      1386:     } else {
1.638     albertel 1387:         my $docuname=$env{'user.name'};
                   1388:         my $docudom=$env{'user.domain'};
1.714     raeburn  1389:         if (exists($env{'form.group'})) {
                   1390:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1391:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1392:         }
1.638     albertel 1393: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1394: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1395:     }
1.271     www      1396: }
                   1397: 
                   1398: sub finishuserfileupload {
1.638     albertel 1399:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1400:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1401:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1402:     my ($fnamepath,$file);
                   1403:     $file=$fname;
                   1404:     if ($fname=~m|/|) {
                   1405:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1406: 	$path.=$fnamepath.'/';
                   1407:     }
1.259     www      1408:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1409:     my $count;
                   1410:     for ($count=4;$count<=$#parts;$count++) {
                   1411:         $filepath.="/$parts[$count]";
                   1412:         if ((-e $filepath)!=1) {
                   1413: 	    mkdir($filepath,0777);
                   1414:         }
                   1415:     }
                   1416: # Save the file
                   1417:     {
1.701     albertel 1418: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1419: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1420: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1421: 	    return '/adm/notfound.html';
                   1422: 	}
                   1423: 	if (!print FH ($env{'form.'.$formname})) {
                   1424: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1425: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1426: 	    return '/adm/notfound.html';
                   1427: 	}
1.570     albertel 1428: 	close(FH);
1.258     www      1429:     }
1.637     raeburn  1430:     if ($parser eq 'parse') {
1.638     albertel 1431:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1432: 						   $codebase);
1.637     raeburn  1433:         unless ($parse_result eq 'ok') {
1.638     albertel 1434:             &logthis('Failed to parse '.$filepath.$file.
                   1435: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1436:         }
                   1437:     }
1.259     www      1438: # Notify homeserver to grep it
                   1439: #
1.638     albertel 1440:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1441:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1442:     if ($fetchresult eq 'ok') {
1.259     www      1443: #
1.258     www      1444: # Return the URL to it
1.494     albertel 1445:         return '/uploaded/'.$path.$file;
1.263     www      1446:     } else {
1.494     albertel 1447:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1448: 		 ': '.$fetchresult);
1.263     www      1449:         return '/adm/notfound.html';
                   1450:     }    
1.493     albertel 1451: }
                   1452: 
1.637     raeburn  1453: sub extract_embedded_items {
1.648     raeburn  1454:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1455:     my @state = ();
                   1456:     my %javafiles = (
                   1457:                       codebase => '',
                   1458:                       code => '',
                   1459:                       archive => ''
                   1460:                     );
                   1461:     my %mediafiles = (
                   1462:                       src => '',
                   1463:                       movie => '',
                   1464:                      );
1.648     raeburn  1465:     my $p;
                   1466:     if ($content) {
                   1467:         $p = HTML::LCParser->new($content);
                   1468:     } else {
                   1469:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1470:     }
1.641     albertel 1471:     while (my $t=$p->get_token()) {
1.640     albertel 1472: 	if ($t->[0] eq 'S') {
                   1473: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1474: 	    push (@state, $tagname);
1.648     raeburn  1475:             if (lc($tagname) eq 'allow') {
                   1476:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1477:             }
1.640     albertel 1478: 	    if (lc($tagname) eq 'img') {
                   1479: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1480: 	    }
1.645     raeburn  1481:             if (lc($tagname) eq 'script') {
                   1482:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1483:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1484:                 } else {
                   1485:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1486:                 }
                   1487:             }
                   1488:             if (lc($tagname) eq 'link') {
                   1489:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1490:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1491:                 }
                   1492:             }
1.640     albertel 1493: 	    if (lc($tagname) eq 'object' ||
                   1494: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1495: 		foreach my $item (keys(%javafiles)) {
                   1496: 		    $javafiles{$item} = '';
                   1497: 		}
                   1498: 	    }
                   1499: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1500: 		my $name = lc($attr->{'name'});
                   1501: 		foreach my $item (keys(%javafiles)) {
                   1502: 		    if ($name eq $item) {
                   1503: 			$javafiles{$item} = $attr->{'value'};
                   1504: 			last;
                   1505: 		    }
                   1506: 		}
                   1507: 		foreach my $item (keys(%mediafiles)) {
                   1508: 		    if ($name eq $item) {
                   1509: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1510: 			last;
                   1511: 		    }
                   1512: 		}
                   1513: 	    }
                   1514: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1515: 		foreach my $item (keys(%javafiles)) {
                   1516: 		    if ($attr->{$item}) {
                   1517: 			$javafiles{$item} = $attr->{$item};
                   1518: 			last;
                   1519: 		    }
                   1520: 		}
                   1521: 		foreach my $item (keys(%mediafiles)) {
                   1522: 		    if ($attr->{$item}) {
                   1523: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1524: 			last;
                   1525: 		    }
                   1526: 		}
                   1527: 	    }
                   1528: 	} elsif ($t->[0] eq 'E') {
                   1529: 	    my ($tagname) = ($t->[1]);
                   1530: 	    if ($javafiles{'codebase'} ne '') {
                   1531: 		$javafiles{'codebase'} .= '/';
                   1532: 	    }  
                   1533: 	    if (lc($tagname) eq 'applet' ||
                   1534: 		lc($tagname) eq 'object' ||
                   1535: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1536: 		) {
                   1537: 		foreach my $item (keys(%javafiles)) {
                   1538: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1539: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1540: 			&add_filetype($allfiles,$file,$item);
                   1541: 		    }
                   1542: 		}
                   1543: 	    } 
                   1544: 	    pop @state;
                   1545: 	}
                   1546:     }
1.637     raeburn  1547:     return 'ok';
                   1548: }
                   1549: 
1.639     albertel 1550: sub add_filetype {
                   1551:     my ($allfiles,$file,$type)=@_;
                   1552:     if (exists($allfiles->{$file})) {
                   1553: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1554: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1555: 	}
                   1556:     } else {
                   1557: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1558:     }
                   1559: }
                   1560: 
1.493     albertel 1561: sub removeuploadedurl {
                   1562:     my ($url)=@_;
                   1563:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1564:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1565: }
                   1566: 
                   1567: sub removeuserfile {
                   1568:     my ($docuname,$docudom,$fname)=@_;
                   1569:     my $home=&homeserver($docuname,$docudom);
                   1570:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1571: }
1.15      www      1572: 
1.530     albertel 1573: sub mkdiruserfile {
                   1574:     my ($docuname,$docudom,$dir)=@_;
                   1575:     my $home=&homeserver($docuname,$docudom);
                   1576:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1577: }
                   1578: 
1.531     albertel 1579: sub renameuserfile {
                   1580:     my ($docuname,$docudom,$old,$new)=@_;
                   1581:     my $home=&homeserver($docuname,$docudom);
                   1582:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1583: 		  &escape("$new"),$home);
                   1584: }
                   1585: 
1.14      www      1586: # ------------------------------------------------------------------------- Log
                   1587: 
                   1588: sub log {
                   1589:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1590:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1591: }
                   1592: 
                   1593: # ------------------------------------------------------------------ Course Log
1.352     www      1594: #
                   1595: # This routine flushes several buffers of non-mission-critical nature
                   1596: #
1.157     www      1597: 
                   1598: sub flushcourselogs {
1.352     www      1599:     &logthis('Flushing log buffers');
                   1600: #
                   1601: # course logs
                   1602: # This is a log of all transactions in a course, which can be used
                   1603: # for data mining purposes
                   1604: #
                   1605: # It also collects the courseid database, which lists last transaction
                   1606: # times and course titles for all courseids
                   1607: #
                   1608:     my %courseidbuffer=();
1.191     harris41 1609:     foreach (keys %courselogs) {
1.157     www      1610:         my $crsid=$_;
1.352     www      1611:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1612: 		          &escape($courselogs{$crsid}),
                   1613: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1614: 	    delete $courselogs{$crsid};
                   1615:         } else {
                   1616:             &logthis('Failed to flush log buffer for '.$crsid);
                   1617:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1618:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1619:                         " exceeded maximum size, deleting.</font>");
                   1620:                delete $courselogs{$crsid};
                   1621:             }
1.352     www      1622:         }
                   1623:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1624:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1625: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1626:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352     www      1627:         } else {
                   1628:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1629: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1630:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
                   1631:         }
1.191     harris41 1632:     }
1.352     www      1633: #
                   1634: # Write course id database (reverse lookup) to homeserver of courses 
                   1635: # Is used in pickcourse
                   1636: #
                   1637:     foreach (keys %courseidbuffer) {
1.353     www      1638:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1639:     }
                   1640: #
                   1641: # File accesses
                   1642: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1643: #
1.449     matthew  1644:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1645:         if ($entry =~ /___count$/) {
                   1646:             my ($dom,$name);
                   1647:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1648:             if (! defined($dom) || $dom eq '' || 
                   1649:                 ! defined($name) || $name eq '') {
1.620     albertel 1650:                 my $cid = $env{'request.course.id'};
                   1651:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1652:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1653:             }
1.450     matthew  1654:             my $value = $accesshash{$entry};
                   1655:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1656:             my %temphash=($url => $value);
1.449     matthew  1657:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1658:             if ($result eq 'ok') {
                   1659:                 delete $accesshash{$entry};
                   1660:             } elsif ($result eq 'unknown_cmd') {
                   1661:                 # Target server has old code running on it.
1.450     matthew  1662:                 my %temphash=($entry => $value);
1.449     matthew  1663:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1664:                     delete $accesshash{$entry};
                   1665:                 }
                   1666:             }
                   1667:         } else {
1.458     matthew  1668:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1669:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1670:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1671:                 delete $accesshash{$entry};
                   1672:             }
1.185     www      1673:         }
1.191     harris41 1674:     }
1.352     www      1675: #
                   1676: # Roles
                   1677: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1678: #
1.349     www      1679:     foreach (keys %userrolehash) {
                   1680:         my $entry=$_;
1.351     www      1681:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1682: 	    split(/\:/,$entry);
                   1683:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1684:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1685:                 $rudom,$runame) eq 'ok') {
                   1686: 	    delete $userrolehash{$entry};
                   1687:         }
                   1688:     }
1.662     raeburn  1689: #
                   1690: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1691: #
                   1692:     my %domrolebuffer = ();
                   1693:     foreach my $entry (keys %domainrolehash) {
                   1694:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1695:         if ($domrolebuffer{$rudom}) {
                   1696:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1697:                       '='.&escape($domainrolehash{$entry});
                   1698:         } else {
                   1699:             $domrolebuffer{$rudom}.=&escape($entry).
                   1700:                       '='.&escape($domainrolehash{$entry});
                   1701:         }
                   1702:         delete $domainrolehash{$entry};
                   1703:     }
                   1704:     foreach my $dom (keys(%domrolebuffer)) {
                   1705:         foreach my $tryserver (keys %libserv) {
                   1706:             if ($hostdom{$tryserver} eq $dom) {
                   1707:                 unless (&reply('domroleput:'.$dom.':'.
                   1708:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1709:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1710:                 }
                   1711:             }
                   1712:         }
                   1713:     }
1.186     www      1714:     $dumpcount++;
1.157     www      1715: }
                   1716: 
                   1717: sub courselog {
                   1718:     my $what=shift;
1.158     www      1719:     $what=time.':'.$what;
1.620     albertel 1720:     unless ($env{'request.course.id'}) { return ''; }
                   1721:     $coursedombuf{$env{'request.course.id'}}=
                   1722:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1723:     $coursenumbuf{$env{'request.course.id'}}=
                   1724:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1725:     $coursehombuf{$env{'request.course.id'}}=
                   1726:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1727:     $coursedescrbuf{$env{'request.course.id'}}=
                   1728:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1729:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1730:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1731:     $courseownerbuf{$env{'request.course.id'}}=
                   1732:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   1733:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1734: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1735:     } else {
1.620     albertel 1736: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1737:     }
1.620     albertel 1738:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1739: 	&flushcourselogs();
                   1740:     }
1.158     www      1741: }
                   1742: 
                   1743: sub courseacclog {
                   1744:     my $fnsymb=shift;
1.620     albertel 1745:     unless ($env{'request.course.id'}) { return ''; }
                   1746:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1747:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1748:         $what.=':POST';
1.583     matthew  1749:         # FIXME: Probably ought to escape things....
1.620     albertel 1750: 	foreach (keys %env) {
1.158     www      1751:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1752: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1753:             }
1.191     harris41 1754:         }
1.583     matthew  1755:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1756:         # FIXME: We should not be depending on a form parameter that someone
                   1757:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1758:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1759:             $what.= ':POST';
                   1760:             # FIXME: Probably ought to escape things....
                   1761:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1762:                                  'crsdiscuss') {
1.620     albertel 1763:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1764:             }
                   1765:         }
1.158     www      1766:     }
                   1767:     &courselog($what);
1.149     www      1768: }
                   1769: 
1.185     www      1770: sub countacc {
                   1771:     my $url=&declutter(shift);
1.458     matthew  1772:     return if (! defined($url) || $url eq '');
1.620     albertel 1773:     unless ($env{'request.course.id'}) { return ''; }
                   1774:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1775:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1776:     $accesshash{$key}++;
1.185     www      1777: }
1.349     www      1778: 
1.361     www      1779: sub linklog {
                   1780:     my ($from,$to)=@_;
                   1781:     $from=&declutter($from);
                   1782:     $to=&declutter($to);
                   1783:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1784:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1785: }
                   1786:   
1.349     www      1787: sub userrolelog {
                   1788:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1789:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1790:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1791:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1792:         ($trole=~/^ta/)) {
1.350     www      1793:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1794:        $userrolehash
                   1795:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1796:                     =$tend.':'.$tstart;
1.662     raeburn  1797:     }
                   1798:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1799:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1800:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1801:         ($trole=~/^sc/)) {
                   1802:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1803:        $domainrolehash
                   1804:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1805:                     = $tend.':'.$tstart;
                   1806:     }
1.351     www      1807: }
                   1808: 
                   1809: sub get_course_adv_roles {
                   1810:     my $cid=shift;
1.620     albertel 1811:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1812:     my %coursehash=&coursedescription($cid);
1.470     www      1813:     my %nothide=();
                   1814:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1815: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1816:     }
1.351     www      1817:     my %returnhash=();
                   1818:     my %dumphash=
                   1819:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1820:     my $now=time;
                   1821:     foreach (keys %dumphash) {
                   1822: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1823:         if (($tstart) && ($tstart<0)) { next; }
                   1824:         if (($tend) && ($tend<$now)) { next; }
                   1825:         if (($tstart) && ($now<$tstart)) { next; }
                   1826:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1827: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1828: 	if ((&privileged($username,$domain)) && 
                   1829: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1830: 	if ($role eq 'cr') { next; }
1.351     www      1831:         my $key=&plaintext($role);
1.656     albertel 1832: 	if ($role =~ /^cr/) {
                   1833: 	    $key=(split('/',$role))[3];
                   1834: 	}
1.351     www      1835:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1836:         if ($returnhash{$key}) {
                   1837: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1838:         } else {
                   1839:             $returnhash{$key}=$username.':'.$domain;
                   1840:         }
1.400     www      1841:      }
                   1842:     return %returnhash;
                   1843: }
                   1844: 
                   1845: sub get_my_roles {
                   1846:     my ($uname,$udom)=@_;
1.620     albertel 1847:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1848:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1849:     my %dumphash=
                   1850:             &dump('nohist_userroles',$udom,$uname);
                   1851:     my %returnhash=();
                   1852:     my $now=time;
                   1853:     foreach (keys %dumphash) {
                   1854: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1855:         if (($tstart) && ($tstart<0)) { next; }
                   1856:         if (($tend) && ($tend<$now)) { next; }
                   1857:         if (($tstart) && ($now<$tstart)) { next; }
                   1858:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1859: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1860:      }
                   1861:     return %returnhash;
1.399     www      1862: }
                   1863: 
                   1864: # ----------------------------------------------------- Frontpage Announcements
                   1865: #
                   1866: #
                   1867: 
                   1868: sub postannounce {
                   1869:     my ($server,$text)=@_;
                   1870:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1871:     unless ($text=~/\w/) { $text=''; }
                   1872:     return &reply('setannounce:'.&escape($text),$server);
                   1873: }
                   1874: 
                   1875: sub getannounce {
1.448     albertel 1876: 
                   1877:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1878: 	my $announcement='';
                   1879: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1880: 	close($fh);
1.399     www      1881: 	if ($announcement=~/\w/) { 
                   1882: 	    return 
                   1883:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1884:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1885: 	} else {
                   1886: 	    return '';
                   1887: 	}
                   1888:     } else {
                   1889: 	return '';
                   1890:     }
1.351     www      1891: }
1.353     www      1892: 
                   1893: # ---------------------------------------------------------- Course ID routines
                   1894: # Deal with domain's nohist_courseid.db files
                   1895: #
                   1896: 
                   1897: sub courseidput {
                   1898:     my ($domain,$what,$coursehome)=@_;
                   1899:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1900: }
                   1901: 
                   1902: sub courseiddump {
1.622     raeburn  1903:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353     www      1904:     my %returnhash=();
1.355     www      1905:     unless ($domfilter) { $domfilter=''; }
1.353     www      1906:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1907:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1908: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1909: 	        foreach (
                   1910:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1911: 			       $sincefilter.':'.&escape($descfilter).':'.
1.622     raeburn  1912:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354     www      1913:                                $tryserver))) {
1.506     raeburn  1914: 		    my ($key,$value)=split(/\=/,$_);
                   1915:                     if (($key) && ($value)) {
1.516     raeburn  1916: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1917:                     }
1.353     www      1918:                 }
                   1919:             }
                   1920:         }
                   1921:     }
                   1922:     return %returnhash;
                   1923: }
                   1924: 
1.658     raeburn  1925: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1926: 
                   1927: sub dcmailput {
1.685     raeburn  1928:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1929:     my $status = &Apache::lonnet::critical(
                   1930:        'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='.
1.685     raeburn  1931:        &Apache::lonnet::escape($message),$server);
1.662     raeburn  1932:     return $status;
                   1933: }
                   1934: 
1.658     raeburn  1935: sub dcmaildump {
                   1936:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1937:     my %returnhash=();
                   1938:     if (exists($domain_primary{$dom})) {
                   1939:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1940:                                                          &escape($enddate).':';
                   1941: 	my @esc_senders=map { &escape($_)} @$senders;
                   1942: 	$cmd.=&escape(join('&',@esc_senders));
                   1943: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1944:             my ($key,$value) = split(/\=/,$_);
                   1945:             if (($key) && ($value)) {
                   1946:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  1947:             }
                   1948:         }
                   1949:     }
                   1950:     return %returnhash;
                   1951: }
1.662     raeburn  1952: # ---------------------------------------------------------- Domain roles
                   1953: 
                   1954: sub get_domain_roles {
                   1955:     my ($dom,$roles,$startdate,$enddate)=@_;
                   1956:     if (undef($startdate) || $startdate eq '') {
                   1957:         $startdate = '.';
                   1958:     }
                   1959:     if (undef($enddate) || $enddate eq '') {
                   1960:         $enddate = '.';
                   1961:     }
                   1962:     my $rolelist = join(':',@{$roles});
                   1963:     my %personnel = ();
                   1964:     foreach my $tryserver (keys(%libserv)) {
                   1965:         if ($hostdom{$tryserver} eq $dom) {
                   1966:             %{$personnel{$tryserver}}=();
                   1967:             foreach (
                   1968:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   1969:                    &escape($startdate).':'.&escape($enddate).':'.
                   1970:                    &escape($rolelist), $tryserver))) {
                   1971:                 my($key,$value) = split(/\=/,$_);
                   1972:                 if (($key) && ($value)) {
                   1973:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   1974:                 }
                   1975:             }
                   1976:         }
                   1977:     }
                   1978:     return %personnel;
                   1979: }
1.658     raeburn  1980: 
1.149     www      1981: # ----------------------------------------------------------- Check out an item
                   1982: 
1.504     albertel 1983: sub get_first_access {
                   1984:     my ($type,$argsymb)=@_;
                   1985:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   1986:     if ($argsymb) { $symb=$argsymb; }
                   1987:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 1988:     if ($type eq 'map') {
                   1989: 	$res=&symbread($map);
                   1990:     } else {
                   1991: 	$res=$symb;
                   1992:     }
                   1993:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   1994:     return $times{"$courseid\0$res"};
1.504     albertel 1995: }
                   1996: 
                   1997: sub set_first_access {
                   1998:     my ($type)=@_;
                   1999:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2000:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2001:     if ($type eq 'map') {
                   2002: 	$res=&symbread($map);
                   2003:     } else {
                   2004: 	$res=$symb;
                   2005:     }
                   2006:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2007:     if (!$firstaccess) {
1.588     albertel 2008: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2009:     }
                   2010:     return 'already_set';
1.504     albertel 2011: }
                   2012: 
1.149     www      2013: sub checkout {
                   2014:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2015:     my $now=time;
                   2016:     my $lonhost=$perlvar{'lonHostID'};
                   2017:     my $infostr=&escape(
1.234     www      2018:                  'CHECKOUTTOKEN&'.
1.149     www      2019:                  $tuname.'&'.
                   2020:                  $tudom.'&'.
                   2021:                  $tcrsid.'&'.
                   2022:                  $symb.'&'.
                   2023: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2024:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2025:     if ($token=~/^error\:/) { 
1.672     albertel 2026:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2027:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2028:                  "</font>");
                   2029:         return ''; 
                   2030:     }
                   2031: 
1.149     www      2032:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2033:     $token=~tr/a-z/A-Z/;
                   2034: 
1.153     www      2035:     my %infohash=('resource.0.outtoken' => $token,
                   2036:                   'resource.0.checkouttime' => $now,
                   2037:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2038: 
                   2039:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2040:        return '';
1.151     www      2041:     } else {
1.672     albertel 2042:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2043:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2044:                  "</font>");
1.149     www      2045:     }    
                   2046: 
                   2047:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2048:                          &escape('Checkout '.$infostr.' - '.
                   2049:                                                  $token)) ne 'ok') {
                   2050: 	return '';
1.151     www      2051:     } else {
1.672     albertel 2052:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2053:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2054:                  "</font>");
1.149     www      2055:     }
1.151     www      2056:     return $token;
1.149     www      2057: }
                   2058: 
                   2059: # ------------------------------------------------------------ Check in an item
                   2060: 
                   2061: sub checkin {
                   2062:     my $token=shift;
1.150     www      2063:     my $now=time;
                   2064:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2065:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2066:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2067:     $dtoken=~s/\W/\_/g;
1.234     www      2068:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2069:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2070: 
1.154     www      2071:     unless (($tuname) && ($tudom)) {
                   2072:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2073:         return '';
                   2074:     }
                   2075:     
                   2076:     unless (&allowed('mgr',$tcrsid)) {
                   2077:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2078:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2079:         return '';
                   2080:     }
                   2081: 
1.153     www      2082:     my %infohash=('resource.0.intoken' => $token,
                   2083:                   'resource.0.checkintime' => $now,
                   2084:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2085: 
                   2086:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2087:        return '';
                   2088:     }    
                   2089: 
                   2090:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2091:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2092: 	return '';
                   2093:     }
                   2094: 
                   2095:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2096: }
                   2097: 
                   2098: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2099: 
                   2100: sub expirespread {
                   2101:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2102:     my $cid=$env{'request.course.id'}; 
1.110     www      2103:     if ($cid) {
                   2104:        my $now=time;
                   2105:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2106:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2107:                             $env{'course.'.$cid.'.num'}.
1.110     www      2108: 	        	    ':nohist_expirationdates:'.
                   2109:                             &escape($key).'='.$now,
1.620     albertel 2110:                             $env{'course.'.$cid.'.home'})
1.110     www      2111:     }
                   2112:     return 'ok';
1.14      www      2113: }
                   2114: 
1.109     www      2115: # ----------------------------------------------------- Devalidate Spreadsheets
                   2116: 
                   2117: sub devalidate {
1.325     www      2118:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2119:     my $cid=$env{'request.course.id'}; 
1.109     www      2120:     if ($cid) {
1.391     matthew  2121:         # delete the stored spreadsheets for
                   2122:         # - the student level sheet of this user in course's homespace
                   2123:         # - the assessment level sheet for this resource 
                   2124:         #   for this user in user's homespace
1.553     albertel 2125: 	# - current conditional state info
1.325     www      2126: 	my $key=$uname.':'.$udom.':';
1.109     www      2127:         my $status=
1.299     matthew  2128: 	    &del('nohist_calculatedsheets',
1.391     matthew  2129: 		 [$key.'studentcalc:'],
1.620     albertel 2130: 		 $env{'course.'.$cid.'.domain'},
                   2131: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2132: 		.' '.
                   2133: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2134: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2135:         unless ($status eq 'ok ok') {
                   2136:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2137:                     $uname.' at '.$udom.' for '.
1.109     www      2138: 		    $symb.': '.$status);
1.133     albertel 2139:         }
1.553     albertel 2140: 	&delenv('user.state.'.$cid);
1.109     www      2141:     }
                   2142: }
                   2143: 
1.265     albertel 2144: sub get_scalar {
                   2145:     my ($string,$end) = @_;
                   2146:     my $value;
                   2147:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2148: 	$value = $1;
                   2149:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2150: 	$value = $1;
                   2151:     }
                   2152:     return &unescape($value);
                   2153: }
                   2154: 
                   2155: sub array2str {
                   2156:   my (@array) = @_;
                   2157:   my $result=&arrayref2str(\@array);
                   2158:   $result=~s/^__ARRAY_REF__//;
                   2159:   $result=~s/__END_ARRAY_REF__$//;
                   2160:   return $result;
                   2161: }
                   2162: 
1.204     albertel 2163: sub arrayref2str {
                   2164:   my ($arrayref) = @_;
1.265     albertel 2165:   my $result='__ARRAY_REF__';
1.204     albertel 2166:   foreach my $elem (@$arrayref) {
1.265     albertel 2167:     if(ref($elem) eq 'ARRAY') {
                   2168:       $result.=&arrayref2str($elem).'&';
                   2169:     } elsif(ref($elem) eq 'HASH') {
                   2170:       $result.=&hashref2str($elem).'&';
                   2171:     } elsif(ref($elem)) {
                   2172:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2173:     } else {
                   2174:       $result.=&escape($elem).'&';
                   2175:     }
                   2176:   }
                   2177:   $result=~s/\&$//;
1.265     albertel 2178:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2179:   return $result;
                   2180: }
                   2181: 
1.168     albertel 2182: sub hash2str {
1.204     albertel 2183:   my (%hash) = @_;
                   2184:   my $result=&hashref2str(\%hash);
1.265     albertel 2185:   $result=~s/^__HASH_REF__//;
                   2186:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2187:   return $result;
                   2188: }
                   2189: 
                   2190: sub hashref2str {
                   2191:   my ($hashref)=@_;
1.265     albertel 2192:   my $result='__HASH_REF__';
1.495     albertel 2193:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2194:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2195:       $result.=&arrayref2str($_).'=';
1.204     albertel 2196:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2197:       $result.=&hashref2str($_).'=';
1.204     albertel 2198:     } elsif (ref($_)) {
1.265     albertel 2199:       $result.='=';
                   2200:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2201:     } else {
1.265     albertel 2202: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2203:     }
                   2204: 
1.265     albertel 2205:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2206:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2207:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2208:       $result.=&hashref2str($hashref->{$_}).'&';
                   2209:     } elsif(ref($hashref->{$_})) {
                   2210:        $result.='&';
                   2211:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2212:     } else {
1.265     albertel 2213:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2214:     }
                   2215:   }
1.168     albertel 2216:   $result=~s/\&$//;
1.265     albertel 2217:   $result .= '__END_HASH_REF__';
1.168     albertel 2218:   return $result;
                   2219: }
                   2220: 
                   2221: sub str2hash {
1.265     albertel 2222:     my ($string)=@_;
                   2223:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2224:     return %$hash;
                   2225: }
                   2226: 
                   2227: sub str2hashref {
1.168     albertel 2228:   my ($string) = @_;
1.265     albertel 2229: 
                   2230:   my %hash;
                   2231: 
                   2232:   if($string !~ /^__HASH_REF__/) {
                   2233:       if (! ($string eq '' || !defined($string))) {
                   2234: 	  $hash{'error'}='Not hash reference';
                   2235:       }
                   2236:       return (\%hash, $string);
                   2237:   }
                   2238: 
                   2239:   $string =~ s/^__HASH_REF__//;
                   2240: 
                   2241:   while($string !~ /^__END_HASH_REF__/) {
                   2242:       #key
                   2243:       my $key='';
                   2244:       if($string =~ /^__HASH_REF__/) {
                   2245:           ($key, $string)=&str2hashref($string);
                   2246:           if(defined($key->{'error'})) {
                   2247:               $hash{'error'}='Bad data';
                   2248:               return (\%hash, $string);
                   2249:           }
                   2250:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2251:           ($key, $string)=&str2arrayref($string);
                   2252:           if($key->[0] eq 'Array reference error') {
                   2253:               $hash{'error'}='Bad data';
                   2254:               return (\%hash, $string);
                   2255:           }
                   2256:       } else {
                   2257:           $string =~ s/^(.*?)=//;
1.267     albertel 2258: 	  $key=&unescape($1);
1.265     albertel 2259:       }
                   2260:       $string =~ s/^=//;
                   2261: 
                   2262:       #value
                   2263:       my $value='';
                   2264:       if($string =~ /^__HASH_REF__/) {
                   2265:           ($value, $string)=&str2hashref($string);
                   2266:           if(defined($value->{'error'})) {
                   2267:               $hash{'error'}='Bad data';
                   2268:               return (\%hash, $string);
                   2269:           }
                   2270:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2271:           ($value, $string)=&str2arrayref($string);
                   2272:           if($value->[0] eq 'Array reference error') {
                   2273:               $hash{'error'}='Bad data';
                   2274:               return (\%hash, $string);
                   2275:           }
                   2276:       } else {
                   2277: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2278:       }
                   2279:       $string =~ s/^&//;
                   2280: 
                   2281:       $hash{$key}=$value;
1.204     albertel 2282:   }
1.265     albertel 2283: 
                   2284:   $string =~ s/^__END_HASH_REF__//;
                   2285: 
                   2286:   return (\%hash, $string);
1.204     albertel 2287: }
                   2288: 
                   2289: sub str2array {
1.265     albertel 2290:     my ($string)=@_;
                   2291:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2292:     return @$array;
                   2293: }
                   2294: 
                   2295: sub str2arrayref {
1.204     albertel 2296:   my ($string) = @_;
1.265     albertel 2297:   my @array;
                   2298: 
                   2299:   if($string !~ /^__ARRAY_REF__/) {
                   2300:       if (! ($string eq '' || !defined($string))) {
                   2301: 	  $array[0]='Array reference error';
                   2302:       }
                   2303:       return (\@array, $string);
                   2304:   }
                   2305: 
                   2306:   $string =~ s/^__ARRAY_REF__//;
                   2307: 
                   2308:   while($string !~ /^__END_ARRAY_REF__/) {
                   2309:       my $value='';
                   2310:       if($string =~ /^__HASH_REF__/) {
                   2311:           ($value, $string)=&str2hashref($string);
                   2312:           if(defined($value->{'error'})) {
                   2313:               $array[0] ='Array reference error';
                   2314:               return (\@array, $string);
                   2315:           }
                   2316:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2317:           ($value, $string)=&str2arrayref($string);
                   2318:           if($value->[0] eq 'Array reference error') {
                   2319:               $array[0] ='Array reference error';
                   2320:               return (\@array, $string);
                   2321:           }
                   2322:       } else {
                   2323: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2324:       }
                   2325:       $string =~ s/^&//;
                   2326: 
                   2327:       push(@array, $value);
1.191     harris41 2328:   }
1.265     albertel 2329: 
                   2330:   $string =~ s/^__END_ARRAY_REF__//;
                   2331: 
                   2332:   return (\@array, $string);
1.168     albertel 2333: }
                   2334: 
1.167     albertel 2335: # -------------------------------------------------------------------Temp Store
                   2336: 
1.168     albertel 2337: sub tmpreset {
                   2338:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2339:   if (!$symb) {
                   2340:     $symb=&symbread();
1.620     albertel 2341:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2342:   }
                   2343:   $symb=escape($symb);
                   2344: 
1.620     albertel 2345:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2346:   $namespace=~s/\//\_/g;
                   2347:   $namespace=~s/\W//g;
                   2348: 
1.620     albertel 2349:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2350:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2351:   if ($domain eq 'public' && $stuname eq 'public') {
                   2352:       $stuname=$ENV{'REMOTE_ADDR'};
                   2353:   }
1.168     albertel 2354:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2355:   my %hash;
                   2356:   if (tie(%hash,'GDBM_File',
                   2357: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2358: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2359:     foreach my $key (keys %hash) {
1.180     albertel 2360:       if ($key=~ /:$symb/) {
1.168     albertel 2361: 	delete($hash{$key});
                   2362:       }
                   2363:     }
                   2364:   }
                   2365: }
                   2366: 
1.167     albertel 2367: sub tmpstore {
1.168     albertel 2368:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2369: 
                   2370:   if (!$symb) {
                   2371:     $symb=&symbread();
1.620     albertel 2372:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2373:   }
                   2374:   $symb=escape($symb);
                   2375: 
                   2376:   if (!$namespace) {
                   2377:     # I don't think we would ever want to store this for a course.
                   2378:     # it seems this will only be used if we don't have a course.
1.620     albertel 2379:     #$namespace=$env{'request.course.id'};
1.168     albertel 2380:     #if (!$namespace) {
1.620     albertel 2381:       $namespace=$env{'request.state'};
1.168     albertel 2382:     #}
                   2383:   }
                   2384:   $namespace=~s/\//\_/g;
                   2385:   $namespace=~s/\W//g;
1.620     albertel 2386:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2387:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2388:   if ($domain eq 'public' && $stuname eq 'public') {
                   2389:       $stuname=$ENV{'REMOTE_ADDR'};
                   2390:   }
1.168     albertel 2391:   my $now=time;
                   2392:   my %hash;
                   2393:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2394:   if (tie(%hash,'GDBM_File',
                   2395: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2396: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2397:     $hash{"version:$symb"}++;
                   2398:     my $version=$hash{"version:$symb"};
                   2399:     my $allkeys=''; 
                   2400:     foreach my $key (keys(%$storehash)) {
                   2401:       $allkeys.=$key.':';
1.591     albertel 2402:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2403:     }
                   2404:     $hash{"$version:$symb:timestamp"}=$now;
                   2405:     $allkeys.='timestamp';
                   2406:     $hash{"$version:keys:$symb"}=$allkeys;
                   2407:     if (untie(%hash)) {
                   2408:       return 'ok';
                   2409:     } else {
                   2410:       return "error:$!";
                   2411:     }
                   2412:   } else {
                   2413:     return "error:$!";
                   2414:   }
                   2415: }
1.167     albertel 2416: 
1.168     albertel 2417: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2418: 
1.168     albertel 2419: sub tmprestore {
                   2420:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2421: 
1.168     albertel 2422:   if (!$symb) {
                   2423:     $symb=&symbread();
1.620     albertel 2424:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2425:   }
                   2426:   $symb=escape($symb);
                   2427: 
1.620     albertel 2428:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2429: 
1.620     albertel 2430:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2431:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2432:   if ($domain eq 'public' && $stuname eq 'public') {
                   2433:       $stuname=$ENV{'REMOTE_ADDR'};
                   2434:   }
1.168     albertel 2435:   my %returnhash;
                   2436:   $namespace=~s/\//\_/g;
                   2437:   $namespace=~s/\W//g;
                   2438:   my %hash;
                   2439:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2440:   if (tie(%hash,'GDBM_File',
                   2441: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2442: 	  &GDBM_READER(),0640)) {
1.168     albertel 2443:     my $version=$hash{"version:$symb"};
                   2444:     $returnhash{'version'}=$version;
                   2445:     my $scope;
                   2446:     for ($scope=1;$scope<=$version;$scope++) {
                   2447:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2448:       my @keys=split(/:/,$vkeys);
                   2449:       my $key;
                   2450:       $returnhash{"$scope:keys"}=$vkeys;
                   2451:       foreach $key (@keys) {
1.591     albertel 2452: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2453: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2454:       }
                   2455:     }
1.168     albertel 2456:     if (!(untie(%hash))) {
                   2457:       return "error:$!";
                   2458:     }
                   2459:   } else {
                   2460:     return "error:$!";
                   2461:   }
                   2462:   return %returnhash;
1.167     albertel 2463: }
                   2464: 
1.9       www      2465: # ----------------------------------------------------------------------- Store
                   2466: 
                   2467: sub store {
1.124     www      2468:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2469:     my $home='';
                   2470: 
1.168     albertel 2471:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2472: 
1.213     www      2473:     $symb=&symbclean($symb);
1.122     albertel 2474:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2475: 
1.620     albertel 2476:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2477:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2478: 
                   2479:     &devalidate($symb,$stuname,$domain);
1.109     www      2480: 
                   2481:     $symb=escape($symb);
1.187     www      2482:     if (!$namespace) { 
1.620     albertel 2483:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2484:           return ''; 
                   2485:        } 
                   2486:     }
1.620     albertel 2487:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2488: 
                   2489:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2490:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2491: 
1.12      www      2492:     my $namevalue='';
1.191     harris41 2493:     foreach (keys %$storehash) {
1.591     albertel 2494:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2495:     }
1.12      www      2496:     $namevalue=~s/\&$//;
1.187     www      2497:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2498:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2499: }
                   2500: 
1.47      www      2501: # -------------------------------------------------------------- Critical Store
                   2502: 
                   2503: sub cstore {
1.124     www      2504:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2505:     my $home='';
                   2506: 
1.168     albertel 2507:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2508: 
1.213     www      2509:     $symb=&symbclean($symb);
1.122     albertel 2510:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2511: 
1.620     albertel 2512:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2513:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2514: 
                   2515:     &devalidate($symb,$stuname,$domain);
1.109     www      2516: 
                   2517:     $symb=escape($symb);
1.187     www      2518:     if (!$namespace) { 
1.620     albertel 2519:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2520:           return ''; 
                   2521:        } 
                   2522:     }
1.620     albertel 2523:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2524: 
                   2525:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2526:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2527: 
1.47      www      2528:     my $namevalue='';
1.191     harris41 2529:     foreach (keys %$storehash) {
1.591     albertel 2530:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2531:     }
1.47      www      2532:     $namevalue=~s/\&$//;
1.187     www      2533:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2534:     return critical
                   2535:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2536: }
                   2537: 
1.9       www      2538: # --------------------------------------------------------------------- Restore
                   2539: 
                   2540: sub restore {
1.124     www      2541:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2542:     my $home='';
                   2543: 
1.168     albertel 2544:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2545: 
1.122     albertel 2546:     if (!$symb) {
                   2547:       unless ($symb=escape(&symbread())) { return ''; }
                   2548:     } else {
1.213     www      2549:       $symb=&escape(&symbclean($symb));
1.122     albertel 2550:     }
1.188     www      2551:     if (!$namespace) { 
1.620     albertel 2552:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2553:           return ''; 
                   2554:        } 
                   2555:     }
1.620     albertel 2556:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2557:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2558:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2559:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2560: 
1.12      www      2561:     my %returnhash=();
1.191     harris41 2562:     foreach (split(/\&/,$answer)) {
1.12      www      2563: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2564:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2565:     }
1.75      www      2566:     my $version;
                   2567:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2568:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2569:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2570:        }
1.75      www      2571:     }
1.13      www      2572:     return %returnhash;
1.34      www      2573: }
                   2574: 
                   2575: # ---------------------------------------------------------- Course Description
                   2576: 
                   2577: sub coursedescription {
                   2578:     my $courseid=shift;
                   2579:     $courseid=~s/^\///;
1.49      www      2580:     $courseid=~s/\_/\//g;
1.34      www      2581:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2582:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2583:     my $normalid=$cdomain.'_'.$cnum;
                   2584:     # need to always cache even if we get errors otherwise we keep 
                   2585:     # trying and trying and trying to get the course description.
                   2586:     my %envhash=();
                   2587:     my %returnhash=();
                   2588:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      2589:     if ($chome ne 'no_host') {
1.302     albertel 2590:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2591:        if (!exists($returnhash{'con_lost'})) {
                   2592:            $returnhash{'home'}= $chome;
                   2593: 	   $returnhash{'domain'} = $cdomain;
                   2594: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2595:            while (my ($name,$value) = each %returnhash) {
1.53      www      2596:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2597:            }
1.270     www      2598:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2599:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2600: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2601:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2602:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2603:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2604:        }
                   2605:     }
1.302     albertel 2606:     &appenv(%envhash);
                   2607:     return %returnhash;
1.461     www      2608: }
                   2609: 
                   2610: # -------------------------------------------------See if a user is privileged
                   2611: 
                   2612: sub privileged {
                   2613:     my ($username,$domain)=@_;
                   2614:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2615: 			&homeserver($username,$domain));
                   2616:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2617:     my $now=time;
                   2618:     if ($rolesdump ne '') {
                   2619:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2620: 	    if ($_!~/^rolesdef_/) {
1.461     www      2621: 		my ($area,$role)=split(/=/,$_);
                   2622: 		$area=~s/\_\w\w$//;
                   2623: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2624: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2625: 		    my $active=1;
                   2626: 		    if ($tend) {
                   2627: 			if ($tend<$now) { $active=0; }
                   2628: 		    }
                   2629: 		    if ($tstart) {
                   2630: 			if ($tstart>$now) { $active=0; }
                   2631: 		    }
                   2632: 		    if ($active) { return 1; }
                   2633: 		}
                   2634: 	    }
                   2635: 	}
                   2636:     }
                   2637:     return 0;
1.9       www      2638: }
1.1       albertel 2639: 
1.103     harris41 2640: # -------------------------------------------------------- Get user privileges
1.11      www      2641: 
                   2642: sub rolesinit {
                   2643:     my ($domain,$username,$authhost)=@_;
                   2644:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2645:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2646:     my %allroles=();
1.678     raeburn  2647:     my %allgroups=();   
1.11      www      2648:     my $now=time;
1.21      www      2649:     my $userroles="user.login.time=$now\n";
1.678     raeburn  2650:     my $group_privs;
1.11      www      2651: 
                   2652:     if ($rolesdump ne '') {
1.191     harris41 2653:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2654: 	  if ($_!~/^rolesdef_/) {
1.11      www      2655:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2656: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2657:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2658: 	    if ($role=~/^cr/) { 
1.655     albertel 2659: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2660: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2661: 		    ($tend,$tstart)=split('_',$trest);
                   2662: 		} else {
                   2663: 		    $trole=$role;
                   2664: 		}
1.678     raeburn  2665:             } elsif ($role =~ m|^gr/|) {
                   2666:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2667:                 ($trole,$group_privs) = split(/\//,$trole);
                   2668:                 $group_privs = &unescape($group_privs);
1.587     albertel 2669: 	    } else {
                   2670: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2671: 	    }
1.576     albertel 2672:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567     raeburn  2673:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2674:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2675:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2676: 		my $spec=$trole.'.'.$area;
                   2677: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2678: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2679:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2680:                 } elsif ($trole eq 'gr') {
                   2681:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2682: 		} else {
1.567     raeburn  2683:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2684: 		}
1.12      www      2685:             }
1.662     raeburn  2686:           }
1.191     harris41 2687:         }
1.678     raeburn  2688:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
1.128     www      2689:         $userroles.='user.adv='.$adv."\n".
                   2690: 	            'user.author='.$author."\n";
1.620     albertel 2691:         $env{'user.adv'}=$adv;
1.11      www      2692:     }
                   2693:     return $userroles;  
                   2694: }
                   2695: 
1.567     raeburn  2696: sub set_arearole {
                   2697:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2698: # log the associated role with the area
                   2699:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   2700:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
                   2701: }
                   2702: 
                   2703: sub custom_roleprivs {
                   2704:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2705:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2706:     my $homsvr=homeserver($rauthor,$rdomain);
                   2707:     if ($hostname{$homsvr} ne '') {
                   2708:         my ($rdummy,$roledef)=
                   2709:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2710:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2711:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2712:             if (defined($syspriv)) {
                   2713:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2714:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2715:             }
                   2716:             if ($tdomain ne '') {
                   2717:                 if (defined($dompriv)) {
                   2718:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2719:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2720:                 }
                   2721:                 if (($trest ne '') && (defined($coursepriv))) {
                   2722:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2723:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2724:                 }
                   2725:             }
                   2726:         }
                   2727:     }
                   2728: }
                   2729: 
1.678     raeburn  2730: sub group_roleprivs {
                   2731:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2732:     my $access = 1;
                   2733:     my $now = time;
                   2734:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2735:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2736:     if ($access) {
                   2737:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2738:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2739:     }
                   2740: }
1.567     raeburn  2741: 
                   2742: sub standard_roleprivs {
                   2743:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2744:     if (defined($pr{$trole.':s'})) {
                   2745:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2746:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2747:     }
                   2748:     if ($tdomain ne '') {
                   2749:         if (defined($pr{$trole.':d'})) {
                   2750:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2751:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2752:         }
                   2753:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2754:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2755:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2756:         }
                   2757:     }
                   2758: }
                   2759: 
                   2760: sub set_userprivs {
1.678     raeburn  2761:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2762:     my $author=0;
                   2763:     my $adv=0;
1.678     raeburn  2764:     my %grouproles = ();
                   2765:     if (keys(%{$allgroups}) > 0) {
                   2766:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2767:             my ($trole,$area,$sec,$extendedarea);
                   2768:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2769:                 $trole = $1;
                   2770:                 $area = $2;
1.681     raeburn  2771:                 $sec = $3;
                   2772:                 $extendedarea = $area.$sec;
                   2773:                 if (exists($$allgroups{$area})) {
                   2774:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2775:                         my $spec = $trole.'.'.$extendedarea;
                   2776:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2777:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2778:                     }
                   2779:                 }
                   2780:             }
                   2781:         }
                   2782:     }
                   2783:     foreach (keys(%grouproles)) {
                   2784:         $$allroles{$_} = $grouproles{$_};
                   2785:     }
1.567     raeburn  2786:     foreach (keys %{$allroles}) {
                   2787:         my %thesepriv=();
                   2788:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2789:         foreach (split(/:/,$$allroles{$_})) {
                   2790:             if ($_ ne '') {
                   2791:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2792:                 if ($restrictions eq '') {
                   2793:                     $thesepriv{$privilege}='F';
                   2794:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2795:                     $thesepriv{$privilege}.=$restrictions;
                   2796:                 }
                   2797:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2798:             }
                   2799:         }
                   2800:         my $thesestr='';
                   2801:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
                   2802:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
                   2803:     }
                   2804:     return ($author,$adv);
                   2805: }
                   2806: 
1.12      www      2807: # --------------------------------------------------------------- get interface
                   2808: 
                   2809: sub get {
1.131     albertel 2810:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2811:    my $items='';
1.191     harris41 2812:    foreach (@$storearr) {
1.12      www      2813:        $items.=escape($_).'&';
1.191     harris41 2814:    }
1.12      www      2815:    $items=~s/\&$//;
1.620     albertel 2816:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2817:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2818:    my $uhome=&homeserver($uname,$udomain);
                   2819: 
1.133     albertel 2820:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2821:    my @pairs=split(/\&/,$rep);
1.273     albertel 2822:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2823:      return @pairs;
                   2824:    }
1.15      www      2825:    my %returnhash=();
1.42      www      2826:    my $i=0;
1.191     harris41 2827:    foreach (@$storearr) {
1.557     albertel 2828:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2829:       $i++;
1.191     harris41 2830:    }
1.15      www      2831:    return %returnhash;
1.27      www      2832: }
                   2833: 
                   2834: # --------------------------------------------------------------- del interface
                   2835: 
                   2836: sub del {
1.133     albertel 2837:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2838:    my $items='';
1.191     harris41 2839:    foreach (@$storearr) {
1.27      www      2840:        $items.=escape($_).'&';
1.191     harris41 2841:    }
1.27      www      2842:    $items=~s/\&$//;
1.620     albertel 2843:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2844:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2845:    my $uhome=&homeserver($uname,$udomain);
                   2846: 
                   2847:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2848: }
                   2849: 
                   2850: # -------------------------------------------------------------- dump interface
                   2851: 
                   2852: sub dump {
1.702     albertel 2853:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.620     albertel 2854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2855:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2856:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2857:    if ($regexp) {
                   2858:        $regexp=&escape($regexp);
                   2859:    } else {
                   2860:        $regexp='.';
                   2861:    }
1.702     albertel 2862:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.12      www      2863:    my @pairs=split(/\&/,$rep);
                   2864:    my %returnhash=();
1.191     harris41 2865:    foreach (@pairs) {
1.702     albertel 2866:       my ($key,$value)=split(/=/,$_,2);
1.557     albertel 2867:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2868:    }
                   2869:    return %returnhash;
1.407     www      2870: }
                   2871: 
1.717     albertel 2872: # --------------------------------------------------------- dumpstore interface
                   2873: 
                   2874: sub dumpstore {
                   2875:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2876:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2877: }
                   2878: 
1.407     www      2879: # -------------------------------------------------------------- keys interface
                   2880: 
                   2881: sub getkeys {
                   2882:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2883:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2884:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2885:    my $uhome=&homeserver($uname,$udomain);
                   2886:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2887:    my @keyarray=();
                   2888:    foreach (split(/\&/,$rep)) {
                   2889:       push (@keyarray,&unescape($_));
                   2890:    }
                   2891:    return @keyarray;
1.318     matthew  2892: }
                   2893: 
1.319     matthew  2894: # --------------------------------------------------------------- currentdump
                   2895: sub currentdump {
1.328     matthew  2896:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2897:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2898:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2899:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2900:    my $uhome = &homeserver($sname,$sdom);
                   2901:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2902:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2903:    #
1.318     matthew  2904:    my %returnhash=();
1.319     matthew  2905:    #
                   2906:    if ($rep eq "unknown_cmd") { 
                   2907:        # an old lond will not know currentdump
                   2908:        # Do a dump and make it look like a currentdump
1.326     matthew  2909:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2910:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2911:        my %hash = @tmp;
                   2912:        @tmp=();
1.424     matthew  2913:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2914:    } else {
                   2915:        my @pairs=split(/\&/,$rep);
                   2916:        foreach (@pairs) {
                   2917:            my ($key,$value)=split(/=/,$_);
                   2918:            my ($symb,$param) = split(/:/,$key);
                   2919:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2920:                                                         &thaw_unescape($value);
1.319     matthew  2921:        }
1.191     harris41 2922:    }
1.12      www      2923:    return %returnhash;
1.424     matthew  2924: }
                   2925: 
                   2926: sub convert_dump_to_currentdump{
                   2927:     my %hash = %{shift()};
                   2928:     my %returnhash;
                   2929:     # Code ripped from lond, essentially.  The only difference
                   2930:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2931:     # we might run in to problems with parameter names =~ /^v\./
                   2932:     while (my ($key,$value) = each(%hash)) {
                   2933:         my ($v,$symb,$param) = split(/:/,$key);
                   2934:         next if ($v eq 'version' || $symb eq 'keys');
                   2935:         next if (exists($returnhash{$symb}) &&
                   2936:                  exists($returnhash{$symb}->{$param}) &&
                   2937:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2938:         $returnhash{$symb}->{$param}=$value;
                   2939:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2940:     }
                   2941:     #
                   2942:     # Remove all of the keys in the hashes which keep track of
                   2943:     # the version of the parameter.
                   2944:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2945:         # use a foreach because we are going to delete from the hash.
                   2946:         foreach my $key (keys(%$param_hash)) {
                   2947:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2948:         }
                   2949:     }
                   2950:     return \%returnhash;
1.12      www      2951: }
                   2952: 
1.627     albertel 2953: # ------------------------------------------------------ critical inc interface
                   2954: 
                   2955: sub cinc {
                   2956:     return &inc(@_,'critical');
                   2957: }
                   2958: 
1.449     matthew  2959: # --------------------------------------------------------------- inc interface
                   2960: 
                   2961: sub inc {
1.627     albertel 2962:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 2963:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2964:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  2965:     my $uhome=&homeserver($uname,$udomain);
                   2966:     my $items='';
                   2967:     if (! ref($store)) {
                   2968:         # got a single value, so use that instead
                   2969:         $items = &escape($store).'=&';
                   2970:     } elsif (ref($store) eq 'SCALAR') {
                   2971:         $items = &escape($$store).'=&';        
                   2972:     } elsif (ref($store) eq 'ARRAY') {
                   2973:         $items = join('=&',map {&escape($_);} @{$store});
                   2974:     } elsif (ref($store) eq 'HASH') {
                   2975:         while (my($key,$value) = each(%{$store})) {
                   2976:             $items.= &escape($key).'='.&escape($value).'&';
                   2977:         }
                   2978:     }
                   2979:     $items=~s/\&$//;
1.627     albertel 2980:     if ($critical) {
                   2981: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2982:     } else {
                   2983: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2984:     }
1.449     matthew  2985: }
                   2986: 
1.12      www      2987: # --------------------------------------------------------------- put interface
                   2988: 
                   2989: sub put {
1.134     albertel 2990:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2991:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2992:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 2993:    my $uhome=&homeserver($uname,$udomain);
1.12      www      2994:    my $items='';
1.191     harris41 2995:    foreach (keys %$storehash) {
1.557     albertel 2996:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2997:    }
1.12      www      2998:    $items=~s/\&$//;
1.134     albertel 2999:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3000: }
                   3001: 
1.631     albertel 3002: # ------------------------------------------------------------ newput interface
                   3003: 
                   3004: sub newput {
                   3005:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3006:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3007:    if (!$uname) { $uname=$env{'user.name'}; }
                   3008:    my $uhome=&homeserver($uname,$udomain);
                   3009:    my $items='';
                   3010:    foreach my $key (keys(%$storehash)) {
                   3011:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3012:    }
                   3013:    $items=~s/\&$//;
                   3014:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3015: }
                   3016: 
                   3017: # ---------------------------------------------------------  putstore interface
                   3018: 
1.524     raeburn  3019: sub putstore {
1.715     albertel 3020:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3021:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3022:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3023:    my $uhome=&homeserver($uname,$udomain);
                   3024:    my $items='';
1.715     albertel 3025:    foreach my $key (keys(%$storehash)) {
                   3026:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3027:    }
1.715     albertel 3028:    $items=~s/\&$//;
1.716     albertel 3029:    my $esc_symb=&escape($symb);
                   3030:    my $esc_v=&escape($version);
1.715     albertel 3031:    my $reply =
1.716     albertel 3032:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3033: 	      $uhome);
                   3034:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3035:        # gfall back to way things use to be done
1.715     albertel 3036:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3037: 			    $uname);
1.524     raeburn  3038:    }
1.715     albertel 3039:    return $reply;
                   3040: }
                   3041: 
                   3042: sub old_putstore {
1.716     albertel 3043:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3044:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3045:     if (!$uname) { $uname=$env{'user.name'}; }
                   3046:     my $uhome=&homeserver($uname,$udomain);
                   3047:     my %newstorehash;
                   3048:     foreach (keys %$storehash) {
                   3049: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3050: 	$newstorehash{$key} = $storehash->{$_};
                   3051:     }
                   3052:     my $items='';
                   3053:     my %allitems = ();
                   3054:     foreach (keys %newstorehash) {
                   3055: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3056: 	    my $key = $1.':keys:'.$2;
                   3057: 	    $allitems{$key} .= $3.':';
                   3058: 	}
                   3059: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3060:     }
                   3061:     foreach (keys %allitems) {
                   3062: 	$allitems{$_} =~ s/\:$//;
                   3063: 	$items.= $_.'='.$allitems{$_}.'&';
                   3064:     }
                   3065:     $items=~s/\&$//;
                   3066:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3067: }
                   3068: 
1.47      www      3069: # ------------------------------------------------------ critical put interface
                   3070: 
                   3071: sub cput {
1.134     albertel 3072:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3073:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3074:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3075:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3076:    my $items='';
1.191     harris41 3077:    foreach (keys %$storehash) {
1.715     albertel 3078:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3079:    }
1.47      www      3080:    $items=~s/\&$//;
1.134     albertel 3081:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3082: }
                   3083: 
                   3084: # -------------------------------------------------------------- eget interface
                   3085: 
                   3086: sub eget {
1.133     albertel 3087:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3088:    my $items='';
1.191     harris41 3089:    foreach (@$storearr) {
1.12      www      3090:        $items.=escape($_).'&';
1.191     harris41 3091:    }
1.12      www      3092:    $items=~s/\&$//;
1.620     albertel 3093:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3094:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3095:    my $uhome=&homeserver($uname,$udomain);
                   3096:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3097:    my @pairs=split(/\&/,$rep);
                   3098:    my %returnhash=();
1.42      www      3099:    my $i=0;
1.191     harris41 3100:    foreach (@$storearr) {
1.557     albertel 3101:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3102:       $i++;
1.191     harris41 3103:    }
1.12      www      3104:    return %returnhash;
                   3105: }
                   3106: 
1.667     albertel 3107: # ------------------------------------------------------------ tmpput interface
                   3108: sub tmpput {
                   3109:     my ($storehash,$server)=@_;
                   3110:     my $items='';
                   3111:     foreach (keys(%$storehash)) {
                   3112: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3113:     }
                   3114:     $items=~s/\&$//;
                   3115:     return &reply("tmpput:$items",$server);
                   3116: }
                   3117: 
                   3118: # ------------------------------------------------------------ tmpget interface
                   3119: sub tmpget {
1.688     albertel 3120:     my ($token,$server)=@_;
                   3121:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3122:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3123:     my %returnhash;
                   3124:     foreach my $item (split(/\&/,$rep)) {
                   3125: 	my ($key,$value)=split(/=/,$item);
                   3126: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3127:     }
                   3128:     return %returnhash;
                   3129: }
                   3130: 
1.688     albertel 3131: # ------------------------------------------------------------ tmpget interface
                   3132: sub tmpdel {
                   3133:     my ($token,$server)=@_;
                   3134:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3135:     return &reply("tmpdel:$token",$server);
                   3136: }
                   3137: 
1.341     www      3138: # ---------------------------------------------- Custom access rule evaluation
                   3139: 
                   3140: sub customaccess {
                   3141:     my ($priv,$uri)=@_;
1.620     albertel 3142:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3143:     $urealm=~s/^\W//;
                   3144:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3145:     my $access=0;
                   3146:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3147: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3148:         if ($role) {
                   3149: 	   if ($role ne $urole) { next; }
                   3150:         }
                   3151:         foreach (split(/\s*\,\s*/,$realm)) {
                   3152:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3153:             if ($tdom) {
                   3154: 		if ($tdom ne $udom) { next; }
                   3155:             }
                   3156:             if ($tcrs) {
                   3157: 		if ($tcrs ne $ucrs) { next; }
                   3158:             }
                   3159:             if ($tsec) {
                   3160: 		if ($tsec ne $usec) { next; }
                   3161:             }
                   3162:             $access=($effect eq 'allow');
                   3163:             last;
1.342     www      3164:         }
1.402     bowersj2 3165: 	if ($realm eq '' && $role eq '') {
                   3166:             $access=($effect eq 'allow');
                   3167: 	}
1.341     www      3168:     }
                   3169:     return $access;
                   3170: }
                   3171: 
1.103     harris41 3172: # ------------------------------------------------- Check for a user privilege
1.12      www      3173: 
                   3174: sub allowed {
1.579     albertel 3175:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3176:     my $ver_orguri=$uri;
1.439     www      3177:     $uri=&deversion($uri);
1.152     www      3178:     my $orguri=$uri;
1.52      www      3179:     $uri=&declutter($uri);
1.545     banghart 3180:     
1.620     albertel 3181:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3182: # Free bre access to adm and meta resources
1.529     albertel 3183:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3184: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3185: 	return 'F';
1.159     www      3186:     }
                   3187: 
1.545     banghart 3188: # Free bre access to user's own portfolio contents
1.714     raeburn  3189:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3190:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3191: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3192:         return 'F';
                   3193:     }
                   3194: 
1.714     raeburn  3195: # bre access to group if user has rgf priv for this group and course.
                   3196:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3197:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3198:         if (exists($env{'request.course.id'})) {
                   3199:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3200:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3201:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3202:                 my $courseprivid=$env{'request.course.id'};
                   3203:                 $courseprivid=~s/\_/\//;
                   3204:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3205:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3206:                     return $1; 
                   3207:                 }
                   3208:             }
                   3209:         }
                   3210:     }
                   3211: 
1.159     www      3212: # Free bre to public access
                   3213: 
                   3214:     if ($priv eq 'bre') {
1.238     www      3215:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3216: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3217:            return 'F'; 
                   3218:         }
1.238     www      3219:         if ($copyright eq 'priv') {
                   3220:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3221: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3222: 		return '';
                   3223:             }
                   3224:         }
                   3225:         if ($copyright eq 'domain') {
                   3226:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3227: 	    unless (($env{'user.domain'} eq $1) ||
                   3228:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3229: 		return '';
                   3230:             }
1.262     matthew  3231:         }
1.620     albertel 3232:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3233:             # Library role, so allow browsing of resources in this domain.
                   3234:             return 'F';
1.238     www      3235:         }
1.341     www      3236:         if ($copyright eq 'custom') {
                   3237: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3238:         }
1.14      www      3239:     }
1.264     matthew  3240:     # Domain coordinator is trying to create a course
1.620     albertel 3241:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3242:         # uri is the requested domain in this case.
                   3243:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3244:         # a role of dc for the domain in question.
1.620     albertel 3245:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3246:     }
1.29      www      3247: 
1.52      www      3248:     my $thisallowed='';
                   3249:     my $statecond=0;
                   3250:     my $courseprivid='';
                   3251: 
                   3252: # Course
                   3253: 
1.620     albertel 3254:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3255:        $thisallowed.=$1;
                   3256:     }
1.29      www      3257: 
1.52      www      3258: # Domain
                   3259: 
1.620     albertel 3260:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3261:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3262:        $thisallowed.=$1;
                   3263:     }
1.52      www      3264: 
                   3265: # Course: uri itself is a course
1.66      www      3266:     my $courseuri=$uri;
                   3267:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3268:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3269: 
1.620     albertel 3270:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3271:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3272:        $thisallowed.=$1;
                   3273:     }
1.29      www      3274: 
1.678     raeburn  3275: # Group: uri itself is a group
                   3276:     my $groupuri=$uri;
                   3277:     $groupuri=~s/^([^\/])/\/$1/;
                   3278:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
                   3279:        =~/\Q$priv\E\&([^\:]*)/) {
                   3280:        $thisallowed.=$1;
                   3281:     }
                   3282: 
1.665     albertel 3283: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3284: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3285:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3286: 	$thisallowed='';
1.671     raeburn  3287:         my ($match)=&is_on_map($uri);
                   3288:         if ($match) {
                   3289:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3290:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3291:                 $thisallowed.=$1;
                   3292:             }
                   3293:         } else {
1.705     albertel 3294:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3295:             if ($refuri) {
                   3296:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3297:                     $thisallowed='F';
1.671     raeburn  3298:                 } else {
                   3299:                     $refuri=&declutter($refuri);
                   3300:                     my ($match) = &is_on_map($refuri);
                   3301:                     if ($match) {
                   3302:                         $thisallowed='F';
                   3303:                     }
1.669     raeburn  3304:                 }
1.671     raeburn  3305:             }
                   3306:         }
1.314     www      3307:     }
1.492     albertel 3308: 
1.52      www      3309: # Full access at system, domain or course-wide level? Exit.
1.29      www      3310: 
                   3311:     if ($thisallowed=~/F/) {
                   3312: 	return 'F';
                   3313:     }
                   3314: 
1.52      www      3315: # If this is generating or modifying users, exit with special codes
1.29      www      3316: 
1.643     www      3317:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3318: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3319: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3320: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3321: 	    unless ($auname) { return $thisallowed; }
                   3322: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3323: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3324: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3325: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3326: 	}
1.52      www      3327: 	return $thisallowed;
                   3328:     }
                   3329: #
1.103     harris41 3330: # Gathered so far: system, domain and course wide privileges
1.52      www      3331: #
                   3332: # Course: See if uri or referer is an individual resource that is part of 
                   3333: # the course
                   3334: 
1.620     albertel 3335:     if ($env{'request.course.id'}) {
1.232     www      3336: 
1.620     albertel 3337:        $courseprivid=$env{'request.course.id'};
                   3338:        if ($env{'request.course.sec'}) {
                   3339:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3340:        }
                   3341:        $courseprivid=~s/\_/\//;
                   3342:        my $checkreferer=1;
1.232     www      3343:        my ($match,$cond)=&is_on_map($uri);
                   3344:        if ($match) {
                   3345:            $statecond=$cond;
1.620     albertel 3346:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3347:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3348:                $thisallowed.=$1;
                   3349:                $checkreferer=0;
                   3350:            }
1.29      www      3351:        }
1.83      www      3352:        
1.148     www      3353:        if ($checkreferer) {
1.620     albertel 3354: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3355:             unless ($refuri) {
1.620     albertel 3356:                 foreach (keys %env) {
1.148     www      3357: 		    if ($_=~/^httpref\..*\*/) {
                   3358: 			my $pattern=$_;
1.156     www      3359:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3360:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3361:                         $pattern=~s/\//\\\//g;
1.152     www      3362:                         if ($orguri=~/$pattern/) {
1.620     albertel 3363: 			    $refuri=$env{$_};
1.148     www      3364:                         }
                   3365:                     }
1.191     harris41 3366:                 }
1.148     www      3367:             }
1.232     www      3368: 
1.148     www      3369:          if ($refuri) { 
1.152     www      3370: 	  $refuri=&declutter($refuri);
1.232     www      3371:           my ($match,$cond)=&is_on_map($refuri);
                   3372:             if ($match) {
                   3373:               my $refstatecond=$cond;
1.620     albertel 3374:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3375:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3376:                   $thisallowed.=$1;
1.53      www      3377:                   $uri=$refuri;
                   3378:                   $statecond=$refstatecond;
1.52      www      3379:               }
                   3380:           }
1.148     www      3381:         }
1.29      www      3382:        }
1.52      www      3383:    }
1.29      www      3384: 
1.52      www      3385: #
1.103     harris41 3386: # Gathered now: all privileges that could apply, and condition number
1.52      www      3387: # 
                   3388: #
                   3389: # Full or no access?
                   3390: #
1.29      www      3391: 
1.52      www      3392:     if ($thisallowed=~/F/) {
                   3393: 	return 'F';
                   3394:     }
1.29      www      3395: 
1.52      www      3396:     unless ($thisallowed) {
                   3397:         return '';
                   3398:     }
1.29      www      3399: 
1.52      www      3400: # Restrictions exist, deal with them
                   3401: #
                   3402: #   C:according to course preferences
                   3403: #   R:according to resource settings
                   3404: #   L:unless locked
                   3405: #   X:according to user session state
                   3406: #
                   3407: 
                   3408: # Possibly locked functionality, check all courses
1.54      www      3409: # Locks might take effect only after 10 minutes cache expiration for other
                   3410: # courses, and 2 minutes for current course
1.52      www      3411: 
                   3412:     my $envkey;
                   3413:     if ($thisallowed=~/L/) {
1.620     albertel 3414:         foreach $envkey (keys %env) {
1.54      www      3415:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3416:                my $courseid=$2;
                   3417:                my $roleid=$1.'.'.$2;
1.92      www      3418:                $courseid=~s/^\///;
1.54      www      3419:                my $expiretime=600;
1.620     albertel 3420:                if ($env{'request.role'} eq $roleid) {
1.54      www      3421: 		  $expiretime=120;
                   3422:                }
                   3423: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3424:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3425:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.54      www      3426: 		   &coursedescription($courseid);
                   3427:                }
1.620     albertel 3428:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3429:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3430: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3431:                        &log($env{'user.domain'},$env{'user.name'},
                   3432:                             $env{'user.home'},
1.57      www      3433:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3434:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3435:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3436: 		       return '';
                   3437:                    }
                   3438:                }
1.620     albertel 3439:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3440:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3441: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3442:                        &log($env{'user.domain'},$env{'user.name'},
                   3443:                             $env{'user.home'},
1.57      www      3444:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3445:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3446:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3447: 		       return '';
                   3448:                    }
                   3449:                }
                   3450: 	   }
1.29      www      3451:        }
1.52      www      3452:     }
                   3453:    
                   3454: #
                   3455: # Rest of the restrictions depend on selected course
                   3456: #
                   3457: 
1.620     albertel 3458:     unless ($env{'request.course.id'}) {
1.52      www      3459:        return '1';
                   3460:     }
1.29      www      3461: 
1.52      www      3462: #
                   3463: # Now user is definitely in a course
                   3464: #
1.53      www      3465: 
                   3466: 
                   3467: # Course preferences
                   3468: 
                   3469:    if ($thisallowed=~/C/) {
1.620     albertel 3470:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3471:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3472:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3473: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3474: 	   if ($priv ne 'pch') { 
                   3475: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3476: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3477: 			$env{'request.course.id'});
                   3478: 	   }
1.237     www      3479:            return '';
                   3480:        }
                   3481: 
1.620     albertel 3482:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3483: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3484: 	   if ($priv ne 'pch') { 
                   3485: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3486: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3487: 			$env{'request.course.id'});
                   3488: 	   }
1.54      www      3489:            return '';
                   3490:        }
1.53      www      3491:    }
                   3492: 
                   3493: # Resource preferences
                   3494: 
                   3495:    if ($thisallowed=~/R/) {
1.620     albertel 3496:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3497:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3498: 	   if ($priv ne 'pch') { 
                   3499: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3500: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3501: 	   }
                   3502: 	   return '';
1.54      www      3503:        }
1.53      www      3504:    }
1.30      www      3505: 
1.246     www      3506: # Restricted by state or randomout?
1.30      www      3507: 
1.52      www      3508:    if ($thisallowed=~/X/) {
1.620     albertel 3509:       if ($env{'acc.randomout'}) {
1.579     albertel 3510: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3511:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3512:             return ''; 
                   3513:          }
1.247     www      3514:       }
                   3515:       if (&condval($statecond)) {
1.52      www      3516: 	 return '2';
                   3517:       } else {
                   3518:          return '';
                   3519:       }
                   3520:    }
1.30      www      3521: 
1.52      www      3522:    return 'F';
1.232     www      3523: }
                   3524: 
1.710     albertel 3525: sub split_uri_for_cond {
                   3526:     my $uri=&deversion(&declutter(shift));
                   3527:     my @uriparts=split(/\//,$uri);
                   3528:     my $filename=pop(@uriparts);
                   3529:     my $pathname=join('/',@uriparts);
                   3530:     return ($pathname,$filename);
                   3531: }
1.232     www      3532: # --------------------------------------------------- Is a resource on the map?
                   3533: 
                   3534: sub is_on_map {
1.710     albertel 3535:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3536:     #Trying to find the conditional for the file
1.620     albertel 3537:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3538: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3539:     if ($match) {
1.289     bowersj2 3540: 	return (1,$1);
                   3541:     } else {
1.434     www      3542: 	return (0,0);
1.289     bowersj2 3543:     }
1.12      www      3544: }
                   3545: 
1.427     www      3546: # --------------------------------------------------------- Get symb from alias
                   3547: 
                   3548: sub get_symb_from_alias {
                   3549:     my $symb=shift;
                   3550:     my ($map,$resid,$url)=&decode_symb($symb);
                   3551: # Already is a symb
                   3552:     if ($url) { return $symb; }
                   3553: # Must be an alias
                   3554:     my $aliassymb='';
                   3555:     my %bighash;
1.620     albertel 3556:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3557:                             &GDBM_READER(),0640)) {
                   3558:         my $rid=$bighash{'mapalias_'.$symb};
                   3559: 	if ($rid) {
                   3560: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3561: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3562: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3563: 	}
                   3564:         untie %bighash;
                   3565:     }
                   3566:     return $aliassymb;
                   3567: }
                   3568: 
1.12      www      3569: # ----------------------------------------------------------------- Define Role
                   3570: 
                   3571: sub definerole {
                   3572:   if (allowed('mcr','/')) {
                   3573:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3574:     foreach (split(':',$sysrole)) {
1.21      www      3575: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3576:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3577:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3578: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3579:                return "refused:s:$crole&$cqual"; 
                   3580:             }
                   3581:         }
1.191     harris41 3582:     }
1.392     www      3583:     foreach (split(':',$domrole)) {
1.21      www      3584: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3585:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3586:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3587: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3588:                return "refused:d:$crole&$cqual"; 
                   3589:             }
                   3590:         }
1.191     harris41 3591:     }
1.392     www      3592:     foreach (split(':',$courole)) {
1.21      www      3593: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3594:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3595:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3596: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3597:                return "refused:c:$crole&$cqual"; 
                   3598:             }
                   3599:         }
1.191     harris41 3600:     }
1.620     albertel 3601:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3602:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3603: 	        "rolesdef_$rolename=".
                   3604:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3605:     return reply($command,$env{'user.home'});
1.12      www      3606:   } else {
                   3607:     return 'refused';
                   3608:   }
1.105     harris41 3609: }
                   3610: 
                   3611: # ---------------- Make a metadata query against the network of library servers
                   3612: 
                   3613: sub metadata_query {
1.244     matthew  3614:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3615:     my %rhash;
1.244     matthew  3616:     my @server_list = (defined($server_array) ? @$server_array
                   3617:                                               : keys(%libserv) );
                   3618:     for my $server (@server_list) {
1.118     harris41 3619: 	unless ($custom or $customshow) {
                   3620: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3621: 	    $rhash{$server}=$reply;
                   3622: 	}
                   3623: 	else {
                   3624: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3625: 			     &escape($custom).':'.&escape($customshow),
                   3626: 			     $server);
                   3627: 	    $rhash{$server}=$reply;
                   3628: 	}
1.112     harris41 3629:     }
1.118     harris41 3630:     return \%rhash;
1.240     www      3631: }
                   3632: 
                   3633: # ----------------------------------------- Send log queries and wait for reply
                   3634: 
                   3635: sub log_query {
                   3636:     my ($uname,$udom,$query,%filters)=@_;
                   3637:     my $uhome=&homeserver($uname,$udom);
                   3638:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3639:     my $uhost=$hostname{$uhome};
1.241     www      3640:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3641:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3642:                        $uhome);
1.479     albertel 3643:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3644:     return get_query_reply($queryid);
                   3645: }
                   3646: 
1.508     raeburn  3647: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3648: 
                   3649: sub fetch_enrollment_query {
1.511     raeburn  3650:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3651:     my $homeserver;
1.547     raeburn  3652:     my $maxtries = 1;
1.508     raeburn  3653:     if ($context eq 'automated') {
                   3654:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3655:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3656:     } else {
                   3657:         $homeserver = &homeserver($cnum,$dom);
                   3658:     }
1.506     raeburn  3659:     my $host=$hostname{$homeserver};
                   3660:     my $cmd = '';
                   3661:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3662:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3663:     }
                   3664:     $cmd =~ s/%%$//;
                   3665:     $cmd = &escape($cmd);
                   3666:     my $query = 'fetchenrollment';
1.620     albertel 3667:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3668:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3669:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3670:         return 'error: '.$queryid;
                   3671:     }
1.506     raeburn  3672:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3673:     my $tries = 1;
                   3674:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3675:         $reply = &get_query_reply($queryid);
                   3676:         $tries ++;
                   3677:     }
1.526     raeburn  3678:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3679:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3680:     } else {
1.515     raeburn  3681:         my @responses = split/:/,$reply;
                   3682:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3683:             foreach (@responses) {
                   3684:                 my ($key,$value) = split/=/,$_;
                   3685:                 $$replyref{$key} = $value;
                   3686:             }
                   3687:         } else {
1.506     raeburn  3688:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3689:             foreach (@responses) {
                   3690:                 my ($key,$value) = split/=/,$_;
                   3691:                 $$replyref{$key} = $value;
                   3692:                 if ($value > 0) {
                   3693:                     foreach (@{$$affiliatesref{$key}}) {
                   3694:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3695:                         my $destname = $pathname.'/'.$filename;
                   3696:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3697:                         if ($xml_classlist =~ /^error/) {
                   3698:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3699:                         } else {
1.506     raeburn  3700:                             if ( open(FILE,">$destname") ) {
                   3701:                                 print FILE &unescape($xml_classlist);
                   3702:                                 close(FILE);
1.526     raeburn  3703:                             } else {
                   3704:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3705:                             }
                   3706:                         }
                   3707:                     }
                   3708:                 }
                   3709:             }
                   3710:         }
                   3711:         return 'ok';
                   3712:     }
                   3713:     return 'error';
                   3714: }
                   3715: 
1.242     www      3716: sub get_query_reply {
                   3717:     my $queryid=shift;
1.240     www      3718:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3719:     my $reply='';
                   3720:     for (1..100) {
                   3721: 	sleep 2;
                   3722:         if (-e $replyfile.'.end') {
1.448     albertel 3723: 	    if (open(my $fh,$replyfile)) {
1.240     www      3724:                $reply.=<$fh>;
1.448     albertel 3725:                close($fh);
1.240     www      3726: 	   } else { return 'error: reply_file_error'; }
1.242     www      3727:            return &unescape($reply);
                   3728: 	}
1.240     www      3729:     }
1.242     www      3730:     return 'timeout:'.$queryid;
1.240     www      3731: }
                   3732: 
                   3733: sub courselog_query {
1.241     www      3734: #
                   3735: # possible filters:
                   3736: # url: url or symb
                   3737: # username
                   3738: # domain
                   3739: # action: view, submit, grade
                   3740: # start: timestamp
                   3741: # end: timestamp
                   3742: #
1.240     www      3743:     my (%filters)=@_;
1.620     albertel 3744:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3745:     if ($filters{'url'}) {
                   3746: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3747:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3748:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3749:     }
1.620     albertel 3750:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3751:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3752:     return &log_query($cname,$cdom,'courselog',%filters);
                   3753: }
                   3754: 
                   3755: sub userlog_query {
                   3756:     my ($uname,$udom,%filters)=@_;
                   3757:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3758: }
                   3759: 
1.506     raeburn  3760: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3761: 
                   3762: sub auto_run {
1.508     raeburn  3763:     my ($cnum,$cdom) = @_;
                   3764:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3765:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3766:     return $response;
                   3767: }
                   3768:                                                                                    
                   3769: sub auto_get_sections {
1.508     raeburn  3770:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3771:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3772:     my @secs = ();
1.511     raeburn  3773:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3774:     unless ($response eq 'refused') {
                   3775:         @secs = split/:/,$response;
                   3776:     }
                   3777:     return @secs;
                   3778: }
                   3779:                                                                                    
                   3780: sub auto_new_course {
1.508     raeburn  3781:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3782:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3783:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3784:     return $response;
                   3785: }
                   3786:                                                                                    
                   3787: sub auto_validate_courseID {
1.508     raeburn  3788:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3789:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3790:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3791:     return $response;
                   3792: }
                   3793:                                                                                    
                   3794: sub auto_create_password {
1.508     raeburn  3795:     my ($cnum,$cdom,$authparam) = @_;
                   3796:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3797:     my $create_passwd = 0;
                   3798:     my $authchk = '';
1.511     raeburn  3799:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3800:     if ($response eq 'refused') {
                   3801:         $authchk = 'refused';
                   3802:     } else {
                   3803:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3804:     }
                   3805:     return ($authparam,$create_passwd,$authchk);
                   3806: }
                   3807: 
1.706     raeburn  3808: sub auto_photo_permission {
                   3809:     my ($cnum,$cdom,$students) = @_;
                   3810:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 3811:     my ($outcome,$perm_reqd,$conditions) = 
                   3812: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 3813:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3814: 	return (undef,undef);
                   3815:     }
1.706     raeburn  3816:     return ($outcome,$perm_reqd,$conditions);
                   3817: }
                   3818: 
                   3819: sub auto_checkphotos {
                   3820:     my ($uname,$udom,$pid) = @_;
                   3821:     my $homeserver = &homeserver($uname,$udom);
                   3822:     my ($result,$resulttype);
                   3823:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 3824: 				   &escape($uname).':'.&escape($pid),
                   3825: 				   $homeserver));
1.709     albertel 3826:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3827: 	return (undef,undef);
                   3828:     }
1.706     raeburn  3829:     if ($outcome) {
                   3830:         ($result,$resulttype) = split(/:/,$outcome);
                   3831:     } 
                   3832:     return ($result,$resulttype);
                   3833: }
                   3834: 
                   3835: sub auto_photochoice {
                   3836:     my ($cnum,$cdom) = @_;
                   3837:     my $homeserver = &homeserver($cnum,$cdom);
                   3838:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 3839: 						       &escape($cdom),
                   3840: 						       $homeserver)));
1.709     albertel 3841:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   3842: 	return (undef,undef);
                   3843:     }
1.706     raeburn  3844:     return ($update,$comment);
                   3845: }
                   3846: 
                   3847: sub auto_photoupdate {
                   3848:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   3849:     my $homeserver = &homeserver($cnum,$dom);
                   3850:     my $host=$hostname{$homeserver};
                   3851:     my $cmd = '';
                   3852:     my $maxtries = 1;
                   3853:     foreach (keys %{$affiliatesref}) {
                   3854:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   3855:     }
                   3856:     $cmd =~ s/%%$//;
                   3857:     $cmd = &escape($cmd);
                   3858:     my $query = 'institutionalphotos';
                   3859:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   3860:     unless ($queryid=~/^\Q$host\E\_/) {
                   3861:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   3862:         return 'error: '.$queryid;
                   3863:     }
                   3864:     my $reply = &get_query_reply($queryid);
                   3865:     my $tries = 1;
                   3866:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3867:         $reply = &get_query_reply($queryid);
                   3868:         $tries ++;
                   3869:     }
                   3870:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   3871:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   3872:     } else {
                   3873:         my @responses = split(/:/,$reply);
                   3874:         my $outcome = shift(@responses); 
                   3875:         foreach my $item (@responses) {
                   3876:             my ($key,$value) = split(/=/,$item);
                   3877:             $$photo{$key} = $value;
                   3878:         }
                   3879:         return $outcome;
                   3880:     }
                   3881:     return 'error';
                   3882: }
                   3883: 
1.521     raeburn  3884: sub auto_instcode_format {
                   3885:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3886:     my $courses = '';
                   3887:     my $homeserver;
                   3888:     if ($caller eq 'global') {
1.584     raeburn  3889:         foreach my $tryserver (keys %libserv) {
                   3890:             if ($hostdom{$tryserver} eq $codedom) {
                   3891:                 $homeserver = $tryserver;
                   3892:                 last;
                   3893:             }
                   3894:         }
1.620     albertel 3895:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3896:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3897:         }
1.521     raeburn  3898:     } else {
                   3899:         $homeserver = &homeserver($caller,$codedom);
                   3900:     }
                   3901:     foreach (keys %{$instcodes}) {
                   3902:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3903:     }
                   3904:     chop($courses);
                   3905:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3906:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3907:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3908:         %{$codes} = &str2hash($codes_str);
                   3909:         @{$codetitles} = &str2array($codetitles_str);
                   3910:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3911:         %{$cat_order} = &str2hash($cat_order_str);
                   3912:         return 'ok';
                   3913:     }
                   3914:     return $response;
                   3915: }
                   3916: 
1.679     raeburn  3917: # ------------------------------------------------------- Course Group routines
                   3918: 
                   3919: sub get_coursegroups {
1.683     raeburn  3920:     my ($cdom,$cnum,$group) = @_;
                   3921:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  3922: }
                   3923: 
                   3924: sub modify_coursegroup {
                   3925:     my ($cdom,$cnum,$groupsettings) = @_;
                   3926:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   3927: }
                   3928: 
                   3929: sub modify_group_roles {
                   3930:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   3931:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   3932:     my $role = 'gr/'.&escape($userprivs);
                   3933:     my ($uname,$udom) = split(/:/,$user);
                   3934:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  3935:     if ($result eq 'ok') {
                   3936:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   3937:     }
                   3938: 
1.679     raeburn  3939:     return $result;
                   3940: }
                   3941: 
                   3942: sub modify_coursegroup_membership {
                   3943:     my ($cdom,$cnum,$membership) = @_;
                   3944:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   3945:     return $result;
                   3946: }
                   3947: 
1.682     raeburn  3948: sub get_active_groups {
                   3949:     my ($udom,$uname,$cdom,$cnum) = @_;
                   3950:     my $now = time;
                   3951:     my %groups = ();
                   3952:     foreach my $key (keys(%env)) {
                   3953:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   3954:             my ($start,$end) = split(/\./,$env{$key});
                   3955:             if (($end!=0) && ($end<$now)) { next; }
                   3956:             if (($start!=0) && ($start>$now)) { next; }
                   3957:             if ($1 eq $cdom && $2 eq $cnum) {
                   3958:                 $groups{$3} = $env{$key} ;
                   3959:             }
                   3960:         }
                   3961:     }
                   3962:     return %groups;
                   3963: }
                   3964: 
1.683     raeburn  3965: sub get_group_membership {
                   3966:     my ($cdom,$cnum,$group) = @_;
                   3967:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   3968: }
                   3969: 
                   3970: sub get_users_groups {
                   3971:     my ($udom,$uname,$courseid) = @_;
                   3972:     my $cachetime=1800;
                   3973:     $courseid=~s/\_/\//g;
                   3974:     $courseid=~s/^(\w)/\/$1/;
                   3975: 
                   3976:     my $hashid="$udom:$uname:$courseid";
                   3977:     my ($result,$cached)=&is_cached_new('getgroups',$hashid);
                   3978:     if (defined($cached)) { return $result; }
                   3979: 
                   3980:     my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   3981:     my ($tmp) = keys(%roleshash);
                   3982:     if ($tmp=~/^error:/) {
                   3983:         &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   3984:         return '';
                   3985:     } else {
                   3986:         my $grouplist;
                   3987:         foreach my $key (keys %roleshash) {
                   3988:             if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   3989:                 unless ($roleshash{$key} =~ /_1_1$/) {   # deleted membership
                   3990:                     $grouplist .= $1.':';
                   3991:                 }
                   3992:             }
                   3993:         }
                   3994:         $grouplist =~ s/:$//;
                   3995:         return &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
                   3996:     }
                   3997: }
                   3998: 
                   3999: sub devalidate_getgroups_cache {
                   4000:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4001:     my $courseid = $cdom.'_'.$cnum;
                   4002:     $courseid=~s/\_/\//g;
                   4003:     $courseid=~s/^(\w)/\/$1/;
                   4004:     my $hashid="$udom:$uname:$courseid";
                   4005:     &devalidate_cache_new('getgroups',$hashid);
                   4006: }
                   4007: 
1.12      www      4008: # ------------------------------------------------------------------ Plain Text
                   4009: 
                   4010: sub plaintext {
1.22      www      4011:     my $short=shift;
1.676     albertel 4012:     return &Apache::lonlocal::mt($prp{$short});
1.12      www      4013: }
                   4014: 
                   4015: # ----------------------------------------------------------------- Assign Role
                   4016: 
                   4017: sub assignrole {
1.357     www      4018:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4019:     my $mrole;
                   4020:     if ($role =~ /^cr\//) {
1.393     www      4021:         my $cwosec=$url;
                   4022:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4023: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4024:            &logthis('Refused custom assignrole: '.
                   4025:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4026: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4027:            return 'refused'; 
                   4028:         }
1.21      www      4029:         $mrole='cr';
1.678     raeburn  4030:     } elsif ($role =~ /^gr\//) {
                   4031:         my $cwogrp=$url;
                   4032:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4033:         unless (&allowed('mdg',$cwogrp)) {
                   4034:             &logthis('Refused group assignrole: '.
                   4035:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4036:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4037:             return 'refused';
                   4038:         }
                   4039:         $mrole='gr';
1.21      www      4040:     } else {
1.82      www      4041:         my $cwosec=$url;
1.83      www      4042:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4043:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4044:            &logthis('Refused assignrole: '.
                   4045:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4046: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4047:            return 'refused'; 
                   4048:         }
1.21      www      4049:         $mrole=$role;
                   4050:     }
1.620     albertel 4051:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4052:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4053:     if ($end) { $command.='_'.$end; }
1.21      www      4054:     if ($start) {
                   4055: 	if ($end) { 
1.81      www      4056:            $command.='_'.$start; 
1.21      www      4057:         } else {
1.81      www      4058:            $command.='_0_'.$start;
1.21      www      4059:         }
                   4060:     }
1.357     www      4061: # actually delete
                   4062:     if ($deleteflag) {
1.373     www      4063: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4064: # modify command to delete the role
1.620     albertel 4065:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4066:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4067: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4068: # set start and finish to negative values for userrolelog
                   4069:            $start=-1;
                   4070:            $end=-1;
                   4071:         }
                   4072:     }
                   4073: # send command
1.349     www      4074:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4075: # log new user role if status is ok
1.349     www      4076:     if ($answer eq 'ok') {
1.663     raeburn  4077: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.349     www      4078:     }
                   4079:     return $answer;
1.169     harris41 4080: }
                   4081: 
                   4082: # -------------------------------------------------- Modify user authentication
1.197     www      4083: # Overrides without validation
                   4084: 
1.169     harris41 4085: sub modifyuserauth {
                   4086:     my ($udom,$uname,$umode,$upass)=@_;
                   4087:     my $uhome=&homeserver($uname,$udom);
1.197     www      4088:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4089:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4090:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4091:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4092:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4093: 		     &escape($upass),$uhome);
1.620     albertel 4094:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4095:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4096:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4097:     &log($udom,,$uname,$uhome,
1.620     albertel 4098:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4099:                                      $env{'user.name'}.', '.$umode.
1.197     www      4100:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4101:     unless ($reply eq 'ok') {
1.197     www      4102:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4103: 	return 'error: '.$reply;
                   4104:     }   
1.170     harris41 4105:     return 'ok';
1.80      www      4106: }
                   4107: 
1.81      www      4108: # --------------------------------------------------------------- Modify a user
1.80      www      4109: 
1.81      www      4110: sub modifyuser {
1.206     matthew  4111:     my ($udom,    $uname, $uid,
                   4112:         $umode,   $upass, $first,
                   4113:         $middle,  $last,  $gene,
1.387     www      4114:         $forceid, $desiredhome, $email)=@_;
1.198     www      4115:     $udom=~s/\W//g;
                   4116:     $uname=~s/\W//g;
1.81      www      4117:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4118:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4119: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4120:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4121:                                      ' desiredhome not specified'). 
1.620     albertel 4122:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4123:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4124:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4125: # ----------------------------------------------------------------- Create User
1.406     albertel 4126:     if (($uhome eq 'no_host') && 
                   4127: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4128:         my $unhome='';
1.209     matthew  4129:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4130:             $unhome = $desiredhome;
1.620     albertel 4131: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4132: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4133:         } else { # load balancing routine for determining $unhome
1.80      www      4134:             my $tryserver;
1.81      www      4135:             my $loadm=10000000;
1.80      www      4136:             foreach $tryserver (keys %libserv) {
                   4137: 	       if ($hostdom{$tryserver} eq $udom) {
                   4138:                   my $answer=reply('load',$tryserver);
                   4139:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4140: 		      $loadm=$answer;
                   4141:                       $unhome=$tryserver;
                   4142:                   }
                   4143: 	       }
                   4144: 	    }
                   4145:         }
                   4146:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4147: 	    return 'error: unable to find a home server for '.$uname.
                   4148:                    ' in domain '.$udom;
1.80      www      4149:         }
                   4150:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4151:                          &escape($upass),$unhome);
                   4152: 	unless ($reply eq 'ok') {
                   4153:             return 'error: '.$reply;
                   4154:         }   
1.230     stredwic 4155:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4156:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4157: 	    return 'error: unable verify users home machine.';
1.80      www      4158:         }
1.209     matthew  4159:     }   # End of creation of new user
1.80      www      4160: # ---------------------------------------------------------------------- Add ID
                   4161:     if ($uid) {
                   4162:        $uid=~tr/A-Z/a-z/;
                   4163:        my %uidhash=&idrget($udom,$uname);
1.196     www      4164:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4165:          && (!$forceid)) {
1.80      www      4166: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4167: 	      return 'error: user id "'.$uid.'" does not match '.
                   4168:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4169:           }
                   4170:        } else {
                   4171: 	  &idput($udom,($uname => $uid));
                   4172:        }
                   4173:     }
                   4174: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4175:     my @tmp=&get('environment',
1.134     albertel 4176: 		   ['firstname','middlename','lastname','generation'],
                   4177: 		   $udom,$uname);
1.313     matthew  4178:     my %names;
                   4179:     if ($tmp[0] =~ m/^error:.*/) { 
                   4180:         %names=(); 
                   4181:     } else {
                   4182:         %names = @tmp;
                   4183:     }
1.388     www      4184: #
                   4185: # Make sure to not trash student environment if instructor does not bother
                   4186: # to supply name and email information
                   4187: #
                   4188:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4189:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4190:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4191:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4192:     if ($email) {
                   4193:        $email=~s/[^\w\@\.\-\,]//gs;
                   4194:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4195: 			   $names{'critnotification'} = $email;
                   4196: 			   $names{'permanentemail'} = $email; }
                   4197:     }
1.134     albertel 4198:     my $reply = &put('environment', \%names, $udom,$uname);
                   4199:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4200:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4201:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4202:              $umode.', '.$first.', '.$middle.', '.
                   4203: 	     $last.', '.$gene.' by '.
1.620     albertel 4204:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4205:     return 'ok';
1.80      www      4206: }
                   4207: 
1.81      www      4208: # -------------------------------------------------------------- Modify student
1.80      www      4209: 
1.81      www      4210: sub modifystudent {
                   4211:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4212:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4213:     if (!$cid) {
1.620     albertel 4214: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4215: 	    return 'not_in_class';
                   4216: 	}
1.80      www      4217:     }
                   4218: # --------------------------------------------------------------- Make the user
1.81      www      4219:     my $reply=&modifyuser
1.209     matthew  4220: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4221:          $desiredhome,$email);
1.80      www      4222:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4223:     # This will cause &modify_student_enrollment to get the uid from the
                   4224:     # students environment
                   4225:     $uid = undef if (!$forceid);
1.455     albertel 4226:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4227: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4228:     return $reply;
                   4229: }
                   4230: 
                   4231: sub modify_student_enrollment {
1.515     raeburn  4232:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4233:     my ($cdom,$cnum,$chome);
                   4234:     if (!$cid) {
1.620     albertel 4235: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4236: 	    return 'not_in_class';
                   4237: 	}
1.620     albertel 4238: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4239: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4240:     } else {
                   4241: 	($cdom,$cnum)=split(/_/,$cid);
                   4242:     }
1.620     albertel 4243:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4244:     if (!$chome) {
1.457     raeburn  4245: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4246:     }
1.455     albertel 4247:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4248:     # Make sure the user exists
1.81      www      4249:     my $uhome=&homeserver($uname,$udom);
                   4250:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4251: 	return 'error: no such user';
                   4252:     }
1.297     matthew  4253:     # Get student data if we were not given enough information
                   4254:     if (!defined($first)  || $first  eq '' || 
                   4255:         !defined($last)   || $last   eq '' || 
                   4256:         !defined($uid)    || $uid    eq '' || 
                   4257:         !defined($middle) || $middle eq '' || 
                   4258:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4259:         # They did not supply us with enough data to enroll the student, so
                   4260:         # we need to pick up more information.
1.297     matthew  4261:         my %tmp = &get('environment',
1.294     matthew  4262:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4263:                        ,$udom,$uname);
                   4264: 
1.455     albertel 4265:         #foreach (keys(%tmp)) {
                   4266:         #    &logthis("key $_ = ".$tmp{$_});
                   4267:         #}
1.294     matthew  4268:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4269:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4270:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4271:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4272:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4273:     }
1.556     albertel 4274:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4275:     my $reply=cput('classlist',
                   4276: 		   {"$uname:$udom" => 
1.515     raeburn  4277: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4278: 		   $cdom,$cnum);
1.81      www      4279:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4280: 	return 'error: '.$reply;
1.652     albertel 4281:     } else {
                   4282: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4283:     }
1.297     matthew  4284:     # Add student role to user
1.83      www      4285:     my $uurl='/'.$cid;
1.81      www      4286:     $uurl=~s/\_/\//g;
                   4287:     if ($usec) {
                   4288: 	$uurl.='/'.$usec;
                   4289:     }
                   4290:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4291: }
                   4292: 
1.556     albertel 4293: sub format_name {
                   4294:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4295:     my $name;
                   4296:     if ($first ne 'lastname') {
                   4297: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4298:     } else {
                   4299: 	if ($lastname=~/\S/) {
                   4300: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4301: 	    $name=~s/\s+,/,/;
                   4302: 	} else {
                   4303: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4304: 	}
                   4305:     }
                   4306:     $name=~s/^\s+//;
                   4307:     $name=~s/\s+$//;
                   4308:     $name=~s/\s+/ /g;
                   4309:     return $name;
                   4310: }
                   4311: 
1.84      www      4312: # ------------------------------------------------- Write to course preferences
                   4313: 
                   4314: sub writecoursepref {
                   4315:     my ($courseid,%prefs)=@_;
                   4316:     $courseid=~s/^\///;
                   4317:     $courseid=~s/\_/\//g;
                   4318:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4319:     my $chome=homeserver($cnum,$cdomain);
                   4320:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4321: 	return 'error: no such course';
                   4322:     }
                   4323:     my $cstring='';
1.191     harris41 4324:     foreach (keys %prefs) {
1.84      www      4325: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4326:     }
1.84      www      4327:     $cstring=~s/\&$//;
                   4328:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4329: }
                   4330: 
                   4331: # ---------------------------------------------------------- Make/modify course
                   4332: 
                   4333: sub createcourse {
1.571     raeburn  4334:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      4335:     $url=&declutter($url);
                   4336:     my $cid='';
1.264     matthew  4337:     unless (&allowed('ccc',$udom)) {
1.84      www      4338:         return 'refused';
                   4339:     }
                   4340: # ------------------------------------------------------------------- Create ID
1.674     www      4341:    my $uname=int(1+rand(9)).
                   4342:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4343:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4344:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4345: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4346:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4347:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4348:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4349:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4350:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4351:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4352:            return 'error: unable to generate unique course-ID';
                   4353:        } 
                   4354:    }
1.264     matthew  4355: # ------------------------------------------------ Check supplied server name
1.620     albertel 4356:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4357:     if (! exists($libserv{$course_server})) {
                   4358:         return 'error:bad server name '.$course_server;
                   4359:     }
1.84      www      4360: # ------------------------------------------------------------- Make the course
                   4361:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4362:                       $course_server);
1.84      www      4363:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4364:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4365:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4366: 	return 'error: no such course';
                   4367:     }
1.271     www      4368: # ----------------------------------------------------------------- Course made
1.516     raeburn  4369: # log existence
                   4370:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  4371:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      4372:     &flushcourselogs();
                   4373: # set toplevel url
1.271     www      4374:     my $topurl=$url;
                   4375:     unless ($nonstandard) {
                   4376: # ------------------------------------------ For standard courses, make top url
                   4377:         my $mapurl=&clutter($url);
1.278     www      4378:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4379:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4380: <map>
                   4381: <resource id="1" type="start"></resource>
                   4382: <resource id="2" src="$mapurl"></resource>
                   4383: <resource id="3" type="finish"></resource>
                   4384: <link index="1" from="1" to="2"></link>
                   4385: <link index="2" from="2" to="3"></link>
                   4386: </map>
                   4387: ENDINITMAP
                   4388:         $topurl=&declutter(
1.638     albertel 4389:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4390:                           );
                   4391:     }
                   4392: # ----------------------------------------------------------- Write preferences
1.84      www      4393:     &writecoursepref($udom.'_'.$uname,
                   4394:                      ('description' => $description,
1.271     www      4395:                       'url'         => $topurl));
1.84      www      4396:     return '/'.$udom.'/'.$uname;
                   4397: }
                   4398: 
1.21      www      4399: # ---------------------------------------------------------- Assign Custom Role
                   4400: 
                   4401: sub assigncustomrole {
1.357     www      4402:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4403:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4404:                        $end,$start,$deleteflag);
1.21      www      4405: }
                   4406: 
                   4407: # ----------------------------------------------------------------- Revoke Role
                   4408: 
                   4409: sub revokerole {
1.357     www      4410:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4411:     my $now=time;
1.357     www      4412:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4413: }
                   4414: 
                   4415: # ---------------------------------------------------------- Revoke Custom Role
                   4416: 
                   4417: sub revokecustomrole {
1.357     www      4418:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4419:     my $now=time;
1.357     www      4420:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4421:            $deleteflag);
1.17      www      4422: }
                   4423: 
1.533     banghart 4424: # ------------------------------------------------------------ Disk usage
1.535     albertel 4425: sub diskusage {
1.533     banghart 4426:     my ($udom,$uname,$directoryRoot)=@_;
                   4427:     $directoryRoot =~ s/\/$//;
1.535     albertel 4428:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4429:     return $listing;
1.512     banghart 4430: }
                   4431: 
1.566     banghart 4432: sub is_locked {
                   4433:     my ($file_name, $domain, $user) = @_;
                   4434:     my @check;
                   4435:     my $is_locked;
                   4436:     push @check, $file_name;
1.613     albertel 4437:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4438: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4439:     my ($tmp)=keys(%locked);
                   4440:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 4441: 
1.566     banghart 4442:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   4443:         $is_locked = 'true';
                   4444:     } else {
                   4445:         $is_locked = 'false';
                   4446:     }
                   4447: }
                   4448: 
1.559     banghart 4449: # ------------------------------------------------------------- Mark as Read Only
                   4450: 
                   4451: sub mark_as_readonly {
                   4452:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4453:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4454:     my ($tmp)=keys(%current_permissions);
                   4455:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4456:     foreach my $file (@{$files}) {
1.561     banghart 4457:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4458:     }
1.613     albertel 4459:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4460:     return;
                   4461: }
                   4462: 
1.572     banghart 4463: # ------------------------------------------------------------Save Selected Files
                   4464: 
                   4465: sub save_selected_files {
                   4466:     my ($user, $path, @files) = @_;
                   4467:     my $filename = $user."savedfiles";
1.573     banghart 4468:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4469:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4470:     foreach my $file (@files) {
1.620     albertel 4471:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4472:     }
                   4473:     foreach my $file (@other_files) {
1.574     banghart 4474:         print (OUT $file."\n");
1.572     banghart 4475:     }
1.574     banghart 4476:     close (OUT);
1.572     banghart 4477:     return 'ok';
                   4478: }
                   4479: 
1.574     banghart 4480: sub clear_selected_files {
                   4481:     my ($user) = @_;
                   4482:     my $filename = $user."savedfiles";
                   4483:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4484:     print (OUT undef);
                   4485:     close (OUT);
                   4486:     return ("ok");    
                   4487: }
                   4488: 
1.572     banghart 4489: sub files_in_path {
                   4490:     my ($user, $path) = @_;
                   4491:     my $filename = $user."savedfiles";
                   4492:     my %return_files;
1.574     banghart 4493:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4494:     while (my $line_in = <IN>) {
1.574     banghart 4495:         chomp ($line_in);
                   4496:         my @paths_and_file = split (m!/!, $line_in);
                   4497:         my $file_part = pop (@paths_and_file);
                   4498:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4499:         $path_part.='/';
                   4500:         my $path_and_file = $path_part.$file_part;
                   4501:         if ($path_part eq $path) {
                   4502:             $return_files{$file_part}= 'selected';
                   4503:         }
                   4504:     }
1.574     banghart 4505:     close (IN);
                   4506:     return (\%return_files);
1.572     banghart 4507: }
                   4508: 
                   4509: # called in portfolio select mode, to show files selected NOT in current directory
                   4510: sub files_not_in_path {
                   4511:     my ($user, $path) = @_;
                   4512:     my $filename = $user."savedfiles";
                   4513:     my @return_files;
                   4514:     my $path_part;
1.574     banghart 4515:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4516:     while (<IN>) {
                   4517:         #ok, I know it's clunky, but I want it to work
                   4518:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4519:         my $file_part = pop (@paths_and_file);
                   4520:         chomp ($file_part);
                   4521:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4522:         $path_part .= '/';
                   4523:         my $path_and_file = $path_part.$file_part;
                   4524:         if ($path_part ne $path) {
1.574     banghart 4525:             push (@return_files, ($path_and_file));
1.572     banghart 4526:         }
                   4527:     }
1.574     banghart 4528:     close (OUT);
                   4529:     return (@return_files);
1.572     banghart 4530: }
                   4531: 
1.561     banghart 4532: #--------------------------------------------------------------Get Marked as Read Only
                   4533: 
1.629     banghart 4534: 
1.561     banghart 4535: sub get_marked_as_readonly {
                   4536:     my ($domain,$user,$what) = @_;
1.613     albertel 4537:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4538:     my ($tmp)=keys(%current_permissions);
                   4539:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563     banghart 4540:     my @readonly_files;
1.629     banghart 4541:     my $cmp1=$what;
                   4542:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.563     banghart 4543:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 4544:         if (ref($value) eq "ARRAY"){
                   4545:             foreach my $stored_what (@{$value}) {
1.629     banghart 4546:                 my $cmp2=$stored_what;
                   4547:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
                   4548:                 if ($cmp1 eq $cmp2) {
1.561     banghart 4549:                     push(@readonly_files, $file_name);
1.563     banghart 4550:                 } elsif (!defined($what)) {
                   4551:                     push(@readonly_files, $file_name);
1.561     banghart 4552:                 }
                   4553:             }
                   4554:         } 
                   4555:     }
                   4556:     return @readonly_files;
                   4557: }
1.577     banghart 4558: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 4559: 
1.577     banghart 4560: sub get_marked_as_readonly_hash {
                   4561:     my ($domain,$user,$what) = @_;
1.613     albertel 4562:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4563:     my ($tmp)=keys(%current_permissions);
                   4564:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4565: 
1.577     banghart 4566:     my %readonly_files;
                   4567:     while (my ($file_name,$value) = each(%current_permissions)) {
                   4568:         if (ref($value) eq "ARRAY"){
                   4569:             foreach my $stored_what (@{$value}) {
                   4570:                 if ($stored_what eq $what) {
                   4571:                     $readonly_files{$file_name} = 'locked';
                   4572:                 } elsif (!defined($what)) {
                   4573:                     $readonly_files{$file_name} = 'locked';
                   4574:                 }
                   4575:             }
                   4576:         } 
                   4577:     }
                   4578:     return %readonly_files;
                   4579: }
1.559     banghart 4580: # ------------------------------------------------------------ Unmark as Read Only
                   4581: 
                   4582: sub unmark_as_readonly {
1.629     banghart 4583:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   4584:     # for portfolio submissions, $what contains [$symb,$crsid] 
                   4585:     my ($domain,$user,$what,$file_name) = @_;
1.634     albertel 4586:     my $symb_crs = $what;
                   4587:     if (ref($what)) { $symb_crs=join('',@$what); }
1.613     albertel 4588:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4589:     my ($tmp)=keys(%current_permissions);
                   4590:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 4591:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.650     albertel 4592:     foreach my $file (@readonly_files) {
                   4593: 	if (defined($file_name) && ($file_name ne $file)) { next; }
                   4594: 	my $current_locks = $current_permissions{$file};
1.563     banghart 4595:         my @new_locks;
                   4596:         my @del_keys;
                   4597:         if (ref($current_locks) eq "ARRAY"){
                   4598:             foreach my $locker (@{$current_locks}) {
1.632     albertel 4599:                 my $compare=$locker;
                   4600:                 if (ref($locker)) { $compare=join('',@{$locker}) };
1.650     albertel 4601:                 if ($compare ne $symb_crs) {
                   4602:                     push(@new_locks, $locker);
1.563     banghart 4603:                 }
                   4604:             }
1.650     albertel 4605:             if (scalar(@new_locks) > 0) {
1.563     banghart 4606:                 $current_permissions{$file} = \@new_locks;
                   4607:             } else {
                   4608:                 push(@del_keys, $file);
1.613     albertel 4609:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 4610:                 delete($current_permissions{$file});
1.563     banghart 4611:             }
                   4612:         }
1.561     banghart 4613:     }
1.613     albertel 4614:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4615:     return;
                   4616: }
1.512     banghart 4617: 
1.17      www      4618: # ------------------------------------------------------------ Directory lister
                   4619: 
                   4620: sub dirlist {
1.253     stredwic 4621:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   4622: 
1.18      www      4623:     $uri=~s/^\///;
                   4624:     $uri=~s/\/$//;
1.253     stredwic 4625:     my ($udom, $uname);
                   4626:     (undef,$udom,$uname)=split(/\//,$uri);
                   4627:     if(defined($userdomain)) {
                   4628:         $udom = $userdomain;
                   4629:     }
                   4630:     if(defined($username)) {
                   4631:         $uname = $username;
                   4632:     }
                   4633: 
                   4634:     my $dirRoot = $perlvar{'lonDocRoot'};
                   4635:     if(defined($alternateDirectoryRoot)) {
                   4636:         $dirRoot = $alternateDirectoryRoot;
                   4637:         $dirRoot =~ s/\/$//;
                   4638:     }
                   4639: 
                   4640:     if($udom) {
                   4641:         if($uname) {
1.605     matthew  4642:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 4643:                               homeserver($uname,$udom));
1.605     matthew  4644:             my @listing_results;
                   4645:             if ($listing eq 'unknown_cmd') {
                   4646:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   4647:                                homeserver($uname,$udom));
                   4648:                 @listing_results = split(/:/,$listing);
                   4649:             } else {
                   4650:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   4651:             }
                   4652:             return @listing_results;
1.253     stredwic 4653:         } elsif(!defined($alternateDirectoryRoot)) {
                   4654:             my $tryserver;
                   4655:             my %allusers=();
                   4656:             foreach $tryserver (keys %libserv) {
                   4657:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  4658:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 4659:                                       $udom, $tryserver);
1.605     matthew  4660:                     my @listing_results;
                   4661:                     if ($listing eq 'unknown_cmd') {
                   4662:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   4663:                                        $udom, $tryserver);
                   4664:                         @listing_results = split(/:/,$listing);
                   4665:                     } else {
                   4666:                         @listing_results =
                   4667:                             map { &unescape($_); } split(/:/,$listing);
                   4668:                     }
                   4669:                     if ($listing_results[0] ne 'no_such_dir' && 
                   4670:                         $listing_results[0] ne 'empty'       &&
                   4671:                         $listing_results[0] ne 'con_lost') {
                   4672:                         foreach (@listing_results) {
1.253     stredwic 4673:                             my ($entry,@stat)=split(/&/,$_);
                   4674:                             $allusers{$entry}=1;
                   4675:                         }
                   4676:                     }
1.191     harris41 4677:                 }
1.253     stredwic 4678:             }
                   4679:             my $alluserstr='';
                   4680:             foreach (sort keys %allusers) {
                   4681:                 $alluserstr.=$_.'&user:';
                   4682:             }
                   4683:             $alluserstr=~s/:$//;
                   4684:             return split(/:/,$alluserstr);
                   4685:         } else {
                   4686:             my @emptyResults = ();
                   4687:             push(@emptyResults, 'missing user name');
                   4688:             return split(':',@emptyResults);
                   4689:         }
                   4690:     } elsif(!defined($alternateDirectoryRoot)) {
                   4691:         my $tryserver;
                   4692:         my %alldom=();
                   4693:         foreach $tryserver (keys %libserv) {
                   4694:             $alldom{$hostdom{$tryserver}}=1;
                   4695:         }
                   4696:         my $alldomstr='';
                   4697:         foreach (sort keys %alldom) {
1.397     albertel 4698:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4699:         }
                   4700:         $alldomstr=~s/:$//;
                   4701:         return split(/:/,$alldomstr);       
                   4702:     } else {
                   4703:         my @emptyResults = ();
                   4704:         push(@emptyResults, 'missing domain');
                   4705:         return split(':',@emptyResults);
1.275     stredwic 4706:     }
                   4707: }
                   4708: 
                   4709: # --------------------------------------------- GetFileTimestamp
                   4710: # This function utilizes dirlist and returns the date stamp for
                   4711: # when it was last modified.  It will also return an error of -1
                   4712: # if an error occurs
                   4713: 
1.410     matthew  4714: ##
                   4715: ## FIXME: This subroutine assumes its caller knows something about the
                   4716: ## directory structure of the home server for the student ($root).
                   4717: ## Not a good assumption to make.  Since this is for looking up files
                   4718: ## in user directories, the full path should be constructed by lond, not
                   4719: ## whatever machine we request data from.
                   4720: ##
1.275     stredwic 4721: sub GetFileTimestamp {
                   4722:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4723:     $studentDomain=~s/\W//g;
                   4724:     $studentName=~s/\W//g;
                   4725:     my $subdir=$studentName.'__';
                   4726:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4727:     my $proname="$studentDomain/$subdir/$studentName";
                   4728:     $proname .= '/'.$filename;
1.375     matthew  4729:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4730:                                               $studentName, $root);
1.275     stredwic 4731:     my @stats = split('&', $fileStat);
                   4732:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4733:         # @stats contains first the filename, then the stat output
                   4734:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4735:     } else {
                   4736:         return -1;
1.253     stredwic 4737:     }
1.26      www      4738: }
                   4739: 
1.712     albertel 4740: sub stat_file {
                   4741:     my ($uri) = @_;
                   4742:     $uri = &clutter($uri);
                   4743:     my ($udom,$uname,$file,$dir);
                   4744:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   4745: 	($udom,$uname,$file) =
                   4746: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   4747: 	$file = 'userfiles/'.$file;
                   4748: 	$dir = &Apache::loncommon::propath($udom,$uname);
                   4749:     }
                   4750:     if ($uri =~ m-^/res/-) {
                   4751: 	($udom,$uname) = 
                   4752: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   4753: 	$file = $uri;
                   4754:     }
                   4755: 
                   4756:     if (!$udom || !$uname || !$file) {
                   4757: 	# unable to handle the uri
                   4758: 	return ();
                   4759:     }
                   4760: 
                   4761:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   4762:     my @stats = split('&', $result);
                   4763:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   4764: 	shift(@stats); #filename is first
                   4765: 	return @stats;
                   4766:     }
                   4767:     return ();
                   4768: }
                   4769: 
1.26      www      4770: # -------------------------------------------------------- Value of a Condition
                   4771: 
1.713     albertel 4772: # gets the value of a specific preevaluated condition
                   4773: #    stored in the string  $env{user.state.<cid>}
                   4774: # or looks up a condition reference in the bighash and if if hasn't
                   4775: # already been evaluated recurses into docondval to get the value of
                   4776: # the condition, then memoizing it to 
                   4777: #   $env{user.state.<cid>.<condition>}
1.40      www      4778: sub directcondval {
                   4779:     my $number=shift;
1.620     albertel 4780:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4781: 	&Apache::lonuserstate::evalstate();
                   4782:     }
1.713     albertel 4783:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   4784: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   4785:     } elsif ($number =~ /^_/) {
                   4786: 	my $sub_condition;
                   4787: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   4788: 		&GDBM_READER(),0640)) {
                   4789: 	    $sub_condition=$bighash{'conditions'.$number};
                   4790: 	    untie(%bighash);
                   4791: 	}
                   4792: 	my $value = &docondval($sub_condition);
                   4793: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   4794: 	return $value;
                   4795:     }
1.620     albertel 4796:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4797:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4798:     } else {
                   4799:        return 2;
                   4800:     }
                   4801: }
                   4802: 
1.713     albertel 4803: # get the collection of conditions for this resource
1.26      www      4804: sub condval {
                   4805:     my $condidx=shift;
1.54      www      4806:     my $allpathcond='';
1.713     albertel 4807:     foreach my $cond (split(/\|/,$condidx)) {
                   4808: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   4809: 	    $allpathcond.=
                   4810: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   4811: 	}
1.191     harris41 4812:     }
1.54      www      4813:     $allpathcond=~s/\|$//;
1.713     albertel 4814:     return &docondval($allpathcond);
                   4815: }
                   4816: 
                   4817: #evaluates an expression of conditions
                   4818: sub docondval {
                   4819:     my ($allpathcond) = @_;
                   4820:     my $result=0;
                   4821:     if ($env{'request.course.id'}
                   4822: 	&& defined($allpathcond)) {
                   4823: 	my $operand='|';
                   4824: 	my @stack;
                   4825: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   4826: 	    if ($chunk eq '(') {
                   4827: 		push @stack,($operand,$result);
                   4828: 	    } elsif ($chunk eq ')') {
                   4829: 		my $before=pop @stack;
                   4830: 		if (pop @stack eq '&') {
                   4831: 		    $result=$result>$before?$before:$result;
                   4832: 		} else {
                   4833: 		    $result=$result>$before?$result:$before;
                   4834: 		}
                   4835: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   4836: 		$operand=$chunk;
                   4837: 	    } else {
                   4838: 		my $new=directcondval($chunk);
                   4839: 		if ($operand eq '&') {
                   4840: 		    $result=$result>$new?$new:$result;
                   4841: 		} else {
                   4842: 		    $result=$result>$new?$result:$new;
                   4843: 		}
                   4844: 	    }
                   4845: 	}
1.26      www      4846:     }
                   4847:     return $result;
1.421     albertel 4848: }
                   4849: 
                   4850: # ---------------------------------------------------- Devalidate courseresdata
                   4851: 
                   4852: sub devalidatecourseresdata {
                   4853:     my ($coursenum,$coursedomain)=@_;
                   4854:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4855:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4856: }
                   4857: 
1.200     www      4858: # --------------------------------------------------- Course Resourcedata Query
                   4859: 
1.624     albertel 4860: sub get_courseresdata {
                   4861:     my ($coursenum,$coursedomain)=@_;
1.200     www      4862:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4863:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4864:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4865:     my %dumpreply;
1.417     albertel 4866:     unless (defined($cached)) {
1.624     albertel 4867: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4868: 	$result=\%dumpreply;
1.251     albertel 4869: 	my ($tmp) = keys(%dumpreply);
                   4870: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4871: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4872: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4873: 	    return $tmp;
1.416     albertel 4874: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4875: 	    $result=undef;
1.599     albertel 4876: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4877: 	}
                   4878:     }
1.624     albertel 4879:     return $result;
                   4880: }
                   4881: 
1.633     albertel 4882: sub devalidateuserresdata {
                   4883:     my ($uname,$udom)=@_;
                   4884:     my $hashid="$udom:$uname";
                   4885:     &devalidate_cache_new('userres',$hashid);
                   4886: }
                   4887: 
1.624     albertel 4888: sub get_userresdata {
                   4889:     my ($uname,$udom)=@_;
                   4890:     #most student don\'t have any data set, check if there is some data
                   4891:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4892: 
                   4893:     my $hashid="$udom:$uname";
                   4894:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4895:     if (!defined($cached)) {
                   4896: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4897: 	$result=\%resourcedata;
                   4898: 	&do_cache_new('userres',$hashid,$result,600);
                   4899:     }
                   4900:     my ($tmp)=keys(%$result);
                   4901:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4902: 	return $result;
                   4903:     }
                   4904:     #error 2 occurs when the .db doesn't exist
                   4905:     if ($tmp!~/error: 2 /) {
1.672     albertel 4906: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 4907: 		 " Trying to get resource data for ".
                   4908: 		 $uname." at ".$udom.": ".
                   4909: 		 $tmp."</font>");
                   4910:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 4911: 	#&EXT_cache_set($udom,$uname);
                   4912: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 4913: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 4914:     }
                   4915:     return $tmp;
                   4916: }
                   4917: 
                   4918: sub resdata {
                   4919:     my ($name,$domain,$type,@which)=@_;
                   4920:     my $result;
                   4921:     if ($type eq 'course') {
                   4922: 	$result=&get_courseresdata($name,$domain);
                   4923:     } elsif ($type eq 'user') {
                   4924: 	$result=&get_userresdata($name,$domain);
                   4925:     }
                   4926:     if (!ref($result)) { return $result; }    
1.251     albertel 4927:     foreach my $item (@which) {
1.417     albertel 4928: 	if (defined($result->{$item})) {
                   4929: 	    return $result->{$item};
1.251     albertel 4930: 	}
1.250     albertel 4931:     }
1.291     albertel 4932:     return undef;
1.200     www      4933: }
                   4934: 
1.379     matthew  4935: #
                   4936: # EXT resource caching routines
                   4937: #
                   4938: 
                   4939: sub clear_EXT_cache_status {
1.383     albertel 4940:     &delenv('cache.EXT.');
1.379     matthew  4941: }
                   4942: 
                   4943: sub EXT_cache_status {
                   4944:     my ($target_domain,$target_user) = @_;
1.383     albertel 4945:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 4946:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  4947:         # We know already the user has no data
                   4948:         return 1;
                   4949:     } else {
                   4950:         return 0;
                   4951:     }
                   4952: }
                   4953: 
                   4954: sub EXT_cache_set {
                   4955:     my ($target_domain,$target_user) = @_;
1.383     albertel 4956:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 4957:     #&appenv($cachename => time);
1.379     matthew  4958: }
                   4959: 
1.28      www      4960: # --------------------------------------------------------- Value of a Variable
1.58      www      4961: sub EXT {
1.715     albertel 4962: 
1.395     albertel 4963:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      4964:     unless ($varname) { return ''; }
1.218     albertel 4965:     #get real user name/domain, courseid and symb
                   4966:     my $courseid;
1.359     albertel 4967:     my $publicuser;
1.427     www      4968:     if ($symbparm) {
                   4969: 	$symbparm=&get_symb_from_alias($symbparm);
                   4970:     }
1.218     albertel 4971:     if (!($uname && $udom)) {
1.360     albertel 4972:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  4973: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 4974:       if (!$symbparm) {	$symbparm=$cursymb; }
                   4975:     } else {
1.620     albertel 4976: 	$courseid=$env{'request.course.id'};
1.218     albertel 4977:     }
1.48      www      4978:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   4979:     my $rest;
1.320     albertel 4980:     if (defined($therest[0])) {
1.48      www      4981:        $rest=join('.',@therest);
                   4982:     } else {
                   4983:        $rest='';
                   4984:     }
1.320     albertel 4985: 
1.57      www      4986:     my $qualifierrest=$qualifier;
                   4987:     if ($rest) { $qualifierrest.='.'.$rest; }
                   4988:     my $spacequalifierrest=$space;
                   4989:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      4990:     if ($realm eq 'user') {
1.48      www      4991: # --------------------------------------------------------------- user.resource
                   4992: 	if ($space eq 'resource') {
1.651     albertel 4993: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   4994: 		  || defined($Apache::lonhomework::parsing_a_task))
                   4995: 		 &&
                   4996: 		 ($symbparm eq &symbread()) ) {
1.335     albertel 4997: 		return $Apache::lonhomework::history{$qualifierrest};
                   4998: 	    } else {
1.359     albertel 4999: 		my %restored;
1.620     albertel 5000: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5001: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5002: 		} else {
                   5003: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5004: 		}
1.335     albertel 5005: 		return $restored{$qualifierrest};
                   5006: 	    }
1.48      www      5007: # ----------------------------------------------------------------- user.access
                   5008:         } elsif ($space eq 'access') {
1.218     albertel 5009: 	    # FIXME - not supporting calls for a specific user
1.48      www      5010:             return &allowed($qualifier,$rest);
                   5011: # ------------------------------------------ user.preferences, user.environment
                   5012:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5013: 	    if (($uname eq $env{'user.name'}) &&
                   5014: 		($udom eq $env{'user.domain'})) {
                   5015: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5016: 	    } else {
1.359     albertel 5017: 		my %returnhash;
                   5018: 		if (!$publicuser) {
                   5019: 		    %returnhash=&userenvironment($udom,$uname,
                   5020: 						 $qualifierrest);
                   5021: 		}
1.218     albertel 5022: 		return $returnhash{$qualifierrest};
                   5023: 	    }
1.48      www      5024: # ----------------------------------------------------------------- user.course
                   5025:         } elsif ($space eq 'course') {
1.218     albertel 5026: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5027:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5028: # ------------------------------------------------------------------- user.role
                   5029:         } elsif ($space eq 'role') {
1.218     albertel 5030: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5031:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5032:             if ($qualifier eq 'value') {
                   5033: 		return $role;
                   5034:             } elsif ($qualifier eq 'extent') {
                   5035:                 return $where;
                   5036:             }
                   5037: # ----------------------------------------------------------------- user.domain
                   5038:         } elsif ($space eq 'domain') {
1.218     albertel 5039:             return $udom;
1.48      www      5040: # ------------------------------------------------------------------- user.name
                   5041:         } elsif ($space eq 'name') {
1.218     albertel 5042:             return $uname;
1.48      www      5043: # ---------------------------------------------------- Any other user namespace
1.29      www      5044:         } else {
1.359     albertel 5045: 	    my %reply;
                   5046: 	    if (!$publicuser) {
                   5047: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5048: 	    }
                   5049: 	    return $reply{$qualifierrest};
1.48      www      5050:         }
1.236     www      5051:     } elsif ($realm eq 'query') {
                   5052: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5053:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5054: 						[$spacequalifierrest]);
1.620     albertel 5055: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5056:    } elsif ($realm eq 'request') {
1.48      www      5057: # ------------------------------------------------------------- request.browser
                   5058:         if ($space eq 'browser') {
1.430     www      5059: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5060: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5061: 		    return 1;
                   5062: 		} else {
                   5063: 		    return 0;
                   5064: 		}
                   5065: 	    } else {
1.620     albertel 5066: 		return $env{'browser.'.$qualifier};
1.430     www      5067: 	    }
1.57      www      5068: # ------------------------------------------------------------ request.filename
                   5069:         } else {
1.620     albertel 5070:             return $env{'request.'.$spacequalifierrest};
1.29      www      5071:         }
1.28      www      5072:     } elsif ($realm eq 'course') {
1.48      www      5073: # ---------------------------------------------------------- course.description
1.620     albertel 5074:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5075:     } elsif ($realm eq 'resource') {
1.165     www      5076: 
1.620     albertel 5077: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5078: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5079: 	}
1.693     albertel 5080: 
                   5081: 	if ($space eq 'title') {
                   5082: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5083: 	    return &gettitle($symbparm);
                   5084: 	}
                   5085: 	
                   5086: 	if ($space eq 'map') {
                   5087: 	    my ($map) = &decode_symb($symbparm);
                   5088: 	    return &symbread($map);
                   5089: 	}
                   5090: 
                   5091: 	my ($section, $group, @groups);
1.593     albertel 5092: 	my ($courselevelm,$courselevel);
1.539     albertel 5093: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5094: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5095: 
1.218     albertel 5096: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5097: 
1.60      www      5098: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5099: 	    my $symbp=$symbparm;
1.409     www      5100: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 5101: 
                   5102: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5103: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5104: 
1.620     albertel 5105: 	    if (($env{'user.name'} eq $uname) &&
                   5106: 		($env{'user.domain'} eq $udom)) {
                   5107: 		$section=$env{'request.course.sec'};
1.691     raeburn  5108:                 @groups=&sort_course_groups($env{'request.course.groups'},$courseid); 
1.684     raeburn  5109:                 if (@groups > 0) {
                   5110:                     @groups = sort(@groups);
                   5111:                 }
1.218     albertel 5112: 	    } else {
1.539     albertel 5113: 		if (! defined($usection)) {
1.551     albertel 5114: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5115: 		} else {
                   5116: 		    $section = $usection;
                   5117: 		}
1.684     raeburn  5118:                 my $grouplist = &get_users_groups($udom,$uname,$courseid);
                   5119:                 if ($grouplist) {
1.691     raeburn  5120:                     @groups=&sort_course_groups($grouplist,$courseid);
1.684     raeburn  5121:                 }
1.218     albertel 5122: 	    }
                   5123: 
                   5124: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5125: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5126: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5127: 
1.593     albertel 5128: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5129: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5130: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5131: 
1.60      www      5132: # ----------------------------------------------------------- first, check user
1.624     albertel 5133: 
                   5134: 	    my $userreply=&resdata($uname,$udom,'user',
                   5135: 				       ($courselevelr,$courselevelm,
                   5136: 					$courselevel));
                   5137: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5138: 
1.594     albertel 5139: # ------------------------------------------------ second, check some of course
1.684     raeburn  5140:             my $coursereply;
1.691     raeburn  5141:             if (@groups > 0) {
                   5142:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5143:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5144:                 if (defined($coursereply)) { return $coursereply; }
                   5145:             }
1.96      www      5146: 
1.684     raeburn  5147: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5148: 				     $env{'course.'.$courseid.'.domain'},
                   5149: 				     'course',
                   5150: 				     ($seclevelr,$seclevelm,$seclevel,
                   5151: 				      $courselevelr));
1.287     albertel 5152: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5153: 
1.60      www      5154: # ------------------------------------------------------ third, check map parms
1.218     albertel 5155: 	    my %parmhash=();
                   5156: 	    my $thisparm='';
                   5157: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5158: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5159: 		    &GDBM_READER(),0640)) {
1.218     albertel 5160: 		$thisparm=$parmhash{$symbparm};
                   5161: 		untie(%parmhash);
                   5162: 	    }
                   5163: 	    if ($thisparm) { return $thisparm; }
                   5164: 	}
1.594     albertel 5165: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5166: 
1.218     albertel 5167: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5168: 	my $filename;
                   5169: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5170: 	if ($symbparm) {
1.409     www      5171: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5172: 	} else {
1.620     albertel 5173: 	    $filename=$env{'request.filename'};
1.282     albertel 5174: 	}
                   5175: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5176: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5177: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5178: 	if (defined($metadata)) { return $metadata; }
1.142     www      5179: 
1.594     albertel 5180: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5181: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5182: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5183: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5184: 				     $env{'course.'.$courseid.'.domain'},
                   5185: 				     'course',
                   5186: 				     ($courselevelm,$courselevel));
1.593     albertel 5187: 	    if (defined($coursereply)) { return $coursereply; }
                   5188: 	}
1.145     www      5189: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5190: 	unless ($space eq '0') {
1.336     albertel 5191: 	    my @parts=split(/_/,$space);
                   5192: 	    my $id=pop(@parts);
                   5193: 	    my $part=join('_',@parts);
                   5194: 	    if ($part eq '') { $part='0'; }
                   5195: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5196: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5197: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5198: 	}
1.395     albertel 5199: 	if ($recurse) { return undef; }
                   5200: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5201: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5202: 
1.48      www      5203: # ---------------------------------------------------- Any other user namespace
                   5204:     } elsif ($realm eq 'environment') {
                   5205: # ----------------------------------------------------------------- environment
1.620     albertel 5206: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5207: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5208: 	} else {
                   5209: 	    my %returnhash=&userenvironment($udom,$uname,
                   5210: 					    $spacequalifierrest);
                   5211: 	    return $returnhash{$spacequalifierrest};
                   5212: 	}
1.28      www      5213:     } elsif ($realm eq 'system') {
1.48      www      5214: # ----------------------------------------------------------------- system.time
                   5215: 	if ($space eq 'time') {
                   5216: 	    return time;
                   5217:         }
1.696     albertel 5218:     } elsif ($realm eq 'server') {
                   5219: # ----------------------------------------------------------------- system.time
                   5220: 	if ($space eq 'name') {
                   5221: 	    return $ENV{'SERVER_NAME'};
                   5222:         }
1.28      www      5223:     }
1.48      www      5224:     return '';
1.61      www      5225: }
                   5226: 
1.691     raeburn  5227: sub check_group_parms {
                   5228:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5229:     my @groupitems = ();
                   5230:     my $resultitem;
                   5231:     my @levels = ($symbparm,$mapparm,$what);
                   5232:     foreach my $group (@{$groups}) {
                   5233:         foreach my $level (@levels) {
                   5234:              my $item = $courseid.'.['.$group.'].'.$level;
                   5235:              push(@groupitems,$item);
                   5236:         }
                   5237:     }
                   5238:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5239:                             $env{'course.'.$courseid.'.domain'},
                   5240:                                      'course',@groupitems);
                   5241:     return $coursereply;
                   5242: }
                   5243: 
                   5244: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
                   5245:     my ($grouplist,$courseid) = @_;
1.720   ! albertel 5246:     my @groups = sort(split(/:/,$grouplist));
1.691     raeburn  5247:     return @groups;
                   5248: }
                   5249: 
1.395     albertel 5250: sub packages_tab_default {
                   5251:     my ($uri,$varname)=@_;
                   5252:     my (undef,$part,$name)=split(/\./,$varname);
                   5253:     my $packages=&metadata($uri,'packages');
                   5254:     foreach my $package (split(/,/,$packages)) {
                   5255: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 5256: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5257: 	    return $packagetab{"$pack_type&$name&default"};
                   5258: 	}
1.585     albertel 5259: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5260: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5261: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5262: 	}
                   5263:     }
                   5264:     return undef;
                   5265: }
                   5266: 
1.334     albertel 5267: sub add_prefix_and_part {
                   5268:     my ($prefix,$part)=@_;
                   5269:     my $keyroot;
                   5270:     if (defined($prefix) && $prefix !~ /^__/) {
                   5271: 	# prefix that has a part already
                   5272: 	$keyroot=$prefix;
                   5273:     } elsif (defined($prefix)) {
                   5274: 	# prefix that is missing a part
                   5275: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5276:     } else {
                   5277: 	# no prefix at all
                   5278: 	if (defined($part)) { $keyroot='_'.$part; }
                   5279:     }
                   5280:     return $keyroot;
                   5281: }
                   5282: 
1.71      www      5283: # ---------------------------------------------------------------- Get metadata
                   5284: 
1.599     albertel 5285: my %metaentry;
1.71      www      5286: sub metadata {
1.176     www      5287:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5288:     $uri=&declutter($uri);
1.288     albertel 5289:     # if it is a non metadata possible uri return quickly
1.529     albertel 5290:     if (($uri eq '') || 
                   5291: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5292: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5293:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5294: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5295: 	return undef;
1.288     albertel 5296:     }
1.73      www      5297:     my $filename=$uri;
                   5298:     $uri=~s/\.meta$//;
1.172     www      5299: #
                   5300: # Is the metadata already cached?
1.177     www      5301: # Look at timestamp of caching
1.172     www      5302: # Everything is cached by the main uri, libraries are never directly cached
                   5303: #
1.428     albertel 5304:     if (!defined($liburi)) {
1.599     albertel 5305: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5306: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5307:     }
                   5308:     {
1.172     www      5309: #
                   5310: # Is this a recursive call for a library?
                   5311: #
1.599     albertel 5312: #	if (! exists($metacache{$uri})) {
                   5313: #	    $metacache{$uri}={};
                   5314: #	}
1.171     www      5315:         if ($liburi) {
                   5316: 	    $liburi=&declutter($liburi);
                   5317:             $filename=$liburi;
1.401     bowersj2 5318:         } else {
1.599     albertel 5319: 	    &devalidate_cache_new('meta',$uri);
                   5320: 	    undef(%metaentry);
1.401     bowersj2 5321: 	}
1.140     www      5322:         my %metathesekeys=();
1.73      www      5323:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5324: 	my $metastring;
1.609     banghart 5325: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 5326: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5327: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5328: 	    $metastring=&getfile($file);
1.489     albertel 5329: 	}
1.208     albertel 5330:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5331:         my $token;
1.140     www      5332:         undef %metathesekeys;
1.71      www      5333:         while ($token=$parser->get_token) {
1.339     albertel 5334: 	    if ($token->[0] eq 'S') {
                   5335: 		if (defined($token->[2]->{'package'})) {
1.172     www      5336: #
                   5337: # This is a package - get package info
                   5338: #
1.339     albertel 5339: 		    my $package=$token->[2]->{'package'};
                   5340: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5341: 		    if (defined($token->[2]->{'id'})) { 
                   5342: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5343: 		    }
1.599     albertel 5344: 		    if ($metaentry{':packages'}) {
                   5345: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5346: 		    } else {
1.599     albertel 5347: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5348: 		    }
1.613     albertel 5349: 		    foreach (sort keys %packagetab) {
1.432     albertel 5350: 			my $part=$keyroot;
                   5351: 			$part=~s/^\_//;
                   5352: 			if ($_=~/^\Q$package\E\&/ || 
                   5353: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 5354: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 5355: 			    # ignore package.tab specified default values
                   5356:                             # here &package_tab_default() will fetch those
                   5357: 			    if ($subp eq 'default') { next; }
1.339     albertel 5358: 			    my $value=$packagetab{$_};
1.432     albertel 5359: 			    my $unikey;
                   5360: 			    if ($pack =~ /_0$/) {
                   5361: 				$unikey='parameter_0_'.$name;
                   5362: 				$part=0;
                   5363: 			    } else {
                   5364: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5365: 			    }
1.339     albertel 5366: 			    if ($subp eq 'display') {
                   5367: 				$value.=' [Part: '.$part.']';
                   5368: 			    }
1.599     albertel 5369: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5370: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5371: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5372: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5373: 			    }
1.599     albertel 5374: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5375: 				$metaentry{':'.$unikey}=
                   5376: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5377: 			    }
1.339     albertel 5378: 			}
                   5379: 		    }
                   5380: 		} else {
1.172     www      5381: #
                   5382: # This is not a package - some other kind of start tag
1.339     albertel 5383: #
                   5384: 		    my $entry=$token->[1];
                   5385: 		    my $unikey;
                   5386: 		    if ($entry eq 'import') {
                   5387: 			$unikey='';
                   5388: 		    } else {
                   5389: 			$unikey=$entry;
                   5390: 		    }
                   5391: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5392: 
                   5393: 		    if (defined($token->[2]->{'id'})) { 
                   5394: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5395: 		    }
1.175     www      5396: 
1.339     albertel 5397: 		    if ($entry eq 'import') {
1.175     www      5398: #
                   5399: # Importing a library here
1.339     albertel 5400: #
                   5401: 			if ($depthcount<20) {
                   5402: 			    my $location=$parser->get_text('/import');
                   5403: 			    my $dir=$filename;
                   5404: 			    $dir=~s|[^/]*$||;
                   5405: 			    $location=&filelocation($dir,$location);
                   5406: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5407: 							       $location,$unikey,
                   5408: 							       $depthcount+1)))) {
1.599     albertel 5409: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 5410: 				$metathesekeys{$_}=1;
                   5411: 			    }
                   5412: 			}
                   5413: 		    } else { 
                   5414: 			
                   5415: 			if (defined($token->[2]->{'name'})) { 
                   5416: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5417: 			}
                   5418: 			$metathesekeys{$unikey}=1;
                   5419: 			foreach (@{$token->[3]}) {
1.599     albertel 5420: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 5421: 			}
                   5422: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5423: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5424: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5425: 		 # only ws inside the tag, and not in default, so use default
                   5426: 		 # as value
1.599     albertel 5427: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5428: 			} else {
1.321     albertel 5429: 		  # either something interesting inside the tag or default
                   5430:                   # uninteresting
1.599     albertel 5431: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5432: 			}
1.172     www      5433: # end of not-a-package not-a-library import
1.339     albertel 5434: 		    }
1.172     www      5435: # end of not-a-package start tag
1.339     albertel 5436: 		}
1.172     www      5437: # the next is the end of "start tag"
1.339     albertel 5438: 	    }
                   5439: 	}
1.483     albertel 5440: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   5441: 	foreach my $key (sort(keys(%packagetab))) {
                   5442: 	    #no specific packages #how's our extension
                   5443: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 5444: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 5445: 					 \%metathesekeys);
                   5446: 	}
1.599     albertel 5447: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 5448: 	    foreach my $key (sort(keys(%packagetab))) {
                   5449: 		#no specific packages well let's get default then
                   5450: 		if ($key!~/^default&/) { next; }
1.488     albertel 5451: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 5452: 					     \%metathesekeys);
                   5453: 	    }
                   5454: 	}
1.338     www      5455: # are there custom rights to evaluate
1.599     albertel 5456: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 5457: 
1.338     www      5458:     #
                   5459:     # Importing a rights file here
1.339     albertel 5460:     #
                   5461: 	    unless ($depthcount) {
1.599     albertel 5462: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 5463: 		my $dir=$filename;
                   5464: 		$dir=~s|[^/]*$||;
                   5465: 		$location=&filelocation($dir,$location);
                   5466: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   5467: 						   $location,'_rights',
                   5468: 						   $depthcount+1)))) {
1.599     albertel 5469: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 5470: 		    $metathesekeys{$_}=1;
                   5471: 		}
                   5472: 	    }
                   5473: 	}
1.599     albertel 5474: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   5475: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   5476: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 5477: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      5478: # this is the end of "was not already recently cached
1.71      www      5479:     }
1.599     albertel 5480:     return $metaentry{':'.$what};
1.261     albertel 5481: }
                   5482: 
1.488     albertel 5483: sub metadata_create_package_def {
1.483     albertel 5484:     my ($uri,$key,$package,$metathesekeys)=@_;
                   5485:     my ($pack,$name,$subp)=split(/\&/,$key);
                   5486:     if ($subp eq 'default') { next; }
                   5487:     
1.599     albertel 5488:     if (defined($metaentry{':packages'})) {
                   5489: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 5490:     } else {
1.599     albertel 5491: 	$metaentry{':packages'}=$package;
1.483     albertel 5492:     }
                   5493:     my $value=$packagetab{$key};
                   5494:     my $unikey;
                   5495:     $unikey='parameter_0_'.$name;
1.599     albertel 5496:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 5497:     $$metathesekeys{$unikey}=1;
1.599     albertel 5498:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5499: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 5500:     }
1.599     albertel 5501:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   5502: 	$metaentry{':'.$unikey}=
                   5503: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 5504:     }
                   5505: }
                   5506: 
1.261     albertel 5507: sub metadata_generate_part0 {
                   5508:     my ($metadata,$metacache,$uri) = @_;
                   5509:     my %allnames;
                   5510:     foreach my $metakey (sort keys %$metadata) {
                   5511: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 5512: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   5513: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 5514: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 5515: 	    $allnames{$name}=$part;
                   5516: 	  }
                   5517: 	}
                   5518:     }
                   5519:     foreach my $name (keys(%allnames)) {
                   5520:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 5521:       my $key=":parameter_0_$name";
1.261     albertel 5522:       $$metacache{"$key.part"}='0';
                   5523:       $$metacache{"$key.name"}=$name;
1.428     albertel 5524:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 5525: 					   $allnames{$name}.'_'.$name.
                   5526: 					   '.type'};
1.428     albertel 5527:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 5528: 			     '.display'};
1.644     www      5529:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 5530:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 5531:       $$metacache{"$key.display"}=$olddis;
                   5532:     }
1.71      www      5533: }
                   5534: 
1.301     www      5535: # ------------------------------------------------- Get the title of a resource
                   5536: 
                   5537: sub gettitle {
                   5538:     my $urlsymb=shift;
                   5539:     my $symb=&symbread($urlsymb);
1.534     albertel 5540:     if ($symb) {
1.620     albertel 5541: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 5542: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 5543: 	if (defined($cached)) { 
                   5544: 	    return $result;
                   5545: 	}
1.534     albertel 5546: 	my ($map,$resid,$url)=&decode_symb($symb);
                   5547: 	my $title='';
                   5548: 	my %bighash;
1.620     albertel 5549: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 5550: 		&GDBM_READER(),0640)) {
                   5551: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   5552: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   5553: 	    untie %bighash;
                   5554: 	}
                   5555: 	$title=~s/\&colon\;/\:/gs;
                   5556: 	if ($title) {
1.599     albertel 5557: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 5558: 	}
                   5559: 	$urlsymb=$url;
                   5560:     }
                   5561:     my $title=&metadata($urlsymb,'title');
                   5562:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   5563:     return $title;
1.301     www      5564: }
1.613     albertel 5565: 
1.614     albertel 5566: sub get_slot {
                   5567:     my ($which,$cnum,$cdom)=@_;
                   5568:     if (!$cnum || !$cdom) {
                   5569: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 5570: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   5571: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 5572:     }
1.703     albertel 5573:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   5574:     my %slotinfo;
                   5575:     if (exists($remembered{$key})) {
                   5576: 	$slotinfo{$which} = $remembered{$key};
                   5577:     } else {
                   5578: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   5579: 	&Apache::lonhomework::showhash(%slotinfo);
                   5580: 	my ($tmp)=keys(%slotinfo);
                   5581: 	if ($tmp=~/^error:/) { return (); }
                   5582: 	$remembered{$key} = $slotinfo{$which};
                   5583:     }
1.616     albertel 5584:     if (ref($slotinfo{$which}) eq 'HASH') {
                   5585: 	return %{$slotinfo{$which}};
                   5586:     }
                   5587:     return $slotinfo{$which};
1.614     albertel 5588: }
1.31      www      5589: # ------------------------------------------------- Update symbolic store links
                   5590: 
                   5591: sub symblist {
                   5592:     my ($mapname,%newhash)=@_;
1.438     www      5593:     $mapname=&deversion(&declutter($mapname));
1.31      www      5594:     my %hash;
1.620     albertel 5595:     if (($env{'request.course.fn'}) && (%newhash)) {
                   5596:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5597:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 5598: 	    foreach my $url (keys %newhash) {
                   5599: 		next if ($url eq 'last_known'
                   5600: 			 && $env{'form.no_update_last_known'});
                   5601: 		$hash{declutter($url)}=&encode_symb($mapname,
                   5602: 						    $newhash{$url}->[1],
                   5603: 						    $newhash{$url}->[0]);
1.191     harris41 5604:             }
1.31      www      5605:             if (untie(%hash)) {
                   5606: 		return 'ok';
                   5607:             }
                   5608:         }
                   5609:     }
                   5610:     return 'error';
1.212     www      5611: }
                   5612: 
                   5613: # --------------------------------------------------------------- Verify a symb
                   5614: 
                   5615: sub symbverify {
1.510     www      5616:     my ($symb,$thisurl)=@_;
                   5617:     my $thisfn=$thisurl;
                   5618: # wrapper not part of symbs
                   5619:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 5620:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      5621:     $thisfn=&declutter($thisfn);
1.215     www      5622: # direct jump to resource in page or to a sequence - will construct own symbs
                   5623:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   5624: # check URL part
1.409     www      5625:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      5626: 
1.431     www      5627:     unless ($url eq $thisfn) { return 0; }
1.213     www      5628: 
1.216     www      5629:     $symb=&symbclean($symb);
1.510     www      5630:     $thisurl=&deversion($thisurl);
1.439     www      5631:     $thisfn=&deversion($thisfn);
1.213     www      5632: 
                   5633:     my %bighash;
                   5634:     my $okay=0;
1.431     www      5635: 
1.620     albertel 5636:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5637:                             &GDBM_READER(),0640)) {
1.510     www      5638:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      5639:         unless ($ids) { 
1.510     www      5640:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      5641:         }
                   5642:         if ($ids) {
                   5643: # ------------------------------------------------------------------- Has ID(s)
                   5644: 	    foreach (split(/\,/,$ids)) {
1.644     www      5645: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      5646:                if (
                   5647:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   5648:    eq $symb) { 
1.620     albertel 5649: 		   if (($env{'request.role.adv'}) ||
                   5650: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 5651: 		       $okay=1; 
                   5652: 		   }
                   5653: 	       }
1.216     www      5654: 	   }
                   5655:         }
1.213     www      5656: 	untie(%bighash);
                   5657:     }
                   5658:     return $okay;
1.31      www      5659: }
                   5660: 
1.210     www      5661: # --------------------------------------------------------------- Clean-up symb
                   5662: 
                   5663: sub symbclean {
                   5664:     my $symb=shift;
1.568     albertel 5665:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      5666: # remove version from map
                   5667:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      5668: 
1.210     www      5669: # remove version from URL
                   5670:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      5671: 
1.507     www      5672: # remove wrapper
                   5673: 
1.510     www      5674:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 5675:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      5676:     return $symb;
1.409     www      5677: }
                   5678: 
                   5679: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 5680: 
                   5681: sub encode_symb {
                   5682:     my ($map,$resid,$url)=@_;
                   5683:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   5684: }
1.409     www      5685: 
                   5686: sub decode_symb {
1.568     albertel 5687:     my $symb=shift;
                   5688:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   5689:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      5690:     return (&fixversion($map),$resid,&fixversion($url));
                   5691: }
                   5692: 
                   5693: sub fixversion {
                   5694:     my $fn=shift;
1.609     banghart 5695:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      5696:     my %bighash;
                   5697:     my $uri=&clutter($fn);
1.620     albertel 5698:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      5699: # is this cached?
1.599     albertel 5700:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      5701:     if (defined($cached)) { return $result; }
                   5702: # unfortunately not cached, or expired
1.620     albertel 5703:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      5704: 	    &GDBM_READER(),0640)) {
                   5705:  	if ($bighash{'version_'.$uri}) {
                   5706:  	    my $version=$bighash{'version_'.$uri};
1.444     www      5707:  	    unless (($version eq 'mostrecent') || 
                   5708: 		    ($version==&getversion($uri))) {
1.440     www      5709:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   5710:  	    }
                   5711:  	}
                   5712:  	untie %bighash;
1.413     www      5713:     }
1.599     albertel 5714:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      5715: }
                   5716: 
                   5717: sub deversion {
                   5718:     my $url=shift;
                   5719:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   5720:     return $url;
1.210     www      5721: }
                   5722: 
1.31      www      5723: # ------------------------------------------------------ Return symb list entry
                   5724: 
                   5725: sub symbread {
1.249     www      5726:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 5727:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 5728:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      5729: # no filename provided? try from environment
1.44      www      5730:     unless ($thisfn) {
1.620     albertel 5731:         if ($env{'request.symb'}) {
                   5732: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 5733: 	}
1.620     albertel 5734: 	$thisfn=$env{'request.filename'};
1.44      www      5735:     }
1.569     albertel 5736:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      5737: # is that filename actually a symb? Verify, clean, and return
                   5738:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 5739: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 5740: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 5741: 	}
1.242     www      5742:     }
1.44      www      5743:     $thisfn=declutter($thisfn);
1.31      www      5744:     my %hash;
1.37      www      5745:     my %bighash;
                   5746:     my $syval='';
1.620     albertel 5747:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  5748:         my $targetfn = $thisfn;
1.609     banghart 5749:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  5750:             $targetfn = 'adm/wrapper/'.$thisfn;
                   5751:         }
1.687     albertel 5752: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   5753: 	    $targetfn=$1;
                   5754: 	}
1.620     albertel 5755:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 5756:                       &GDBM_READER(),0640)) {
1.481     raeburn  5757: 	    $syval=$hash{$targetfn};
1.37      www      5758:             untie(%hash);
                   5759:         }
                   5760: # ---------------------------------------------------------- There was an entry
                   5761:         if ($syval) {
1.601     albertel 5762: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 5763: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 5764: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 5765: 		    #return $env{$cache_str}='';
1.601     albertel 5766: 		#}    
                   5767: 		#$syval.=$1;
                   5768: 	    #}
1.37      www      5769:         } else {
                   5770: # ------------------------------------------------------- Was not in symb table
1.620     albertel 5771:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 5772:                             &GDBM_READER(),0640)) {
1.37      www      5773: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      5774:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      5775:               unless ($ids) { 
                   5776:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      5777:               }
                   5778:               unless ($ids) {
                   5779: # alias?
                   5780: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      5781:               }
1.37      www      5782:               if ($ids) {
                   5783: # ------------------------------------------------------------------- Has ID(s)
                   5784:                  my @possibilities=split(/\,/,$ids);
1.39      www      5785:                  if ($#possibilities==0) {
                   5786: # ----------------------------------------------- There is only one possibility
1.37      www      5787: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 5788: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5789: 						    $resid,$thisfn);
1.249     www      5790:                  } elsif (!$donotrecurse) {
1.39      www      5791: # ------------------------------------------ There is more than one possibility
                   5792:                      my $realpossible=0;
1.191     harris41 5793:                      foreach (@possibilities) {
1.39      www      5794: 			 my $file=$bighash{'src_'.$_};
                   5795:                          if (&allowed('bre',$file)) {
                   5796:          		    my ($mapid,$resid)=split(/\./,$_);
                   5797:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   5798: 				$realpossible++;
1.626     albertel 5799:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   5800: 						    $resid,$thisfn);
1.39      www      5801:                             }
                   5802: 			 }
1.191     harris41 5803:                      }
1.39      www      5804: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      5805:                  } else {
                   5806:                      $syval='';
1.37      www      5807:                  }
                   5808: 	      }
                   5809:               untie(%bighash)
1.481     raeburn  5810:            }
1.31      www      5811:         }
1.62      www      5812:         if ($syval) {
1.620     albertel 5813: 	    return $env{$cache_str}=$syval;
1.62      www      5814:         }
1.31      www      5815:     }
1.44      www      5816:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 5817:     return $env{$cache_str}='';
1.31      www      5818: }
                   5819: 
                   5820: # ---------------------------------------------------------- Return random seed
                   5821: 
1.32      www      5822: sub numval {
                   5823:     my $txt=shift;
                   5824:     $txt=~tr/A-J/0-9/;
                   5825:     $txt=~tr/a-j/0-9/;
                   5826:     $txt=~tr/K-T/0-9/;
                   5827:     $txt=~tr/k-t/0-9/;
                   5828:     $txt=~tr/U-Z/0-5/;
                   5829:     $txt=~tr/u-z/0-5/;
                   5830:     $txt=~s/\D//g;
1.564     albertel 5831:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      5832:     return int($txt);
1.368     albertel 5833: }
                   5834: 
1.484     albertel 5835: sub numval2 {
                   5836:     my $txt=shift;
                   5837:     $txt=~tr/A-J/0-9/;
                   5838:     $txt=~tr/a-j/0-9/;
                   5839:     $txt=~tr/K-T/0-9/;
                   5840:     $txt=~tr/k-t/0-9/;
                   5841:     $txt=~tr/U-Z/0-5/;
                   5842:     $txt=~tr/u-z/0-5/;
                   5843:     $txt=~s/\D//g;
                   5844:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5845:     my $total;
                   5846:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5847:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5848:     return int($total);
                   5849: }
                   5850: 
1.575     albertel 5851: sub numval3 {
                   5852:     use integer;
                   5853:     my $txt=shift;
                   5854:     $txt=~tr/A-J/0-9/;
                   5855:     $txt=~tr/a-j/0-9/;
                   5856:     $txt=~tr/K-T/0-9/;
                   5857:     $txt=~tr/k-t/0-9/;
                   5858:     $txt=~tr/U-Z/0-5/;
                   5859:     $txt=~tr/u-z/0-5/;
                   5860:     $txt=~s/\D//g;
                   5861:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5862:     my $total;
                   5863:     foreach my $val (@txts) { $total+=$val; }
                   5864:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5865:     return $total;
                   5866: }
                   5867: 
1.675     albertel 5868: sub digest {
                   5869:     my ($data)=@_;
                   5870:     my $digest=&Digest::MD5::md5($data);
                   5871:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   5872:     my ($e,$f);
                   5873:     {
                   5874:         use integer;
                   5875:         $e=($a+$b);
                   5876:         $f=($c+$d);
                   5877:         if ($_64bit) {
                   5878:             $e=(($e<<32)>>32);
                   5879:             $f=(($f<<32)>>32);
                   5880:         }
                   5881:     }
                   5882:     if (wantarray) {
                   5883: 	return ($e,$f);
                   5884:     } else {
                   5885: 	my $g;
                   5886: 	{
                   5887: 	    use integer;
                   5888: 	    $g=($e+$f);
                   5889: 	    if ($_64bit) {
                   5890: 		$g=(($g<<32)>>32);
                   5891: 	    }
                   5892: 	}
                   5893: 	return $g;
                   5894:     }
                   5895: }
                   5896: 
1.368     albertel 5897: sub latest_rnd_algorithm_id {
1.675     albertel 5898:     return '64bit5';
1.366     albertel 5899: }
1.32      www      5900: 
1.503     albertel 5901: sub get_rand_alg {
                   5902:     my ($courseid)=@_;
                   5903:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   5904:     if ($courseid) {
1.620     albertel 5905: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 5906:     }
                   5907:     return &latest_rnd_algorithm_id();
                   5908: }
                   5909: 
1.562     albertel 5910: sub validCODE {
                   5911:     my ($CODE)=@_;
                   5912:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5913:     return 0;
                   5914: }
                   5915: 
1.491     albertel 5916: sub getCODE {
1.620     albertel 5917:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 5918:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   5919: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   5920: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5921: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5922:     }
                   5923:     return undef;
                   5924: }
                   5925: 
1.31      www      5926: sub rndseed {
1.155     albertel 5927:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5928: 
                   5929:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5930:     if (!$symb) {
1.366     albertel 5931: 	unless ($symb=$wsymb) { return time; }
                   5932:     }
                   5933:     if (!$courseid) { $courseid=$wcourseid; }
                   5934:     if (!$domain) { $domain=$wdomain; }
                   5935:     if (!$username) { $username=$wusername }
1.503     albertel 5936:     my $which=&get_rand_alg();
1.491     albertel 5937:     if (defined(&getCODE())) {
1.675     albertel 5938: 	if ($which eq '64bit5') {
                   5939: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   5940: 	} elsif ($which eq '64bit4') {
1.575     albertel 5941: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5942: 	} else {
                   5943: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5944: 	}
1.675     albertel 5945:     } elsif ($which eq '64bit5') {
                   5946: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 5947:     } elsif ($which eq '64bit4') {
                   5948: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 5949:     } elsif ($which eq '64bit3') {
                   5950: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 5951:     } elsif ($which eq '64bit2') {
                   5952: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 5953:     } elsif ($which eq '64bit') {
                   5954: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   5955:     }
                   5956:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   5957: }
                   5958: 
                   5959: sub rndseed_32bit {
                   5960:     my ($symb,$courseid,$domain,$username)=@_;
                   5961:     {
                   5962: 	use integer;
                   5963: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   5964: 	my $symbseed=numval($symb) << 22;
                   5965: 	my $namechck=unpack("%32C*",$username) << 17;
                   5966: 	my $nameseed=numval($username) << 12;
                   5967: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   5968: 	my $courseseed=unpack("%32C*",$courseid);
                   5969: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   5970: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5971: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5972: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 5973: 	return $num;
                   5974:     }
                   5975: }
                   5976: 
                   5977: sub rndseed_64bit {
                   5978:     my ($symb,$courseid,$domain,$username)=@_;
                   5979:     {
                   5980: 	use integer;
                   5981: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   5982: 	my $symbseed=numval($symb) << 10;
                   5983: 	my $namechck=unpack("%32S*",$username);
                   5984: 	
                   5985: 	my $nameseed=numval($username) << 21;
                   5986: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   5987: 	my $courseseed=unpack("%32S*",$courseid);
                   5988: 	
                   5989: 	my $num1=$symbchck+$symbseed+$namechck;
                   5990: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5991: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5992: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5993: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5994: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 5995: 	return "$num1,$num2";
1.155     albertel 5996:     }
1.366     albertel 5997: }
                   5998: 
1.443     albertel 5999: sub rndseed_64bit2 {
                   6000:     my ($symb,$courseid,$domain,$username)=@_;
                   6001:     {
                   6002: 	use integer;
                   6003: 	# strings need to be an even # of cahracters long, it it is odd the
                   6004:         # last characters gets thrown away
                   6005: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6006: 	my $symbseed=numval($symb) << 10;
                   6007: 	my $namechck=unpack("%32S*",$username.' ');
                   6008: 	
                   6009: 	my $nameseed=numval($username) << 21;
1.501     albertel 6010: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6011: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6012: 	
                   6013: 	my $num1=$symbchck+$symbseed+$namechck;
                   6014: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6015: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6016: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6017: 	return "$num1,$num2";
                   6018:     }
                   6019: }
                   6020: 
                   6021: sub rndseed_64bit3 {
                   6022:     my ($symb,$courseid,$domain,$username)=@_;
                   6023:     {
                   6024: 	use integer;
                   6025: 	# strings need to be an even # of cahracters long, it it is odd the
                   6026:         # last characters gets thrown away
                   6027: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6028: 	my $symbseed=numval2($symb) << 10;
                   6029: 	my $namechck=unpack("%32S*",$username.' ');
                   6030: 	
                   6031: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6032: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6033: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6034: 	
                   6035: 	my $num1=$symbchck+$symbseed+$namechck;
                   6036: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6037: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6038: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6039: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6040: 	
1.503     albertel 6041: 	return "$num1:$num2";
1.443     albertel 6042:     }
                   6043: }
                   6044: 
1.575     albertel 6045: sub rndseed_64bit4 {
                   6046:     my ($symb,$courseid,$domain,$username)=@_;
                   6047:     {
                   6048: 	use integer;
                   6049: 	# strings need to be an even # of cahracters long, it it is odd the
                   6050:         # last characters gets thrown away
                   6051: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6052: 	my $symbseed=numval3($symb) << 10;
                   6053: 	my $namechck=unpack("%32S*",$username.' ');
                   6054: 	
                   6055: 	my $nameseed=numval3($username) << 21;
                   6056: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6057: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6058: 	
                   6059: 	my $num1=$symbchck+$symbseed+$namechck;
                   6060: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6061: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6062: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6063: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6064: 	
                   6065: 	return "$num1:$num2";
                   6066:     }
                   6067: }
                   6068: 
1.675     albertel 6069: sub rndseed_64bit5 {
                   6070:     my ($symb,$courseid,$domain,$username)=@_;
                   6071:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6072:     return "$num1:$num2";
                   6073: }
                   6074: 
1.366     albertel 6075: sub rndseed_CODE_64bit {
                   6076:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6077:     {
1.366     albertel 6078: 	use integer;
1.443     albertel 6079: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6080: 	my $symbseed=numval2($symb);
1.491     albertel 6081: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6082: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6083: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6084: 	my $num1=$symbseed+$CODEchck;
                   6085: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6086: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6087: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6088: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6089: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6090: 	return "$num1:$num2";
1.366     albertel 6091:     }
                   6092: }
                   6093: 
1.575     albertel 6094: sub rndseed_CODE_64bit4 {
                   6095:     my ($symb,$courseid,$domain,$username)=@_;
                   6096:     {
                   6097: 	use integer;
                   6098: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6099: 	my $symbseed=numval3($symb);
                   6100: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6101: 	my $CODEseed=numval3(&getCODE());
                   6102: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6103: 	my $num1=$symbseed+$CODEchck;
                   6104: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6105: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6106: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6107: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6108: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6109: 	return "$num1:$num2";
                   6110:     }
                   6111: }
                   6112: 
1.675     albertel 6113: sub rndseed_CODE_64bit5 {
                   6114:     my ($symb,$courseid,$domain,$username)=@_;
                   6115:     my $code = &getCODE();
                   6116:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6117:     return "$num1:$num2";
                   6118: }
                   6119: 
1.366     albertel 6120: sub setup_random_from_rndseed {
                   6121:     my ($rndseed)=@_;
1.503     albertel 6122:     if ($rndseed =~/([,:])/) {
                   6123: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6124: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6125:     } else {
                   6126: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6127:     }
1.36      albertel 6128: }
                   6129: 
1.474     albertel 6130: sub latest_receipt_algorithm_id {
                   6131:     return 'receipt2';
                   6132: }
                   6133: 
1.480     www      6134: sub recunique {
                   6135:     my $fucourseid=shift;
                   6136:     my $unique;
1.620     albertel 6137:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6138: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6139:     } else {
                   6140: 	$unique=$perlvar{'lonReceipt'};
                   6141:     }
                   6142:     return unpack("%32C*",$unique);
                   6143: }
                   6144: 
                   6145: sub recprefix {
                   6146:     my $fucourseid=shift;
                   6147:     my $prefix;
1.620     albertel 6148:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6149: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6150:     } else {
                   6151: 	$prefix=$perlvar{'lonHostID'};
                   6152:     }
                   6153:     return unpack("%32C*",$prefix);
                   6154: }
                   6155: 
1.76      www      6156: sub ireceipt {
1.474     albertel 6157:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6158:     my $cuname=unpack("%32C*",$funame);
                   6159:     my $cudom=unpack("%32C*",$fudom);
                   6160:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6161:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6162:     my $cunique=&recunique($fucourseid);
1.474     albertel 6163:     my $cpart=unpack("%32S*",$part);
1.480     www      6164:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6165:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6166: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6167: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6168: 			       " and ".($cpart%$cudom));
                   6169: 			       
                   6170: 	$return.= ($cunique%$cuname+
                   6171: 		   $cunique%$cudom+
                   6172: 		   $cusymb%$cuname+
                   6173: 		   $cusymb%$cudom+
                   6174: 		   $cucourseid%$cuname+
                   6175: 		   $cucourseid%$cudom+
                   6176: 		   $cpart%$cuname+
                   6177: 		   $cpart%$cudom);
                   6178:     } else {
                   6179: 	$return.= ($cunique%$cuname+
                   6180: 		   $cunique%$cudom+
                   6181: 		   $cusymb%$cuname+
                   6182: 		   $cusymb%$cudom+
                   6183: 		   $cucourseid%$cuname+
                   6184: 		   $cucourseid%$cudom);
                   6185:     }
                   6186:     return $return;
1.76      www      6187: }
                   6188: 
                   6189: sub receipt {
1.474     albertel 6190:     my ($part)=@_;
                   6191:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6192:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6193: }
1.260     ng       6194: 
1.36      albertel 6195: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6196: # returns either the contents of the file or 
                   6197: # -1 if the file doesn't exist
1.481     raeburn  6198: #
                   6199: # if the target is a file that was uploaded via DOCS, 
                   6200: # a check will be made to see if a current copy exists on the local server,
                   6201: # if it does this will be served, otherwise a copy will be retrieved from
                   6202: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6203: # the local server.   
1.472     albertel 6204: 
1.36      albertel 6205: sub getfile {
1.538     albertel 6206:     my ($file) = @_;
1.609     banghart 6207:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6208:     &repcopy($file);
                   6209:     return &readfile($file);
                   6210: }
                   6211: 
                   6212: sub repcopy_userfile {
                   6213:     my ($file)=@_;
1.609     banghart 6214:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6215:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6216:     my ($cdom,$cnum,$filename) = 
                   6217: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6218:     my ($info,$rtncode);
                   6219:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6220:     if (-e "$file") {
                   6221: 	my @fileinfo = stat($file);
                   6222: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6223: 	if ($lwpresp ne 'ok') {
                   6224: 	    if ($rtncode eq '404') {
1.538     albertel 6225: 		unlink($file);
1.482     albertel 6226: 	    }
1.517     albertel 6227: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6228: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6229: 	    #my $response=$ua->request($request);
                   6230: 	    #if ($response->is_success()) {
                   6231: 	#	return $response->content;
                   6232: 	#    } else {
                   6233: 	#	return -1;
                   6234: 	#    }
1.482     albertel 6235: 	    return -1;
                   6236: 	}
                   6237: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6238: 	    return 'ok';
1.482     albertel 6239: 	}
                   6240: 	$info = '';
1.538     albertel 6241: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6242: 	if ($lwpresp ne 'ok') {
                   6243: 	    return -1;
                   6244: 	}
                   6245:     } else {
1.538     albertel 6246: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6247: 	if ($lwpresp ne 'ok') {
1.517     albertel 6248: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6249: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6250: 	    my $response=$ua->request($request);
                   6251: 	    if ($response->is_success()) {
1.538     albertel 6252: 		$info=$response->content;
1.517     albertel 6253: 	    } else {
                   6254: 		return -1;
                   6255: 	    }
1.482     albertel 6256: 	}
                   6257: 	my @parts = ($cdom,$cnum); 
                   6258: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6259: 	    push @parts, split(/\//,$1);
1.518     albertel 6260: 	}
1.538     albertel 6261: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6262: 	foreach my $part (@parts) {
                   6263: 	    $path .= '/'.$part;
                   6264: 	    if (!-e $path) {
                   6265: 		mkdir($path,0770);
                   6266: 	    }
                   6267: 	}
                   6268:     }
1.538     albertel 6269:     open(FILE,">$file");
1.482     albertel 6270:     print FILE $info;
                   6271:     close(FILE);
1.607     raeburn  6272:     return 'ok';
1.481     raeburn  6273: }
                   6274: 
1.517     albertel 6275: sub tokenwrapper {
                   6276:     my $uri=shift;
1.552     albertel 6277:     $uri=~s|^http\://([^/]+)||;
                   6278:     $uri=~s|^/||;
1.620     albertel 6279:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6280:     my $token=$1;
1.552     albertel 6281:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6282:     if ($udom && $uname && $file) {
                   6283: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6284:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6285:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6286:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6287:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6288:     } else {
                   6289:         return '/adm/notfound.html';
                   6290:     }
                   6291: }
                   6292: 
1.481     raeburn  6293: sub getuploaded {
                   6294:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6295:     $uri=~s/^\///;
                   6296:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6297:     my $ua=new LWP::UserAgent;
                   6298:     my $request=new HTTP::Request($reqtype,$uri);
                   6299:     my $response=$ua->request($request);
                   6300:     $$rtncode = $response->code;
1.482     albertel 6301:     if (! $response->is_success()) {
                   6302: 	return 'failed';
                   6303:     }      
                   6304:     if ($reqtype eq 'HEAD') {
1.486     www      6305: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6306:     } elsif ($reqtype eq 'GET') {
                   6307: 	$$info = $response->content;
1.472     albertel 6308:     }
1.482     albertel 6309:     return 'ok';
1.36      albertel 6310: }
                   6311: 
1.481     raeburn  6312: sub readfile {
                   6313:     my $file = shift;
                   6314:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6315:     my $fh;
                   6316:     open($fh,"<$file");
                   6317:     my $a='';
                   6318:     while (<$fh>) { $a .=$_; }
                   6319:     return $a;
                   6320: }
                   6321: 
1.36      albertel 6322: sub filelocation {
1.590     banghart 6323:     my ($dir,$file) = @_;
                   6324:     my $location;
                   6325:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6326: 
                   6327:     if ($file =~ m-^/adm/-) {
                   6328: 	$file=~s-^/adm/wrapper/-/-;
                   6329: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6330:     }
1.590     banghart 6331:     if ($file=~m:^/~:) { # is a contruction space reference
                   6332:         $location = $file;
                   6333:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6334:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6335: 	# is a correct contruction space reference
                   6336:         $location = $file;
1.609     banghart 6337:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6338:         my ($udom,$uname,$filename)=
1.609     banghart 6339:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6340:         my $home=&homeserver($uname,$udom);
                   6341:         my $is_me=0;
                   6342:         my @ids=&current_machine_ids();
                   6343:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6344:         if ($is_me) {
                   6345:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   6346:   	      '/userfiles/'.$filename;
                   6347:         } else {
                   6348:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6349:   	      $udom.'/'.$uname.'/'.$filename;
                   6350:         }
                   6351:     } else {
                   6352:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6353:         $file=~s:^/res/:/:;
                   6354:         if ( !( $file =~ m:^/:) ) {
                   6355:             $location = $dir. '/'.$file;
                   6356:         } else {
                   6357:             $location = '/home/httpd/html/res'.$file;
                   6358:         }
1.59      albertel 6359:     }
1.590     banghart 6360:     $location=~s://+:/:g; # remove duplicate /
                   6361:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6362:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6363:     return $location;
1.46      www      6364: }
1.36      albertel 6365: 
1.46      www      6366: sub hreflocation {
                   6367:     my ($dir,$file)=@_;
1.460     albertel 6368:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6369: 	$file=filelocation($dir,$file);
1.700     albertel 6370:     } elsif ($file=~m-^/adm/-) {
                   6371: 	$file=~s-^/adm/wrapper/-/-;
                   6372: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6373:     }
                   6374:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6375: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6376:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6377: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6378:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6379: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6380: 	    -/uploaded/$1/$2/-x;
1.46      www      6381:     }
1.462     albertel 6382:     return $file;
1.465     albertel 6383: }
                   6384: 
                   6385: sub current_machine_domains {
                   6386:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6387:     my @domains;
                   6388:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6389: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6390: 	if ($hostname eq $name) {
                   6391: 	    push(@domains,$hostdom{$id});
                   6392: 	}
                   6393:     }
                   6394:     return @domains;
                   6395: }
                   6396: 
                   6397: sub current_machine_ids {
                   6398:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6399:     my @ids;
                   6400:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6401: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6402: 	if ($hostname eq $name) {
                   6403: 	    push(@ids,$id);
                   6404: 	}
                   6405:     }
                   6406:     return @ids;
1.31      www      6407: }
                   6408: 
                   6409: # ------------------------------------------------------------- Declutters URLs
                   6410: 
                   6411: sub declutter {
                   6412:     my $thisfn=shift;
1.569     albertel 6413:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6414:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6415:     $thisfn=~s/^\///;
1.697     albertel 6416:     $thisfn=~s|^adm/wrapper/||;
                   6417:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      6418:     $thisfn=~s/^res\///;
1.235     www      6419:     $thisfn=~s/\?.+$//;
1.268     www      6420:     return $thisfn;
                   6421: }
                   6422: 
                   6423: # ------------------------------------------------------------- Clutter up URLs
                   6424: 
                   6425: sub clutter {
                   6426:     my $thisfn='/'.&declutter(shift);
1.609     banghart 6427:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      6428:        $thisfn='/res'.$thisfn; 
                   6429:     }
1.694     albertel 6430:     if ($thisfn !~m|/adm|) {
1.695     albertel 6431: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 6432: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 6433: 	} else {
                   6434: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   6435: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 6436: 	    if ($embstyle eq 'ssi'
                   6437: 		|| ($embstyle eq 'hdn')
                   6438: 		|| ($embstyle eq 'rat')
                   6439: 		|| ($embstyle eq 'prv')
                   6440: 		|| ($embstyle eq 'ign')) {
                   6441: 		#do nothing with these
                   6442: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 6443: 		|| ($embstyle eq 'emb')
                   6444: 		|| ($embstyle eq 'wrp')) {
                   6445: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 6446: 	    } elsif ($embstyle eq 'unk'
                   6447: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 6448: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 6449: 	    } else {
1.718     www      6450: #		&logthis("Got a blank emb style");
1.695     albertel 6451: 	    }
1.694     albertel 6452: 	}
                   6453:     }
1.31      www      6454:     return $thisfn;
1.12      www      6455: }
                   6456: 
1.557     albertel 6457: sub freeze_escape {
                   6458:     my ($value)=@_;
                   6459:     if (ref($value)) {
                   6460: 	$value=&nfreeze($value);
                   6461: 	return '__FROZEN__'.&escape($value);
                   6462:     }
                   6463:     return &escape($value);
                   6464: }
                   6465: 
1.12      www      6466: # -------------------------------------------------------- Escape Special Chars
                   6467: 
                   6468: sub escape {
                   6469:     my $str=shift;
                   6470:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   6471:     return $str;
                   6472: }
                   6473: 
                   6474: # ----------------------------------------------------- Un-Escape Special Chars
                   6475: 
                   6476: sub unescape {
                   6477:     my $str=shift;
                   6478:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   6479:     return $str;
                   6480: }
1.11      www      6481: 
1.557     albertel 6482: sub thaw_unescape {
                   6483:     my ($value)=@_;
                   6484:     if ($value =~ /^__FROZEN__/) {
                   6485: 	substr($value,0,10,undef);
                   6486: 	$value=&unescape($value);
                   6487: 	return &thaw($value);
                   6488:     }
                   6489:     return &unescape($value);
                   6490: }
                   6491: 
1.436     albertel 6492: sub correct_line_ends {
                   6493:     my ($result)=@_;
                   6494:     $$result =~s/\r\n/\n/mg;
                   6495:     $$result =~s/\r/\n/mg;
1.415     albertel 6496: }
1.1       albertel 6497: # ================================================================ Main Program
                   6498: 
1.184     www      6499: sub goodbye {
1.204     albertel 6500:    &logthis("Starting Shut down");
1.443     albertel 6501: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 6502:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 6503: #converted
1.599     albertel 6504: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   6505:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   6506: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   6507: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 6508: #1.1 only
1.599     albertel 6509: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   6510: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   6511: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   6512: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   6513:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   6514:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   6515:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      6516:    &flushcourselogs();
                   6517:    &logthis("Shutting down");
1.362     albertel 6518:    return DONE;
1.184     www      6519: }
                   6520: 
1.179     www      6521: BEGIN {
1.228     harris41 6522: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      6523:     unless ($readit) {
1.217     harris41 6524: {
1.581     matthew  6525:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 6526:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 6527: 
                   6528:     while (my $configline=<$config>) {
1.484     albertel 6529:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 6530: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      6531:            chomp($varvalue);
1.1       albertel 6532:            $perlvar{$varname}=$varvalue;
                   6533:         }
                   6534:     }
1.448     albertel 6535:     close($config);
1.1       albertel 6536: }
1.227     harris41 6537: {
1.448     albertel 6538:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 6539: 
                   6540:     while (my $configline=<$config>) {
                   6541:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   6542: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   6543:            chomp($varvalue);
                   6544:            $perlvar{$varname}=$varvalue;
                   6545:         }
                   6546:     }
1.448     albertel 6547:     close($config);
1.227     harris41 6548: }
1.1       albertel 6549: 
1.327     albertel 6550: # ------------------------------------------------------------ Read domain file
                   6551: {
                   6552:     %domaindescription = ();
                   6553:     %domain_auth_def = ();
                   6554:     %domain_auth_arg_def = ();
1.448     albertel 6555:     my $fh;
                   6556:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 6557:        while (<$fh>) {
1.390     matthew  6558:            next if (/^(\#|\s*$)/);
                   6559: #           next if /^\#/;
1.327     albertel 6560:            chomp;
1.403     www      6561:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  6562: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      6563: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 6564:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      6565: 	   $domaindescription{$domain}=$domain_description;
                   6566: 	   $domain_lang_def{$domain}=$def_lang;
                   6567: 	   $domain_city{$domain}=$city;
                   6568: 	   $domain_longi{$domain}=$longi;
                   6569: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  6570:            $domain_primary{$domain}=$primary;
1.403     www      6571: 
1.448     albertel 6572:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 6573: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 6574: 	}
1.327     albertel 6575:     }
1.448     albertel 6576:     close ($fh);
1.327     albertel 6577: }
                   6578: 
                   6579: 
1.1       albertel 6580: # ------------------------------------------------------------- Read hosts file
                   6581: {
1.448     albertel 6582:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 6583: 
                   6584:     while (my $configline=<$config>) {
1.303     matthew  6585:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      6586:        chomp($configline);
1.595     albertel 6587:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 6588:        $name=~s/\s//g;
1.595     albertel 6589:        if ($id && $domain && $role && $name) {
1.252     albertel 6590: 	 $hostname{$id}=$name;
                   6591: 	 $hostdom{$id}=$domain;
                   6592: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      6593:        }
1.1       albertel 6594:     }
1.448     albertel 6595:     close($config);
1.619     albertel 6596:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 6597:     #&get_iphost();
1.1       albertel 6598: }
                   6599: 
1.598     albertel 6600: sub get_iphost {
                   6601:     if (%iphost) { return %iphost; }
1.653     albertel 6602:     my %name_to_ip;
1.598     albertel 6603:     foreach my $id (keys(%hostname)) {
                   6604: 	my $name=$hostname{$id};
1.653     albertel 6605: 	my $ip;
                   6606: 	if (!exists($name_to_ip{$name})) {
                   6607: 	    $ip = gethostbyname($name);
                   6608: 	    if (!$ip || length($ip) ne 4) {
                   6609: 		&logthis("Skipping host $id name $name no IP found\n");
                   6610: 		next;
                   6611: 	    }
                   6612: 	    $ip=inet_ntoa($ip);
                   6613: 	    $name_to_ip{$name} = $ip;
                   6614: 	} else {
                   6615: 	    $ip = $name_to_ip{$name};
1.598     albertel 6616: 	}
                   6617: 	push(@{$iphost{$ip}},$id);
                   6618:     }
                   6619:     return %iphost;
                   6620: }
                   6621: 
1.1       albertel 6622: # ------------------------------------------------------ Read spare server file
                   6623: {
1.448     albertel 6624:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 6625: 
                   6626:     while (my $configline=<$config>) {
                   6627:        chomp($configline);
1.284     matthew  6628:        if ($configline) {
1.1       albertel 6629:           $spareid{$configline}=1;
                   6630:        }
                   6631:     }
1.448     albertel 6632:     close($config);
1.1       albertel 6633: }
1.11      www      6634: # ------------------------------------------------------------ Read permissions
                   6635: {
1.448     albertel 6636:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      6637: 
                   6638:     while (my $configline=<$config>) {
1.448     albertel 6639: 	chomp($configline);
                   6640: 	if ($configline) {
                   6641: 	    my ($role,$perm)=split(/ /,$configline);
                   6642: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   6643: 	}
1.11      www      6644:     }
1.448     albertel 6645:     close($config);
1.11      www      6646: }
                   6647: 
                   6648: # -------------------------------------------- Read plain texts for permissions
                   6649: {
1.448     albertel 6650:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      6651: 
                   6652:     while (my $configline=<$config>) {
1.448     albertel 6653: 	chomp($configline);
                   6654: 	if ($configline) {
                   6655: 	    my ($short,$plain)=split(/:/,$configline);
                   6656: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   6657: 	}
1.135     www      6658:     }
1.448     albertel 6659:     close($config);
1.135     www      6660: }
                   6661: 
                   6662: # ---------------------------------------------------------- Read package table
                   6663: {
1.448     albertel 6664:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      6665: 
                   6666:     while (my $configline=<$config>) {
1.483     albertel 6667: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 6668: 	chomp($configline);
                   6669: 	my ($short,$plain)=split(/:/,$configline);
                   6670: 	my ($pack,$name)=split(/\&/,$short);
                   6671: 	if ($plain ne '') {
                   6672: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   6673: 	    $packagetab{$short}=$plain; 
                   6674: 	}
1.11      www      6675:     }
1.448     albertel 6676:     close($config);
1.329     matthew  6677: }
                   6678: 
                   6679: # ------------- set up temporary directory
                   6680: {
                   6681:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   6682: 
1.11      www      6683: }
                   6684: 
1.599     albertel 6685: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      6686: 
1.281     www      6687: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      6688: $dumpcount=0;
1.22      www      6689: 
1.163     harris41 6690: &logtouch();
1.672     albertel 6691: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      6692: $readit=1;
1.564     albertel 6693:     {
                   6694: 	use integer;
                   6695: 	my $test=(2**32)+1;
1.568     albertel 6696: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 6697: 	&logthis(" Detected 64bit platform ($_64bit)");
                   6698:     }
1.195     www      6699: }
1.1       albertel 6700: }
1.179     www      6701: 
1.1       albertel 6702: 1;
1.191     harris41 6703: __END__
                   6704: 
1.243     albertel 6705: =pod
                   6706: 
1.191     harris41 6707: =head1 NAME
                   6708: 
1.243     albertel 6709: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 6710: 
                   6711: =head1 SYNOPSIS
                   6712: 
1.243     albertel 6713: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 6714: 
                   6715:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   6716: 
1.243     albertel 6717: Common parameters:
                   6718: 
                   6719: =over 4
                   6720: 
                   6721: =item *
                   6722: 
                   6723: $uname : an internal username (if $cname expecting a course Id specifically)
                   6724: 
                   6725: =item *
                   6726: 
                   6727: $udom : a domain (if $cdom expecting a course's domain specifically)
                   6728: 
                   6729: =item *
                   6730: 
                   6731: $symb : a resource instance identifier
                   6732: 
                   6733: =item *
                   6734: 
                   6735: $namespace : the name of a .db file that contains the data needed or
                   6736: being set.
                   6737: 
                   6738: =back
                   6739: 
1.394     bowersj2 6740: =head1 OVERVIEW
1.191     harris41 6741: 
1.394     bowersj2 6742: lonnet provides subroutines which interact with the
                   6743: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   6744: about classes, users, and resources.
1.243     albertel 6745: 
                   6746: For many of these objects you can also use this to store data about
                   6747: them or modify them in various ways.
1.191     harris41 6748: 
1.394     bowersj2 6749: =head2 Symbs
1.191     harris41 6750: 
1.394     bowersj2 6751: To identify a specific instance of a resource, LON-CAPA uses symbols
                   6752: or "symbs"X<symb>. These identifiers are built from the URL of the
                   6753: map, the resource number of the resource in the map, and the URL of
                   6754: the resource itself. The latter is somewhat redundant, but might help
                   6755: if maps change.
                   6756: 
                   6757: An example is
                   6758: 
                   6759:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   6760: 
                   6761: The respective map entry is
                   6762: 
                   6763:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   6764:   title="Problem 2">
                   6765:  </resource>
                   6766: 
                   6767: Symbs are used by the random number generator, as well as to store and
                   6768: restore data specific to a certain instance of for example a problem.
                   6769: 
                   6770: =head2 Storing And Retrieving Data
                   6771: 
                   6772: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   6773: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   6774: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   6775: is is the non-critical message twin of cstore. These functions are for
                   6776: handlers to store a perl hash to a user's permanent data space in an
                   6777: easy manner, and to retrieve it again on another call. It is expected
                   6778: that a handler would use this once at the beginning to retrieve data,
                   6779: and then again once at the end to send only the new data back.
                   6780: 
                   6781: The data is stored in the user's data directory on the user's
                   6782: homeserver under the ID of the course.
                   6783: 
                   6784: The hash that is returned by restore will have all of the previous
                   6785: value for all of the elements of the hash.
                   6786: 
                   6787: Example:
                   6788: 
                   6789:  #creating a hash
                   6790:  my %hash;
                   6791:  $hash{'foo'}='bar';
                   6792: 
                   6793:  #storing it
                   6794:  &Apache::lonnet::cstore(\%hash);
                   6795: 
                   6796:  #changing a value
                   6797:  $hash{'foo'}='notbar';
                   6798: 
                   6799:  #adding a new value
                   6800:  $hash{'bar'}='foo';
                   6801:  &Apache::lonnet::cstore(\%hash);
                   6802: 
                   6803:  #retrieving the hash
                   6804:  my %history=&Apache::lonnet::restore();
                   6805: 
                   6806:  #print the hash
                   6807:  foreach my $key (sort(keys(%history))) {
                   6808:    print("\%history{$key} = $history{$key}");
                   6809:  }
                   6810: 
                   6811: Will print out:
1.191     harris41 6812: 
1.394     bowersj2 6813:  %history{1:foo} = bar
                   6814:  %history{1:keys} = foo:timestamp
                   6815:  %history{1:timestamp} = 990455579
                   6816:  %history{2:bar} = foo
                   6817:  %history{2:foo} = notbar
                   6818:  %history{2:keys} = foo:bar:timestamp
                   6819:  %history{2:timestamp} = 990455580
                   6820:  %history{bar} = foo
                   6821:  %history{foo} = notbar
                   6822:  %history{timestamp} = 990455580
                   6823:  %history{version} = 2
                   6824: 
                   6825: Note that the special hash entries C<keys>, C<version> and
                   6826: C<timestamp> were added to the hash. C<version> will be equal to the
                   6827: total number of versions of the data that have been stored. The
                   6828: C<timestamp> attribute will be the UNIX time the hash was
                   6829: stored. C<keys> is available in every historical section to list which
                   6830: keys were added or changed at a specific historical revision of a
                   6831: hash.
                   6832: 
                   6833: B<Warning>: do not store the hash that restore returns directly. This
                   6834: will cause a mess since it will restore the historical keys as if the
                   6835: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 6836: 
1.394     bowersj2 6837: Calling convention:
1.191     harris41 6838: 
1.394     bowersj2 6839:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   6840:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 6841: 
1.394     bowersj2 6842: For more detailed information, see lonnet specific documentation.
1.191     harris41 6843: 
1.394     bowersj2 6844: =head1 RETURN MESSAGES
1.191     harris41 6845: 
1.394     bowersj2 6846: =over 4
1.191     harris41 6847: 
1.394     bowersj2 6848: =item * B<con_lost>: unable to contact remote host
1.191     harris41 6849: 
1.394     bowersj2 6850: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   6851: when the connection is brought back up
1.191     harris41 6852: 
1.394     bowersj2 6853: =item * B<con_failed>: unable to contact remote host and unable to save message
                   6854: for later delivery
1.191     harris41 6855: 
1.394     bowersj2 6856: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 6857: 
1.394     bowersj2 6858: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 6859: that was requested
1.191     harris41 6860: 
1.243     albertel 6861: =back
1.191     harris41 6862: 
1.243     albertel 6863: =head1 PUBLIC SUBROUTINES
1.191     harris41 6864: 
1.243     albertel 6865: =head2 Session Environment Functions
1.191     harris41 6866: 
1.243     albertel 6867: =over 4
1.191     harris41 6868: 
1.394     bowersj2 6869: =item * 
                   6870: X<appenv()>
                   6871: B<appenv(%hash)>: the value of %hash is written to
                   6872: the user envirnoment file, and will be restored for each access this
1.620     albertel 6873: user makes during this session, also modifies the %env for the current
1.394     bowersj2 6874: process
1.191     harris41 6875: 
                   6876: =item *
1.394     bowersj2 6877: X<delenv()>
                   6878: B<delenv($regexp)>: removes all items from the session
                   6879: environment file that matches the regular expression in $regexp. The
1.620     albertel 6880: values are also delted from the current processes %env.
1.191     harris41 6881: 
1.243     albertel 6882: =back
                   6883: 
                   6884: =head2 User Information
1.191     harris41 6885: 
1.243     albertel 6886: =over 4
1.191     harris41 6887: 
                   6888: =item *
1.394     bowersj2 6889: X<queryauthenticate()>
                   6890: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 6891: authentication scheme
                   6892: 
                   6893: =item *
1.394     bowersj2 6894: X<authenticate()>
                   6895: B<authenticate($uname,$upass,$udom)>: try to
                   6896: authenticate user from domain's lib servers (first use the current
                   6897: one). C<$upass> should be the users password.
1.191     harris41 6898: 
                   6899: =item *
1.394     bowersj2 6900: X<homeserver()>
                   6901: B<homeserver($uname,$udom)>: find the server which has
                   6902: the user's directory and files (there must be only one), this caches
                   6903: the answer, and also caches if there is a borken connection.
1.191     harris41 6904: 
                   6905: =item *
1.394     bowersj2 6906: X<idget()>
                   6907: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   6908: (IDs are a unique resource in a domain, there must be only 1 ID per
                   6909: username, and only 1 username per ID in a specific domain) (returns
                   6910: hash: id=>name,id=>name)
1.191     harris41 6911: 
                   6912: =item *
1.394     bowersj2 6913: X<idrget()>
                   6914: B<idrget($udom,@unames)>: find the IDs behind a list of
                   6915: usernames (returns hash: name=>id,name=>id)
1.191     harris41 6916: 
                   6917: =item *
1.394     bowersj2 6918: X<idput()>
                   6919: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 6920: 
                   6921: =item *
1.394     bowersj2 6922: X<rolesinit()>
                   6923: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 6924: 
                   6925: =item *
1.551     albertel 6926: X<getsection()>
                   6927: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 6928: course $cname, return section name/number or '' for "not in course"
                   6929: and '-1' for "no section"
                   6930: 
                   6931: =item *
1.394     bowersj2 6932: X<userenvironment()>
                   6933: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 6934: passed in @what from the requested user's environment, returns a hash
                   6935: 
                   6936: =back
                   6937: 
                   6938: =head2 User Roles
                   6939: 
                   6940: =over 4
                   6941: 
                   6942: =item *
                   6943: 
                   6944: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   6945: actions
                   6946:  F: full access
                   6947:  U,I,K: authentication modes (cxx only)
                   6948:  '': forbidden
                   6949:  1: user needs to choose course
                   6950:  2: browse allowed
                   6951: 
                   6952: =item *
                   6953: 
                   6954: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   6955: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   6956: and course level
                   6957: 
                   6958: =item *
                   6959: 
                   6960: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   6961: explanation of a user role term
                   6962: 
                   6963: =back
                   6964: 
                   6965: =head2 User Modification
                   6966: 
                   6967: =over 4
                   6968: 
                   6969: =item *
                   6970: 
                   6971: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   6972: user for the level given by URL.  Optional start and end dates (leave empty
                   6973: string or zero for "no date")
1.191     harris41 6974: 
                   6975: =item *
                   6976: 
1.243     albertel 6977: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   6978: change a users, password, possible return values are: ok,
                   6979: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   6980: refused
1.191     harris41 6981: 
                   6982: =item *
                   6983: 
1.243     albertel 6984: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 6985: 
                   6986: =item *
                   6987: 
1.243     albertel 6988: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   6989: modify user
1.191     harris41 6990: 
                   6991: =item *
                   6992: 
1.286     matthew  6993: modifystudent
                   6994: 
                   6995: modify a students enrollment and identification information.
                   6996: The course id is resolved based on the current users environment.  
                   6997: This means the envoking user must be a course coordinator or otherwise
                   6998: associated with a course.
                   6999: 
1.297     matthew  7000: This call is essentially a wrapper for lonnet::modifyuser and
                   7001: lonnet::modify_student_enrollment
1.286     matthew  7002: 
                   7003: Inputs: 
                   7004: 
                   7005: =over 4
                   7006: 
                   7007: =item B<$udom> Students loncapa domain
                   7008: 
                   7009: =item B<$uname> Students loncapa login name
                   7010: 
                   7011: =item B<$uid> Students id/student number
                   7012: 
                   7013: =item B<$umode> Students authentication mode
                   7014: 
                   7015: =item B<$upass> Students password
                   7016: 
                   7017: =item B<$first> Students first name
                   7018: 
                   7019: =item B<$middle> Students middle name
                   7020: 
                   7021: =item B<$last> Students last name
                   7022: 
                   7023: =item B<$gene> Students generation
                   7024: 
                   7025: =item B<$usec> Students section in course
                   7026: 
                   7027: =item B<$end> Unix time of the roles expiration
                   7028: 
                   7029: =item B<$start> Unix time of the roles start date
                   7030: 
                   7031: =item B<$forceid> If defined, allow $uid to be changed
                   7032: 
                   7033: =item B<$desiredhome> server to use as home server for student
                   7034: 
                   7035: =back
1.297     matthew  7036: 
                   7037: =item *
                   7038: 
                   7039: modify_student_enrollment
                   7040: 
                   7041: Change a students enrollment status in a class.  The environment variable
                   7042: 'role.request.course' must be defined for this function to proceed.
                   7043: 
                   7044: Inputs:
                   7045: 
                   7046: =over 4
                   7047: 
                   7048: =item $udom, students domain
                   7049: 
                   7050: =item $uname, students name
                   7051: 
                   7052: =item $uid, students user id
                   7053: 
                   7054: =item $first, students first name
                   7055: 
                   7056: =item $middle
                   7057: 
                   7058: =item $last
                   7059: 
                   7060: =item $gene
                   7061: 
                   7062: =item $usec
                   7063: 
                   7064: =item $end
                   7065: 
                   7066: =item $start
                   7067: 
                   7068: =back
                   7069: 
1.191     harris41 7070: 
                   7071: =item *
                   7072: 
1.243     albertel 7073: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7074: custom role; give a custom role to a user for the level given by URL.  Specify
                   7075: name and domain of role author, and role name
1.191     harris41 7076: 
                   7077: =item *
                   7078: 
1.243     albertel 7079: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7080: 
                   7081: =item *
                   7082: 
1.243     albertel 7083: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7084: 
                   7085: =back
                   7086: 
                   7087: =head2 Course Infomation
                   7088: 
                   7089: =over 4
1.191     harris41 7090: 
                   7091: =item *
                   7092: 
1.631     albertel 7093: coursedescription($courseid) : returns a hash of information about the
                   7094: specified course id, including all environment settings for the
                   7095: course, the description of the course will be in the hash under the
                   7096: key 'description'
1.191     harris41 7097: 
                   7098: =item *
                   7099: 
1.624     albertel 7100: resdata($name,$domain,$type,@which) : request for current parameter
                   7101: setting for a specific $type, where $type is either 'course' or 'user',
                   7102: @what should be a list of parameters to ask about. This routine caches
                   7103: answers for 5 minutes.
1.243     albertel 7104: 
                   7105: =back
                   7106: 
                   7107: =head2 Course Modification
                   7108: 
                   7109: =over 4
1.191     harris41 7110: 
                   7111: =item *
                   7112: 
1.243     albertel 7113: writecoursepref($courseid,%prefs) : write preferences (environment
                   7114: database) for a course
1.191     harris41 7115: 
                   7116: =item *
                   7117: 
1.243     albertel 7118: createcourse($udom,$description,$url) : make/modify course
                   7119: 
                   7120: =back
                   7121: 
                   7122: =head2 Resource Subroutines
                   7123: 
                   7124: =over 4
1.191     harris41 7125: 
                   7126: =item *
                   7127: 
1.243     albertel 7128: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7129: 
                   7130: =item *
                   7131: 
1.243     albertel 7132: repcopy($filename) : subscribes to the requested file, and attempts to
                   7133: replicate from the owning library server, Might return
1.607     raeburn  7134: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7135: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7136: resource. Expects the local filesystem pathname
                   7137: (/home/httpd/html/res/....)
                   7138: 
                   7139: =back
                   7140: 
                   7141: =head2 Resource Information
                   7142: 
                   7143: =over 4
1.191     harris41 7144: 
                   7145: =item *
                   7146: 
1.243     albertel 7147: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7148: a vairety of different possible values, $varname should be a request
                   7149: string, and the other parameters can be used to specify who and what
                   7150: one is asking about.
                   7151: 
                   7152: Possible values for $varname are environment.lastname (or other item
                   7153: from the envirnment hash), user.name (or someother aspect about the
                   7154: user), resource.0.maxtries (or some other part and parameter of a
                   7155: resource)
1.204     albertel 7156: 
                   7157: =item *
                   7158: 
1.243     albertel 7159: directcondval($number) : get current value of a condition; reads from a state
                   7160: string
1.204     albertel 7161: 
                   7162: =item *
                   7163: 
1.243     albertel 7164: condval($condidx) : value of condition index based on state
1.204     albertel 7165: 
                   7166: =item *
                   7167: 
1.243     albertel 7168: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7169: resource's metadata, $what should be either a specific key, or either
                   7170: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7171: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7172: 
                   7173: this function automatically caches all requests
1.191     harris41 7174: 
                   7175: =item *
                   7176: 
1.243     albertel 7177: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7178: network of library servers; returns file handle of where SQL and regex results
                   7179: will be stored for query
1.191     harris41 7180: 
                   7181: =item *
                   7182: 
1.243     albertel 7183: symbread($filename) : return symbolic list entry (filename argument optional);
                   7184: returns the data handle
1.191     harris41 7185: 
                   7186: =item *
                   7187: 
1.243     albertel 7188: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7189: a possible symb for the URL in $thisfn, and if is an encryypted
                   7190: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7191: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7192: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7193: 
1.191     harris41 7194: 
                   7195: =item *
                   7196: 
1.243     albertel 7197: symbclean($symb) : removes versions numbers from a symb, returns the
                   7198: cleaned symb
1.191     harris41 7199: 
                   7200: =item *
                   7201: 
1.243     albertel 7202: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7203: course map, user must be in a course for it to work.
1.191     harris41 7204: 
                   7205: =item *
                   7206: 
1.243     albertel 7207: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7208: 
                   7209: =item *
                   7210: 
1.243     albertel 7211: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7212: a random seed, all arguments are optional, if they aren't sent it uses the
                   7213: environment to derive them. Note: if symb isn't sent and it can't get one
                   7214: from &symbread it will use the current time as its return value
1.191     harris41 7215: 
                   7216: =item *
                   7217: 
1.243     albertel 7218: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7219: unfakeable, receipt
1.191     harris41 7220: 
                   7221: =item *
                   7222: 
1.620     albertel 7223: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7224: 
                   7225: =item *
                   7226: 
1.243     albertel 7227: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7228: 
                   7229: =item *
                   7230: 
1.243     albertel 7231: 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 7232: 
                   7233: =item *
                   7234: 
1.243     albertel 7235: 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 7236: 
                   7237: =item *
                   7238: 
1.243     albertel 7239: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7240: 
                   7241: =item *
                   7242: 
1.243     albertel 7243: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7244: forcing spreadsheet to reevaluate the resource scores next time.
                   7245: 
                   7246: =back
                   7247: 
                   7248: =head2 Storing/Retreiving Data
                   7249: 
                   7250: =over 4
1.191     harris41 7251: 
                   7252: =item *
                   7253: 
1.243     albertel 7254: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7255: for this url; hashref needs to be given and should be a \%hashname; the
                   7256: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7257: be derived from the env
1.191     harris41 7258: 
                   7259: =item *
                   7260: 
1.243     albertel 7261: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7262: uses critical subroutine
1.191     harris41 7263: 
                   7264: =item *
                   7265: 
1.243     albertel 7266: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7267: all args are optional
1.191     harris41 7268: 
                   7269: =item *
                   7270: 
1.717     albertel 7271: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7272: dumps the complete (or key matching regexp) namespace into a hash
                   7273: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7274: normally &store()ed into
                   7275: 
                   7276: $range should be either an integer '100' (give me the first 100
                   7277:                                            matching records)
                   7278:               or be  two integers sperated by a - with no spaces
                   7279:                  '30-50' (give me the 30th through the 50th matching
                   7280:                           records)
                   7281: 
                   7282: 
                   7283: =item *
                   7284: 
                   7285: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7286: replaces a &store() version of data with a replacement set of data
                   7287: for a particular resource in a namespace passed in the $storehash hash 
                   7288: reference
                   7289: 
                   7290: =item *
                   7291: 
1.243     albertel 7292: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7293: works very similar to store/cstore, but all data is stored in a
                   7294: temporary location and can be reset using tmpreset, $storehash should
                   7295: be a hash reference, returns nothing on success
1.191     harris41 7296: 
                   7297: =item *
                   7298: 
1.243     albertel 7299: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7300: similar to restore, but all data is stored in a temporary location and
                   7301: can be reset using tmpreset. Returns a hash of values on success,
                   7302: error string otherwise.
1.191     harris41 7303: 
                   7304: =item *
                   7305: 
1.243     albertel 7306: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7307: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7308: 
                   7309: =item *
                   7310: 
1.243     albertel 7311: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7312: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7313: 
                   7314: =item *
                   7315: 
1.243     albertel 7316: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7317: namesp ($udom and $uname are optional)
1.191     harris41 7318: 
                   7319: =item *
                   7320: 
1.702     albertel 7321: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7322: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7323: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7324: 
1.702     albertel 7325: $range should be either an integer '100' (give me the first 100
                   7326:                                            matching records)
                   7327:               or be  two integers sperated by a - with no spaces
                   7328:                  '30-50' (give me the 30th through the 50th matching
                   7329:                           records)
1.449     matthew  7330: =item *
                   7331: 
                   7332: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7333: $store can be a scalar, an array reference, or if the amount to be 
                   7334: incremented is > 1, a hash reference.
                   7335: 
                   7336: ($udom and $uname are optional)
1.191     harris41 7337: 
                   7338: =item *
                   7339: 
1.243     albertel 7340: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7341: ($udom and $uname are optional)
1.191     harris41 7342: 
                   7343: =item *
                   7344: 
1.243     albertel 7345: cput($namespace,$storehash,$udom,$uname) : critical put
                   7346: ($udom and $uname are optional)
1.191     harris41 7347: 
                   7348: =item *
                   7349: 
1.243     albertel 7350: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7351: reference filled in from namesp (encrypts the return communication)
                   7352: ($udom and $uname are optional)
1.191     harris41 7353: 
                   7354: =item *
                   7355: 
1.243     albertel 7356: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7357: critical subroutine
                   7358: 
                   7359: =back
                   7360: 
                   7361: =head2 Network Status Functions
                   7362: 
                   7363: =over 4
1.191     harris41 7364: 
                   7365: =item *
                   7366: 
                   7367: dirlist($uri) : return directory list based on URI
                   7368: 
                   7369: =item *
                   7370: 
1.243     albertel 7371: spareserver() : find server with least workload from spare.tab
                   7372: 
                   7373: =back
                   7374: 
                   7375: =head2 Apache Request
                   7376: 
                   7377: =over 4
1.191     harris41 7378: 
                   7379: =item *
                   7380: 
1.243     albertel 7381: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7382: localhost, posts hash
                   7383: 
                   7384: =back
                   7385: 
                   7386: =head2 Data to String to Data
                   7387: 
                   7388: =over 4
1.191     harris41 7389: 
                   7390: =item *
                   7391: 
1.243     albertel 7392: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7393: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7394: 
                   7395: =item *
                   7396: 
1.243     albertel 7397: hashref2str($hashref) : convert a hashref into a string complete with
                   7398: escaping and '=' and '&' separators, supports elements that are
                   7399: arrayrefs and hashrefs
1.191     harris41 7400: 
                   7401: =item *
                   7402: 
1.243     albertel 7403: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7404: with escaping and '&' separators, supports elements that are arrayrefs
                   7405: and hashrefs
1.191     harris41 7406: 
                   7407: =item *
                   7408: 
1.243     albertel 7409: str2hash($string) : convert string to hash using unescaping and
                   7410: splitting on '=' and '&', supports elements that are arrayrefs and
                   7411: hashrefs
1.191     harris41 7412: 
                   7413: =item *
                   7414: 
1.243     albertel 7415: str2array($string) : convert string to hash using unescaping and
                   7416: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7417: 
                   7418: =back
                   7419: 
                   7420: =head2 Logging Routines
                   7421: 
                   7422: =over 4
                   7423: 
                   7424: These routines allow one to make log messages in the lonnet.log and
                   7425: lonnet.perm logfiles.
1.191     harris41 7426: 
                   7427: =item *
                   7428: 
1.243     albertel 7429: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 7430: 
                   7431: =item *
                   7432: 
1.243     albertel 7433: logthis() : append message to the normal lonnet.log file, it gets
                   7434: preiodically rolled over and deleted.
1.191     harris41 7435: 
                   7436: =item *
                   7437: 
1.243     albertel 7438: logperm() : append a permanent message to lonnet.perm.log, this log
                   7439: file never gets deleted by any automated portion of the system, only
                   7440: messages of critical importance should go in here.
                   7441: 
                   7442: =back
                   7443: 
                   7444: =head2 General File Helper Routines
                   7445: 
                   7446: =over 4
1.191     harris41 7447: 
                   7448: =item *
                   7449: 
1.481     raeburn  7450: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   7451: (a) files in /uploaded
                   7452:   (i) If a local copy of the file exists - 
                   7453:       compares modification date of local copy with last-modified date for 
                   7454:       definitive version stored on home server for course. If local copy is 
                   7455:       stale, requests a new version from the home server and stores it. 
                   7456:       If the original has been removed from the home server, then local copy 
                   7457:       is unlinked.
                   7458:   (ii) If local copy does not exist -
                   7459:       requests the file from the home server and stores it. 
                   7460:   
                   7461:   If $caller is 'uploadrep':  
                   7462:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   7463:     for request for files originally uploaded via DOCS. 
                   7464:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   7465:   
                   7466:   Otherwise:
                   7467:      This indicates a call from the content generation phase of the request.
                   7468:      -  returns the entire contents of the file or -1.
                   7469:      
                   7470: (b) files in /res
                   7471:    - returns the entire contents of a file or -1; 
                   7472:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 7473: 
1.712     albertel 7474: 
                   7475: =item *
                   7476: 
                   7477: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   7478:                   reference
                   7479: 
                   7480: returns either a stat() list of data about the file or an empty list
                   7481: if the file doesn't exist or couldn't find out about it (connection
                   7482: problems or user unknown)
                   7483: 
1.191     harris41 7484: =item *
                   7485: 
1.243     albertel 7486: filelocation($dir,$file) : returns file system location of a file
                   7487: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   7488: directory that relative $file lookups are to looked in ($dir of /a/dir
                   7489: and a file of ../bob will become /a/bob)
1.191     harris41 7490: 
                   7491: =item *
                   7492: 
                   7493: hreflocation($dir,$file) : returns file system location or a URL; same as
                   7494: filelocation except for hrefs
                   7495: 
                   7496: =item *
                   7497: 
                   7498: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   7499: 
1.243     albertel 7500: =back
                   7501: 
1.608     albertel 7502: =head2 Usererfile file routines (/uploaded*)
                   7503: 
                   7504: =over 4
                   7505: 
                   7506: =item *
                   7507: 
                   7508: userfileupload(): main rotine for putting a file in a user or course's
                   7509:                   filespace, arguments are,
                   7510: 
1.620     albertel 7511:  formname - required - this is the name of the element in $env where the
1.608     albertel 7512:            filename, and the contents of the file to create/modifed exist
1.620     albertel 7513:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   7514:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 7515:  coursedoc - if true, store the file in the course of the active role
                   7516:              of the current user
                   7517:  subdir - required - subdirectory to put the file in under ../userfiles/
                   7518:          if undefined, it will be placed in "unknown"
                   7519: 
                   7520:  (This routine calls clean_filename() to remove any dangerous
                   7521:  characters from the filename, and then calls finuserfileupload() to
                   7522:  complete the transaction)
                   7523: 
                   7524:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7525:  and /adm/notfound.html if unsuccessful
                   7526: 
                   7527: =item *
                   7528: 
                   7529: clean_filename(): routine for cleaing a filename up for storage in
                   7530:                  userfile space, argument is:
                   7531: 
                   7532:  filename - proposed filename
                   7533: 
                   7534: returns: the new clean filename
                   7535: 
                   7536: =item *
                   7537: 
                   7538: finishuserfileupload(): routine that creaes and sends the file to
                   7539: userspace, probably shouldn't be called directly
                   7540: 
                   7541:   docuname: username or courseid of destination for the file
                   7542:   docudom: domain of user/course of destination for the file
                   7543:   formname: same as for userfileupload()
                   7544:   fname: filename (inculding subdirectories) for the file
                   7545: 
                   7546:  returns either the url of the uploaded file (/uploaded/....) if successful
                   7547:  and /adm/notfound.html if unsuccessful
                   7548: 
                   7549: =item *
                   7550: 
                   7551: renameuserfile(): renames an existing userfile to a new name
                   7552: 
                   7553:   Args:
                   7554:    docuname: username or courseid of destination for the file
                   7555:    docudom: domain of user/course of destination for the file
                   7556:    old: current file name (including any subdirs under userfiles)
                   7557:    new: desired file name (including any subdirs under userfiles)
                   7558: 
                   7559: =item *
                   7560: 
                   7561: mkdiruserfile(): creates a directory is a userfiles dir
                   7562: 
                   7563:   Args:
                   7564:    docuname: username or courseid of destination for the file
                   7565:    docudom: domain of user/course of destination for the file
                   7566:    dir: dir to create (including any subdirs under userfiles)
                   7567: 
                   7568: =item *
                   7569: 
                   7570: removeuserfile(): removes a file that exists in userfiles
                   7571: 
                   7572:   Args:
                   7573:    docuname: username or courseid of destination for the file
                   7574:    docudom: domain of user/course of destination for the file
                   7575:    fname: filname to delete (including any subdirs under userfiles)
                   7576: 
                   7577: =item *
                   7578: 
                   7579: removeuploadedurl(): convience function for removeuserfile()
                   7580: 
                   7581:   Args:
                   7582:    url:  a full /uploaded/... url to delete
                   7583: 
                   7584: =back
                   7585: 
1.243     albertel 7586: =head2 HTTP Helper Routines
                   7587: 
                   7588: =over 4
                   7589: 
1.191     harris41 7590: =item *
                   7591: 
                   7592: escape() : unpack non-word characters into CGI-compatible hex codes
                   7593: 
                   7594: =item *
                   7595: 
                   7596: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   7597: 
1.243     albertel 7598: =back
                   7599: 
                   7600: =head1 PRIVATE SUBROUTINES
                   7601: 
                   7602: =head2 Underlying communication routines (Shouldn't call)
                   7603: 
                   7604: =over 4
                   7605: 
                   7606: =item *
                   7607: 
                   7608: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   7609: 
                   7610: =item *
                   7611: 
                   7612: reply() : uses subreply to send a message to remote machine, logs all failures
                   7613: 
                   7614: =item *
                   7615: 
                   7616: critical() : passes a critical message to another server; if cannot
                   7617: get through then place message in connection buffer directory and
                   7618: returns con_delayed, if incapable of saving message, returns
                   7619: con_failed
                   7620: 
                   7621: =item *
                   7622: 
                   7623: reconlonc() : tries to reconnect lonc client processes.
                   7624: 
                   7625: =back
                   7626: 
                   7627: =head2 Resource Access Logging
                   7628: 
                   7629: =over 4
                   7630: 
                   7631: =item *
                   7632: 
                   7633: flushcourselogs() : flush (save) buffer logs and access logs
                   7634: 
                   7635: =item *
                   7636: 
                   7637: courselog($what) : save message for course in hash
                   7638: 
                   7639: =item *
                   7640: 
                   7641: courseacclog($what) : save message for course using &courselog().  Perform
                   7642: special processing for specific resource types (problems, exams, quizzes, etc).
                   7643: 
1.191     harris41 7644: =item *
                   7645: 
                   7646: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   7647: as a PerlChildExitHandler
1.243     albertel 7648: 
                   7649: =back
                   7650: 
                   7651: =head2 Other
                   7652: 
                   7653: =over 4
                   7654: 
                   7655: =item *
                   7656: 
                   7657: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 7658: 
                   7659: =back
                   7660: 
                   7661: =cut

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