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

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

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