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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.768   ! albertel    4: # $Id: lonnet.pm,v 1.767 2006/08/02 19:29:32 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.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.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   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.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.740     www        55: use lib '/home/httpd/lib/perl';
                     56: use LONCAPA;
                     57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.374     www       295: # ------------------------------------------- Transfer profile into environment
                    296: 
                    297: sub transfer_profile_to_env {
                    298:     my ($lonidsdir,$handle)=@_;
1.720     albertel  299:     if (!defined($lonidsdir)) {
                    300: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    301:     }
                    302:     if (!defined($handle)) {
                    303:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    304:     }
                    305: 
1.374     www       306:     my @profile;
                    307:     {
1.448     albertel  308: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       309: 	flock($idf,LOCK_SH);
                    310: 	@profile=<$idf>;
1.448     albertel  311: 	close($idf);
1.374     www       312:     }
                    313:     my $envi;
1.433     matthew   314:     my %Remove;
1.374     www       315:     for ($envi=0;$envi<=$#profile;$envi++) {
                    316: 	chomp($profile[$envi]);
1.690     albertel  317: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  318: 	$envname=&unescape($envname);
                    319: 	$envvalue=&unescape($envvalue);
1.619     albertel  320: 	$env{$envname} = $envvalue;
1.433     matthew   321:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    322:             if ($time < time-300) {
                    323:                 $Remove{$key}++;
                    324:             }
                    325:         }
                    326:     }
1.619     albertel  327:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   328:     foreach my $expired_key (keys(%Remove)) {
                    329:         &delenv($expired_key);
1.374     www       330:     }
1.1       albertel  331: }
                    332: 
1.5       www       333: # ---------------------------------------------------------- Append Environment
                    334: 
                    335: sub appenv {
1.6       www       336:     my %newenv=@_;
1.692     albertel  337:     foreach my $key (keys(%newenv)) {
                    338: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  339:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  340:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       341:                 .'</font>');
1.692     albertel  342: 	    delete($newenv{$key});
1.35      www       343:         } else {
1.692     albertel  344:             $env{$key}=$newenv{$key};
1.35      www       345:         }
1.191     harris41  346:     }
1.95      www       347: 
                    348:     my $lockfh;
1.620     albertel  349:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  350: 	return 'error: '.$!;
1.95      www       351:     }
                    352:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  353:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       354:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  355:          close($lockfh);
1.95      www       356:          return 'error: '.$!;
                    357:     }
                    358: 
1.6       www       359:     my @oldenv;
                    360:     {
1.448     albertel  361: 	my $fh;
1.620     albertel  362: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  363: 	    return 'error: '.$!;
                    364: 	}
                    365: 	@oldenv=<$fh>;
                    366: 	close($fh);
1.6       www       367:     }
                    368:     for (my $i=0; $i<=$#oldenv; $i++) {
                    369:         chomp($oldenv[$i]);
1.9       www       370:         if ($oldenv[$i] ne '') {
1.690     albertel  371: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.726     albertel  372: 	    $name=&unescape($name);
                    373: 	    $value=&unescape($value);
1.448     albertel  374: 	    unless (defined($newenv{$name})) {
                    375: 		$newenv{$name}=$value;
                    376: 	    }
1.9       www       377:         }
1.6       www       378:     }
                    379:     {
1.448     albertel  380: 	my $fh;
1.620     albertel  381: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  382: 	    return 'error';
                    383: 	}
                    384: 	my $newname;
                    385: 	foreach $newname (keys %newenv) {
1.726     albertel  386: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
1.448     albertel  387: 	}
                    388: 	close($fh);
1.56      www       389:     }
1.448     albertel  390: 	
                    391:     close($lockfh);
1.56      www       392:     return 'ok';
                    393: }
                    394: # ----------------------------------------------------- Delete from Environment
                    395: 
                    396: sub delenv {
                    397:     my $delthis=shift;
                    398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  399:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       400:                 "Attempt to delete from environment ".$delthis);
                    401:         return 'error';
                    402:     }
                    403:     my @oldenv;
                    404:     {
1.448     albertel  405: 	my $fh;
1.620     albertel  406: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  407: 	    return 'error';
                    408: 	}
                    409: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  410: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  411: 		     'Could not obtain shared lock in delenv: '.$!);
                    412: 	    close($fh);
                    413: 	    return 'error: '.$!;
                    414: 	}
                    415: 	@oldenv=<$fh>;
                    416: 	close($fh);
1.56      www       417:     }
                    418:     {
1.448     albertel  419: 	my $fh;
1.620     albertel  420: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  421: 	    return 'error';
                    422: 	}
                    423: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  424: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  425: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    426: 	    close($fh);
                    427: 	    return 'error: '.$!;
                    428: 	}
1.692     albertel  429: 	foreach my $cur_key (@oldenv) {
1.726     albertel  430: 	    my $unescaped_cur_key = &unescape($cur_key);
                    431: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    432:                 my ($key) = split('=',$cur_key,2);
                    433: 		$key = &unescape($key);
1.619     albertel  434:                 delete($env{$key});
1.473     matthew   435:             } else {
1.692     albertel  436:                 print $fh $cur_key; 
1.473     matthew   437:             }
1.448     albertel  438: 	}
                    439: 	close($fh);
1.5       www       440:     }
                    441:     return 'ok';
1.369     albertel  442: }
                    443: 
                    444: # ------------------------------------------ Find out current server userload
                    445: # there is a copy in lond
                    446: sub userload {
                    447:     my $numusers=0;
                    448:     {
                    449: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    450: 	my $filename;
                    451: 	my $curtime=time;
                    452: 	while ($filename=readdir(LONIDS)) {
                    453: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  454: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  455: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  456: 	}
                    457: 	closedir(LONIDS);
                    458:     }
                    459:     my $userloadpercent=0;
                    460:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    461:     if ($maxuserload) {
1.371     albertel  462: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  463:     }
1.372     albertel  464:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  465:     return $userloadpercent;
1.283     www       466: }
                    467: 
                    468: # ------------------------------------------ Fight off request when overloaded
                    469: 
                    470: sub overloaderror {
                    471:     my ($r,$checkserver)=@_;
                    472:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    473:     my $loadavg;
                    474:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  475:        open(my $loadfile,'/proc/loadavg');
1.283     www       476:        $loadavg=<$loadfile>;
                    477:        $loadavg =~ s/\s.*//g;
1.285     matthew   478:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  479:        close($loadfile);
1.283     www       480:     } else {
                    481:        $loadavg=&reply('load',$checkserver);
                    482:     }
1.285     matthew   483:     my $overload=$loadavg-100;
1.283     www       484:     if ($overload>0) {
1.285     matthew   485: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       486:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       487:         return 413;
1.283     www       488:     }    
                    489:     return '';
1.5       www       490: }
1.1       albertel  491: 
                    492: # ------------------------------ Find server with least workload from spare.tab
1.11      www       493: 
1.1       albertel  494: sub spareserver {
1.670     albertel  495:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  496:     my $tryserver;
                    497:     my $spareserver='';
1.370     albertel  498:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    499:     my $lowestserver=$loadpercent > $userloadpercent?
                    500: 	             $loadpercent :  $userloadpercent;
1.670     albertel  501:     foreach $tryserver (keys(%spareid)) {
                    502: 	my $loadans=&reply('load',$tryserver);
                    503: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  504: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    505: 	    next; #didn't get a number from the server
                    506: 	}
                    507: 	my $answer;
                    508: 	if ($loadans =~ /\d/) {
                    509: 	    if ($userloadans =~ /\d/) {
                    510: 		#both are numbers, pick the bigger one
                    511: 		$answer=$loadans > $userloadans?
                    512: 		    $loadans :  $userloadans;
                    513: 	    } else {
                    514: 		$answer = $loadans;
                    515: 	    }
                    516: 	} else {
                    517: 	    $answer = $userloadans;
                    518: 	}
                    519: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  520: 	    if ($want_server_name) {
                    521: 		$spareserver=$tryserver;
                    522: 	    } else {
                    523: 		$spareserver="http://$hostname{$tryserver}";
                    524: 	    }
1.411     albertel  525: 	    $lowestserver=$answer;
                    526: 	}
1.370     albertel  527:     }
1.1       albertel  528:     return $spareserver;
1.202     matthew   529: }
                    530: 
                    531: # --------------------------------------------- Try to change a user's password
                    532: 
                    533: sub changepass {
                    534:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    535:     $currentpass = &escape($currentpass);
                    536:     $newpass     = &escape($newpass);
                    537:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    538: 		       $server);
                    539:     if (! $answer) {
                    540: 	&logthis("No reply on password change request to $server ".
                    541: 		 "by $uname in domain $udom.");
                    542:     } elsif ($answer =~ "^ok") {
                    543:         &logthis("$uname in $udom successfully changed their password ".
                    544: 		 "on $server.");
                    545:     } elsif ($answer =~ "^pwchange_failure") {
                    546: 	&logthis("$uname in $udom was unable to change their password ".
                    547: 		 "on $server.  The action was blocked by either lcpasswd ".
                    548: 		 "or pwchange");
                    549:     } elsif ($answer =~ "^non_authorized") {
                    550:         &logthis("$uname in $udom did not get their password correct when ".
                    551: 		 "attempting to change it on $server.");
                    552:     } elsif ($answer =~ "^auth_mode_error") {
                    553:         &logthis("$uname in $udom attempted to change their password despite ".
                    554: 		 "not being locally or internally authenticated on $server.");
                    555:     } elsif ($answer =~ "^unknown_user") {
                    556:         &logthis("$uname in $udom attempted to change their password ".
                    557: 		 "on $server but were unable to because $server is not ".
                    558: 		 "their home server.");
                    559:     } elsif ($answer =~ "^refused") {
                    560: 	&logthis("$server refused to change $uname in $udom password because ".
                    561: 		 "it was sent an unencrypted request to change the password.");
                    562:     }
                    563:     return $answer;
1.1       albertel  564: }
                    565: 
1.169     harris41  566: # ----------------------- Try to determine user's current authentication scheme
                    567: 
                    568: sub queryauthenticate {
                    569:     my ($uname,$udom)=@_;
1.456     albertel  570:     my $uhome=&homeserver($uname,$udom);
                    571:     if (!$uhome) {
                    572: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    573: 	return 'no_host';
                    574:     }
                    575:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    576:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    577: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  578:     }
1.456     albertel  579:     return $answer;
1.169     harris41  580: }
                    581: 
1.1       albertel  582: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       583: 
1.1       albertel  584: sub authenticate {
                    585:     my ($uname,$upass,$udom)=@_;
1.12      www       586:     $upass=escape($upass);
1.199     www       587:     $uname=~s/\W//g;
1.471     albertel  588:     my $uhome=&homeserver($uname,$udom);
                    589:     if (!$uhome) {
                    590: 	&logthis("User $uname at $udom is unknown in authenticate");
                    591: 	return 'no_host';
1.1       albertel  592:     }
1.471     albertel  593:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    594:     if ($answer eq 'authorized') {
                    595: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    596: 	return $uhome; 
                    597:     }
                    598:     if ($answer eq 'non_authorized') {
                    599: 	&logthis("User $uname at $udom rejected by $uhome");
                    600: 	return 'no_host'; 
1.9       www       601:     }
1.471     albertel  602:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  603:     return 'no_host';
                    604: }
                    605: 
                    606: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       607: 
1.599     albertel  608: my %homecache;
1.1       albertel  609: sub homeserver {
1.230     stredwic  610:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  611:     my $index="$uname:$udom";
1.426     albertel  612: 
1.599     albertel  613:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  614:     my $tryserver;
                    615:     foreach $tryserver (keys %libserv) {
1.230     stredwic  616:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  617: 		 exists($badServerCache{$tryserver}));
1.1       albertel  618: 	if ($hostdom{$tryserver} eq $udom) {
                    619:            my $answer=reply("home:$udom:$uname",$tryserver);
                    620:            if ($answer eq 'found') { 
1.599     albertel  621: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  622:            } elsif ($answer eq 'no_host') {
                    623: 	       $badServerCache{$tryserver}=1;
1.221     matthew   624:            }
1.1       albertel  625:        }
                    626:     }    
                    627:     return 'no_host';
1.70      www       628: }
                    629: 
                    630: # ------------------------------------- Find the usernames behind a list of IDs
                    631: 
                    632: sub idget {
                    633:     my ($udom,@ids)=@_;
                    634:     my %returnhash=();
                    635:     
                    636:     my $tryserver;
                    637:     foreach $tryserver (keys %libserv) {
                    638:        if ($hostdom{$tryserver} eq $udom) {
                    639: 	  my $idlist=join('&',@ids);
                    640:           $idlist=~tr/A-Z/a-z/; 
                    641: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    642:           my @answer=();
1.76      www       643:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       644: 	      @answer=split(/\&/,$reply);
                    645:           }                    ;
                    646:           my $i;
                    647:           for ($i=0;$i<=$#ids;$i++) {
                    648:               if ($answer[$i]) {
                    649: 		  $returnhash{$ids[$i]}=$answer[$i];
                    650:               } 
                    651:           }
                    652:        }
                    653:     }    
                    654:     return %returnhash;
                    655: }
                    656: 
                    657: # ------------------------------------- Find the IDs behind a list of usernames
                    658: 
                    659: sub idrget {
                    660:     my ($udom,@unames)=@_;
                    661:     my %returnhash=();
1.191     harris41  662:     foreach (@unames) {
1.70      www       663:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  664:     }
1.70      www       665:     return %returnhash;
                    666: }
                    667: 
                    668: # ------------------------------- Store away a list of names and associated IDs
                    669: 
                    670: sub idput {
                    671:     my ($udom,%ids)=@_;
                    672:     my %servers=();
1.191     harris41  673:     foreach (keys %ids) {
1.487     albertel  674: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       675:         my $uhom=&homeserver($_,$udom);
                    676:         if ($uhom ne 'no_host') {
                    677:             my $id=&escape($ids{$_});
                    678:             $id=~tr/A-Z/a-z/;
                    679:             my $unam=&escape($_);
                    680: 	    if ($servers{$uhom}) {
                    681: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    682:             } else {
                    683:                 $servers{$uhom}=$id.'='.$unam;
                    684:             }
                    685:         }
1.191     harris41  686:     }
                    687:     foreach (keys %servers) {
1.70      www       688:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  689:     }
1.344     www       690: }
                    691: 
                    692: # --------------------------------------------------- Assign a key to a student
                    693: 
                    694: sub assign_access_key {
1.364     www       695: #
                    696: # a valid key looks like uname:udom#comments
                    697: # comments are being appended
                    698: #
1.498     www       699:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    700:     $kdom=
1.620     albertel  701:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       702:     $knum=
1.620     albertel  703:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       704:     $cdom=
1.620     albertel  705:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       706:     $cnum=
1.620     albertel  707:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    708:     $udom=$env{'user.name'} unless (defined($udom));
                    709:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       710:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       711:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  712:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       713:                                                   # assigned to this person
                    714:                                                   # - this should not happen,
1.345     www       715:                                                   # unless something went wrong
                    716:                                                   # the first time around
                    717: # ready to assign
1.364     www       718:         $logentry=$1.'; '.$logentry;
1.496     www       719:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       720:                                                  $kdom,$knum) eq 'ok') {
1.345     www       721: # key now belongs to user
1.346     www       722: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       723:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    724:                 &appenv('environment.'.$envkey => $ckey);
                    725:                 return 'ok';
                    726:             } else {
                    727:                 return 
                    728:   'error: Count not permanently assign key, will need to be re-entered later.';
                    729: 	    }
                    730:         } else {
                    731:             return 'error: Could not assign key, try again later.';
                    732:         }
1.364     www       733:     } elsif (!$existing{$ckey}) {
1.345     www       734: # the key does not exist
                    735: 	return 'error: The key does not exist';
                    736:     } else {
                    737: # the key is somebody else's
                    738: 	return 'error: The key is already in use';
                    739:     }
1.344     www       740: }
                    741: 
1.364     www       742: # ------------------------------------------ put an additional comment on a key
                    743: 
                    744: sub comment_access_key {
                    745: #
                    746: # a valid key looks like uname:udom#comments
                    747: # comments are being appended
                    748: #
                    749:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    750:     $cdom=
1.620     albertel  751:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       752:     $cnum=
1.620     albertel  753:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       754:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    755:     if ($existing{$ckey}) {
                    756:         $existing{$ckey}.='; '.$logentry;
                    757: # ready to assign
1.367     www       758:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       759:                                                  $cdom,$cnum) eq 'ok') {
                    760: 	    return 'ok';
                    761:         } else {
                    762: 	    return 'error: Count not store comment.';
                    763:         }
                    764:     } else {
                    765: # the key does not exist
                    766: 	return 'error: The key does not exist';
                    767:     }
                    768: }
                    769: 
1.344     www       770: # ------------------------------------------------------ Generate a set of keys
                    771: 
                    772: sub generate_access_keys {
1.364     www       773:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       774:     $cdom=
1.620     albertel  775:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       776:     $cnum=
1.620     albertel  777:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       778:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       779:     unless (($cdom) && ($cnum)) { return 0; }
                    780:     if ($number>10000) { return 0; }
                    781:     sleep(2); # make sure don't get same seed twice
                    782:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    783:     my $total=0;
                    784:     for (my $i=1;$i<=$number;$i++) {
                    785:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    786:                   sprintf("%lx",int(100000*rand)).'-'.
                    787:                   sprintf("%lx",int(100000*rand));
                    788:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    789:        $newkey=~s/0/h/g; # and also 0 and O
                    790:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    791:        if ($existing{$newkey}) {
                    792:            $i--;
                    793:        } else {
1.364     www       794: 	  if (&put('accesskeys',
                    795:               { $newkey => '# generated '.localtime().
1.620     albertel  796:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       797:                            '; '.$logentry },
                    798: 		   $cdom,$cnum) eq 'ok') {
1.344     www       799:               $total++;
                    800: 	  }
                    801:        }
                    802:     }
1.620     albertel  803:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       804:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    805:     return $total;
                    806: }
                    807: 
                    808: # ------------------------------------------------------- Validate an accesskey
                    809: 
                    810: sub validate_access_key {
                    811:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    812:     $cdom=
1.620     albertel  813:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       814:     $cnum=
1.620     albertel  815:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    816:     $udom=$env{'user.domain'} unless (defined($udom));
                    817:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       818:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  819:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       820: }
                    821: 
                    822: # ------------------------------------- Find the section of student in a course
1.652     albertel  823: sub devalidate_getsection_cache {
                    824:     my ($udom,$unam,$courseid)=@_;
                    825:     $courseid=~s/\_/\//g;
                    826:     $courseid=~s/^(\w)/\/$1/;
                    827:     my $hashid="$udom:$unam:$courseid";
                    828:     &devalidate_cache_new('getsection',$hashid);
                    829: }
1.298     matthew   830: 
                    831: sub getsection {
                    832:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  833:     my $cachetime=1800;
1.298     matthew   834:     $courseid=~s/\_/\//g;
                    835:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  836: 
                    837:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  838:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  839:     if (defined($cached)) { return $result; }
                    840: 
1.298     matthew   841:     my %Pending; 
                    842:     my %Expired;
                    843:     #
                    844:     # Each role can either have not started yet (pending), be active, 
                    845:     #    or have expired.
                    846:     #
                    847:     # If there is an active role, we are done.
                    848:     #
                    849:     # If there is more than one role which has not started yet, 
                    850:     #     choose the one which will start sooner
                    851:     # If there is one role which has not started yet, return it.
                    852:     #
                    853:     # If there is more than one expired role, choose the one which ended last.
                    854:     # If there is a role which has expired, return it.
                    855:     #
                    856:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    857:                         &homeserver($unam,$udom)))) {
                    858:         my ($key,$value)=split(/\=/,$_);
                    859:         $key=&unescape($key);
1.479     albertel  860:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   861:         my $section=$1;
                    862:         if ($key eq $courseid.'_st') { $section=''; }
                    863:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    864:         my $now=time;
1.548     albertel  865:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   866:             $Expired{$end}=$section;
                    867:             next;
                    868:         }
1.548     albertel  869:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   870:             $Pending{$start}=$section;
                    871:             next;
                    872:         }
1.599     albertel  873:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   874:     }
                    875:     #
                    876:     # Presumedly there will be few matching roles from the above
                    877:     # loop and the sorting time will be negligible.
                    878:     if (scalar(keys(%Pending))) {
                    879:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  880:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   881:     } 
                    882:     if (scalar(keys(%Expired))) {
                    883:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    884:         my $time = pop(@sorted);
1.599     albertel  885:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   886:     }
1.599     albertel  887:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   888: }
1.70      www       889: 
1.599     albertel  890: sub save_cache {
                    891:     &purge_remembered();
1.722     albertel  892:     #&Apache::loncommon::validate_page();
1.620     albertel  893:     undef(%env);
1.599     albertel  894: }
1.452     albertel  895: 
1.599     albertel  896: my $to_remember=-1;
                    897: my %remembered;
                    898: my %accessed;
                    899: my $kicks=0;
                    900: my $hits=0;
                    901: sub devalidate_cache_new {
                    902:     my ($name,$id,$debug) = @_;
                    903:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    904:     $id=&escape($name.':'.$id);
                    905:     $memcache->delete($id);
                    906:     delete($remembered{$id});
                    907:     delete($accessed{$id});
                    908: }
                    909: 
                    910: sub is_cached_new {
                    911:     my ($name,$id,$debug) = @_;
                    912:     $id=&escape($name.':'.$id);
                    913:     if (exists($remembered{$id})) {
                    914: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    915: 	$accessed{$id}=[&gettimeofday()];
                    916: 	$hits++;
                    917: 	return ($remembered{$id},1);
                    918:     }
                    919:     my $value = $memcache->get($id);
                    920:     if (!(defined($value))) {
                    921: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  922: 	return (undef,undef);
1.416     albertel  923:     }
1.599     albertel  924:     if ($value eq '__undef__') {
                    925: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    926: 	$value=undef;
                    927:     }
                    928:     &make_room($id,$value,$debug);
                    929:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    930:     return ($value,1);
                    931: }
                    932: 
                    933: sub do_cache_new {
                    934:     my ($name,$id,$value,$time,$debug) = @_;
                    935:     $id=&escape($name.':'.$id);
                    936:     my $setvalue=$value;
                    937:     if (!defined($setvalue)) {
                    938: 	$setvalue='__undef__';
                    939:     }
1.623     albertel  940:     if (!defined($time) ) {
                    941: 	$time=600;
                    942:     }
1.599     albertel  943:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  944:     $memcache->set($id,$setvalue,$time);
                    945:     # need to make a copy of $value
                    946:     #&make_room($id,$value,$debug);
1.599     albertel  947:     return $value;
                    948: }
                    949: 
                    950: sub make_room {
                    951:     my ($id,$value,$debug)=@_;
                    952:     $remembered{$id}=$value;
                    953:     if ($to_remember<0) { return; }
                    954:     $accessed{$id}=[&gettimeofday()];
                    955:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    956:     my $to_kick;
                    957:     my $max_time=0;
                    958:     foreach my $other (keys(%accessed)) {
                    959: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    960: 	    $to_kick=$other;
                    961: 	    $max_time=&tv_interval($accessed{$other});
                    962: 	}
                    963:     }
                    964:     delete($remembered{$to_kick});
                    965:     delete($accessed{$to_kick});
                    966:     $kicks++;
                    967:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  968:     return;
                    969: }
                    970: 
1.599     albertel  971: sub purge_remembered {
1.604     albertel  972:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    973:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  974:     undef(%remembered);
                    975:     undef(%accessed);
1.428     albertel  976: }
1.70      www       977: # ------------------------------------- Read an entry from a user's environment
                    978: 
                    979: sub userenvironment {
                    980:     my ($udom,$unam,@what)=@_;
                    981:     my %returnhash=();
                    982:     my @answer=split(/\&/,
                    983:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    984:                       &homeserver($unam,$udom)));
                    985:     my $i;
                    986:     for ($i=0;$i<=$#what;$i++) {
                    987: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    988:     }
                    989:     return %returnhash;
1.1       albertel  990: }
                    991: 
1.617     albertel  992: # ---------------------------------------------------------- Get a studentphoto
                    993: sub studentphoto {
                    994:     my ($udom,$unam,$ext) = @_;
                    995:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   996:     if (defined($env{'request.course.id'})) {
1.708     raeburn   997:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   998:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    999:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1000:             } else {
                   1001:                 my ($result,$perm_reqd)=
1.707     albertel 1002: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1003:                 if ($result eq 'ok') {
                   1004:                     if (!($perm_reqd eq 'yes')) {
                   1005:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1006:                     }
                   1007:                 }
                   1008:             }
                   1009:         }
                   1010:     } else {
                   1011:         my ($result,$perm_reqd) = 
1.707     albertel 1012: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1013:         if ($result eq 'ok') {
                   1014:             if (!($perm_reqd eq 'yes')) {
                   1015:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1016:             }
                   1017:         }
                   1018:     }
                   1019:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1020: }
                   1021: 
                   1022: sub retrievestudentphoto {
                   1023:     my ($udom,$unam,$ext,$type) = @_;
                   1024:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1025:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1026:     if ($ret eq 'ok') {
                   1027:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1028:         if ($type eq 'thumbnail') {
                   1029:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1030:         }
                   1031:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1032:         return $tokenurl;
                   1033:     } else {
                   1034:         if ($type eq 'thumbnail') {
                   1035:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1036:         } else { 
                   1037:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1038:         }
1.617     albertel 1039:     }
                   1040: }
                   1041: 
1.263     www      1042: # -------------------------------------------------------------------- New chat
                   1043: 
                   1044: sub chatsend {
1.724     raeburn  1045:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1046:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1047:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1048:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1049:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1050: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1051: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1052: }
                   1053: 
                   1054: # ------------------------------------------ Find current version of a resource
                   1055: 
                   1056: sub getversion {
                   1057:     my $fname=&clutter(shift);
                   1058:     unless ($fname=~/^\/res\//) { return -1; }
                   1059:     return &currentversion(&filelocation('',$fname));
                   1060: }
                   1061: 
                   1062: sub currentversion {
                   1063:     my $fname=shift;
1.599     albertel 1064:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1065:     if (defined($cached)) { return $result; }
1.292     www      1066:     my $author=$fname;
                   1067:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1068:     my ($udom,$uname)=split(/\//,$author);
                   1069:     my $home=homeserver($uname,$udom);
                   1070:     if ($home eq 'no_host') { 
                   1071:         return -1; 
                   1072:     }
                   1073:     my $answer=reply("currentversion:$fname",$home);
                   1074:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1075: 	return -1;
                   1076:     }
1.599     albertel 1077:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1078: }
                   1079: 
1.1       albertel 1080: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1081: 
1.1       albertel 1082: sub subscribe {
                   1083:     my $fname=shift;
1.761     raeburn  1084:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1085:     $fname=~s/[\n\r]//g;
1.1       albertel 1086:     my $author=$fname;
                   1087:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1088:     my ($udom,$uname)=split(/\//,$author);
                   1089:     my $home=homeserver($uname,$udom);
1.335     albertel 1090:     if ($home eq 'no_host') {
                   1091:         return 'not_found';
1.1       albertel 1092:     }
                   1093:     my $answer=reply("sub:$fname",$home);
1.64      www      1094:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1095: 	$answer.=' by '.$home;
                   1096:     }
1.1       albertel 1097:     return $answer;
                   1098: }
                   1099:     
1.8       www      1100: # -------------------------------------------------------------- Replicate file
                   1101: 
                   1102: sub repcopy {
                   1103:     my $filename=shift;
1.23      www      1104:     $filename=~s/\/+/\//g;
1.607     raeburn  1105:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1106:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1107:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1108: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1109: 	return &repcopy_userfile($filename);
                   1110:     }
1.532     albertel 1111:     $filename=~s/[\n\r]//g;
1.8       www      1112:     my $transname="$filename.in.transfer";
1.607     raeburn  1113:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1114:     my $remoteurl=subscribe($filename);
1.64      www      1115:     if ($remoteurl =~ /^con_lost by/) {
                   1116: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1117:            return 'unavailable';
1.8       www      1118:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1119: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1120: 	   return 'not_found';
1.64      www      1121:     } elsif ($remoteurl =~ /^rejected by/) {
                   1122: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1123:            return 'forbidden';
1.20      www      1124:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1125:            return 'ok';
1.8       www      1126:     } else {
1.290     www      1127:         my $author=$filename;
                   1128:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1129:         my ($udom,$uname)=split(/\//,$author);
                   1130:         my $home=homeserver($uname,$udom);
                   1131:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1132:            my @parts=split(/\//,$filename);
                   1133:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1134:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1135:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1136: 	       return 'bad_request';
1.8       www      1137:            }
                   1138:            my $count;
                   1139:            for ($count=5;$count<$#parts;$count++) {
                   1140:                $path.="/$parts[$count]";
                   1141:                if ((-e $path)!=1) {
                   1142: 		   mkdir($path,0777);
                   1143:                }
                   1144:            }
                   1145:            my $ua=new LWP::UserAgent;
                   1146:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1147:            my $response=$ua->request($request,$transname);
                   1148:            if ($response->is_error()) {
                   1149: 	       unlink($transname);
                   1150:                my $message=$response->status_line;
1.672     albertel 1151:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1152:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1153:                return 'unavailable';
1.8       www      1154:            } else {
1.16      www      1155: 	       if ($remoteurl!~/\.meta$/) {
                   1156:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1157:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1158:                   if ($mresponse->is_error()) {
                   1159: 		      unlink($filename.'.meta');
                   1160:                       &logthis(
1.672     albertel 1161:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1162:                   }
                   1163: 	       }
1.8       www      1164:                rename($transname,$filename);
1.607     raeburn  1165:                return 'ok';
1.8       www      1166:            }
1.290     www      1167:        }
1.8       www      1168:     }
1.330     www      1169: }
                   1170: 
                   1171: # ------------------------------------------------ Get server side include body
                   1172: sub ssi_body {
1.381     albertel 1173:     my ($filelink,%form)=@_;
1.606     matthew  1174:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1175:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1176:     }
1.330     www      1177:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1178:                                      &ssi($filelink,%form));
1.565     albertel 1179:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1180:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1181:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1182:     return $output;
1.8       www      1183: }
                   1184: 
1.15      www      1185: # --------------------------------------------------------- Server Side Include
                   1186: 
                   1187: sub ssi {
                   1188: 
1.23      www      1189:     my ($fn,%form)=@_;
1.15      www      1190: 
                   1191:     my $ua=new LWP::UserAgent;
1.23      www      1192:     
                   1193:     my $request;
1.711     albertel 1194: 
                   1195:     $form{'no_update_last_known'}=1;
                   1196: 
1.23      www      1197:     if (%form) {
                   1198:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1199:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1200:     } else {
                   1201:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1202:     }
                   1203: 
1.15      www      1204:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1205:     my $response=$ua->request($request);
                   1206: 
1.324     www      1207:     return $response->content;
                   1208: }
                   1209: 
                   1210: sub externalssi {
                   1211:     my ($url)=@_;
                   1212:     my $ua=new LWP::UserAgent;
                   1213:     my $request=new HTTP::Request('GET',$url);
                   1214:     my $response=$ua->request($request);
1.15      www      1215:     return $response->content;
                   1216: }
1.254     www      1217: 
1.492     albertel 1218: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1219: 
                   1220: sub allowuploaded {
                   1221:     my ($srcurl,$url)=@_;
                   1222:     $url=&clutter(&declutter($url));
                   1223:     my $dir=$url;
                   1224:     $dir=~s/\/[^\/]+$//;
                   1225:     my %httpref=();
                   1226:     my $httpurl=&hreflocation('',$url);
                   1227:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1228:     &Apache::lonnet::appenv(%httpref);
1.254     www      1229: }
1.477     raeburn  1230: 
1.478     albertel 1231: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1232: # input: action, courseID, current domain, intended
1.637     raeburn  1233: #        path to file, source of file, instruction to parse file for objects,
                   1234: #        ref to hash for embedded objects,
                   1235: #        ref to hash for codebase of java objects.
                   1236: #
1.485     raeburn  1237: # output: url to file (if action was uploaddoc), 
                   1238: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1239: #
1.478     albertel 1240: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1241: # course.
1.477     raeburn  1242: #
1.478     albertel 1243: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1244: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1245: #          course's home server.
1.477     raeburn  1246: #
1.478     albertel 1247: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1248: #          be copied from $source (current location) to 
                   1249: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1250: #         and will then be copied to
                   1251: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1252: #         course's home server.
1.485     raeburn  1253: #
1.481     raeburn  1254: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1255: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1256: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1257: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1258: #         in course's home server.
1.637     raeburn  1259: #
1.477     raeburn  1260: 
                   1261: sub process_coursefile {
1.638     albertel 1262:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1263:     my $fetchresult;
1.638     albertel 1264:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1265:     if ($action eq 'propagate') {
1.638     albertel 1266:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1267: 			     $home);
1.481     raeburn  1268:     } else {
1.477     raeburn  1269:         my $fpath = '';
                   1270:         my $fname = $file;
1.478     albertel 1271:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1272:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1273:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1274:         if ($action eq 'copy') {
                   1275:             if ($source eq '') {
                   1276:                 $fetchresult = 'no source file';
                   1277:                 return $fetchresult;
                   1278:             } else {
                   1279:                 my $destination = $filepath.'/'.$fname;
                   1280:                 rename($source,$destination);
                   1281:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1282:                                  $home);
1.481     raeburn  1283:             }
                   1284:         } elsif ($action eq 'uploaddoc') {
                   1285:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1286:             print $fh $env{'form.'.$source};
1.481     raeburn  1287:             close($fh);
1.637     raeburn  1288:             if ($parser eq 'parse') {
                   1289:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1290:                 unless ($parse_result eq 'ok') {
                   1291:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1292:                 }
                   1293:             }
1.477     raeburn  1294:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1295:                                  $home);
1.481     raeburn  1296:             if ($fetchresult eq 'ok') {
                   1297:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1298:             } else {
                   1299:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1300:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1301:                 return '/adm/notfound.html';
                   1302:             }
1.477     raeburn  1303:         }
                   1304:     }
1.485     raeburn  1305:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1306:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1307:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1308:     }
                   1309:     return $fetchresult;
                   1310: }
                   1311: 
1.637     raeburn  1312: sub build_filepath {
                   1313:     my ($fpath) = @_;
                   1314:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1315:     unless ($fpath eq '') {
                   1316:         my @parts=split('/',$fpath);
                   1317:         foreach my $part (@parts) {
                   1318:             $filepath.= '/'.$part;
                   1319:             if ((-e $filepath)!=1) {
                   1320:                 mkdir($filepath,0777);
                   1321:             }
                   1322:         }
                   1323:     }
                   1324:     return $filepath;
                   1325: }
                   1326: 
                   1327: sub store_edited_file {
1.638     albertel 1328:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1329:     my $file = $primary_url;
                   1330:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1331:     my $fpath = '';
                   1332:     my $fname = $file;
                   1333:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1334:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1335:     my $filepath = &build_filepath($fpath);
                   1336:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1337:     print $fh $content;
                   1338:     close($fh);
1.638     albertel 1339:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1340:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1341: 			  $home);
1.637     raeburn  1342:     if ($$fetchresult eq 'ok') {
                   1343:         return '/uploaded/'.$fpath.'/'.$fname;
                   1344:     } else {
1.638     albertel 1345:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1346: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1347:         return '/adm/notfound.html';
                   1348:     }
                   1349: }
                   1350: 
1.531     albertel 1351: sub clean_filename {
                   1352:     my ($fname)=@_;
1.315     www      1353: # Replace Windows backslashes by forward slashes
1.257     www      1354:     $fname=~s/\\/\//g;
1.315     www      1355: # Get rid of everything but the actual filename
1.257     www      1356:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1357: # Replace spaces by underscores
                   1358:     $fname=~s/\s+/\_/g;
                   1359: # Replace all other weird characters by nothing
1.317     www      1360:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1361: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1362: # numbers
                   1363:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1364:     return $fname;
                   1365: }
                   1366: 
1.608     albertel 1367: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1368: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1369: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1370: #        $coursedoc - if true up to the current course
                   1371: #                     if false
                   1372: #        $subdir - directory in userfile to store the file into
                   1373: #        $parser, $allfiles, $codebase - unknown
                   1374: #
                   1375: # output: url of file in userspace, or error: <message> 
                   1376: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1377: 
                   1378: 
1.531     albertel 1379: sub userfileupload {
1.719     banghart 1380:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1381:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1382:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1383:     $fname=&clean_filename($fname);
1.315     www      1384: # See if there is anything left
1.257     www      1385:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1386:     chop($env{'form.'.$formname});
1.523     raeburn  1387:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1388:         my $now = time;
                   1389:         my $filepath = 'tmp/helprequests/'.$now;
                   1390:         my @parts=split(/\//,$filepath);
                   1391:         my $fullpath = $perlvar{'lonDaemons'};
                   1392:         for (my $i=0;$i<@parts;$i++) {
                   1393:             $fullpath .= '/'.$parts[$i];
                   1394:             if ((-e $fullpath)!=1) {
                   1395:                 mkdir($fullpath,0777);
                   1396:             }
                   1397:         }
                   1398:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1399:         print $fh $env{'form.'.$formname};
1.523     raeburn  1400:         close($fh);
1.741     raeburn  1401:         return $fullpath.'/'.$fname;
                   1402:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1403:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1404:                        '_'.$env{'user.domain'}.'/pending';
                   1405:         my @parts=split(/\//,$filepath);
                   1406:         my $fullpath = $perlvar{'lonDaemons'};
                   1407:         for (my $i=0;$i<@parts;$i++) {
                   1408:             $fullpath .= '/'.$parts[$i];
                   1409:             if ((-e $fullpath)!=1) {
                   1410:                 mkdir($fullpath,0777);
                   1411:             }
                   1412:         }
                   1413:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1414:         print $fh $env{'form.'.$formname};
                   1415:         close($fh);
                   1416:         return $fullpath.'/'.$fname;
1.523     raeburn  1417:     }
1.719     banghart 1418:     
1.258     www      1419: # Create the directory if not present
1.493     albertel 1420:     $fname="$subdir/$fname";
1.259     www      1421:     if ($coursedoc) {
1.638     albertel 1422: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1423: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1424:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1425:             return &finishuserfileupload($docuname,$docudom,
                   1426: 					 $formname,$fname,$parser,$allfiles,
                   1427: 					 $codebase);
1.481     raeburn  1428:         } else {
1.620     albertel 1429:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1430:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1431: 				       $fname,$formname,$parser,
                   1432: 				       $allfiles,$codebase);
1.481     raeburn  1433:         }
1.719     banghart 1434:     } elsif (defined($destuname)) {
                   1435:         my $docuname=$destuname;
                   1436:         my $docudom=$destudom;
                   1437: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1438: 				     $fname,$parser,$allfiles,$codebase);
                   1439:         
1.259     www      1440:     } else {
1.638     albertel 1441:         my $docuname=$env{'user.name'};
                   1442:         my $docudom=$env{'user.domain'};
1.714     raeburn  1443:         if (exists($env{'form.group'})) {
                   1444:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1445:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1446:         }
1.638     albertel 1447: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1448: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1449:     }
1.271     www      1450: }
                   1451: 
                   1452: sub finishuserfileupload {
1.638     albertel 1453:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1454:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1455:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1456:     my ($fnamepath,$file);
                   1457:     $file=$fname;
                   1458:     if ($fname=~m|/|) {
                   1459:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1460: 	$path.=$fnamepath.'/';
                   1461:     }
1.259     www      1462:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1463:     my $count;
                   1464:     for ($count=4;$count<=$#parts;$count++) {
                   1465:         $filepath.="/$parts[$count]";
                   1466:         if ((-e $filepath)!=1) {
                   1467: 	    mkdir($filepath,0777);
                   1468:         }
                   1469:     }
                   1470: # Save the file
                   1471:     {
1.701     albertel 1472: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1473: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1474: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1475: 	    return '/adm/notfound.html';
                   1476: 	}
                   1477: 	if (!print FH ($env{'form.'.$formname})) {
                   1478: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1479: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1480: 	    return '/adm/notfound.html';
                   1481: 	}
1.570     albertel 1482: 	close(FH);
1.258     www      1483:     }
1.637     raeburn  1484:     if ($parser eq 'parse') {
1.638     albertel 1485:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1486: 						   $codebase);
1.637     raeburn  1487:         unless ($parse_result eq 'ok') {
1.638     albertel 1488:             &logthis('Failed to parse '.$filepath.$file.
                   1489: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1490:         }
                   1491:     }
1.259     www      1492: # Notify homeserver to grep it
                   1493: #
1.638     albertel 1494:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1495:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1496:     if ($fetchresult eq 'ok') {
1.259     www      1497: #
1.258     www      1498: # Return the URL to it
1.494     albertel 1499:         return '/uploaded/'.$path.$file;
1.263     www      1500:     } else {
1.494     albertel 1501:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1502: 		 ': '.$fetchresult);
1.263     www      1503:         return '/adm/notfound.html';
                   1504:     }    
1.493     albertel 1505: }
                   1506: 
1.637     raeburn  1507: sub extract_embedded_items {
1.648     raeburn  1508:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1509:     my @state = ();
                   1510:     my %javafiles = (
                   1511:                       codebase => '',
                   1512:                       code => '',
                   1513:                       archive => ''
                   1514:                     );
                   1515:     my %mediafiles = (
                   1516:                       src => '',
                   1517:                       movie => '',
                   1518:                      );
1.648     raeburn  1519:     my $p;
                   1520:     if ($content) {
                   1521:         $p = HTML::LCParser->new($content);
                   1522:     } else {
                   1523:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1524:     }
1.641     albertel 1525:     while (my $t=$p->get_token()) {
1.640     albertel 1526: 	if ($t->[0] eq 'S') {
                   1527: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1528: 	    push (@state, $tagname);
1.648     raeburn  1529:             if (lc($tagname) eq 'allow') {
                   1530:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1531:             }
1.640     albertel 1532: 	    if (lc($tagname) eq 'img') {
                   1533: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1534: 	    }
1.645     raeburn  1535:             if (lc($tagname) eq 'script') {
                   1536:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1537:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1538:                 } else {
                   1539:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1540:                 }
                   1541:             }
                   1542:             if (lc($tagname) eq 'link') {
                   1543:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1544:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1545:                 }
                   1546:             }
1.640     albertel 1547: 	    if (lc($tagname) eq 'object' ||
                   1548: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1549: 		foreach my $item (keys(%javafiles)) {
                   1550: 		    $javafiles{$item} = '';
                   1551: 		}
                   1552: 	    }
                   1553: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1554: 		my $name = lc($attr->{'name'});
                   1555: 		foreach my $item (keys(%javafiles)) {
                   1556: 		    if ($name eq $item) {
                   1557: 			$javafiles{$item} = $attr->{'value'};
                   1558: 			last;
                   1559: 		    }
                   1560: 		}
                   1561: 		foreach my $item (keys(%mediafiles)) {
                   1562: 		    if ($name eq $item) {
                   1563: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1564: 			last;
                   1565: 		    }
                   1566: 		}
                   1567: 	    }
                   1568: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1569: 		foreach my $item (keys(%javafiles)) {
                   1570: 		    if ($attr->{$item}) {
                   1571: 			$javafiles{$item} = $attr->{$item};
                   1572: 			last;
                   1573: 		    }
                   1574: 		}
                   1575: 		foreach my $item (keys(%mediafiles)) {
                   1576: 		    if ($attr->{$item}) {
                   1577: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1578: 			last;
                   1579: 		    }
                   1580: 		}
                   1581: 	    }
                   1582: 	} elsif ($t->[0] eq 'E') {
                   1583: 	    my ($tagname) = ($t->[1]);
                   1584: 	    if ($javafiles{'codebase'} ne '') {
                   1585: 		$javafiles{'codebase'} .= '/';
                   1586: 	    }  
                   1587: 	    if (lc($tagname) eq 'applet' ||
                   1588: 		lc($tagname) eq 'object' ||
                   1589: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1590: 		) {
                   1591: 		foreach my $item (keys(%javafiles)) {
                   1592: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1593: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1594: 			&add_filetype($allfiles,$file,$item);
                   1595: 		    }
                   1596: 		}
                   1597: 	    } 
                   1598: 	    pop @state;
                   1599: 	}
                   1600:     }
1.637     raeburn  1601:     return 'ok';
                   1602: }
                   1603: 
1.639     albertel 1604: sub add_filetype {
                   1605:     my ($allfiles,$file,$type)=@_;
                   1606:     if (exists($allfiles->{$file})) {
                   1607: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1608: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1609: 	}
                   1610:     } else {
                   1611: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1612:     }
                   1613: }
                   1614: 
1.493     albertel 1615: sub removeuploadedurl {
                   1616:     my ($url)=@_;
                   1617:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1618:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1619: }
                   1620: 
                   1621: sub removeuserfile {
                   1622:     my ($docuname,$docudom,$fname)=@_;
                   1623:     my $home=&homeserver($docuname,$docudom);
                   1624:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1625: }
1.15      www      1626: 
1.530     albertel 1627: sub mkdiruserfile {
                   1628:     my ($docuname,$docudom,$dir)=@_;
                   1629:     my $home=&homeserver($docuname,$docudom);
                   1630:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1631: }
                   1632: 
1.531     albertel 1633: sub renameuserfile {
                   1634:     my ($docuname,$docudom,$old,$new)=@_;
                   1635:     my $home=&homeserver($docuname,$docudom);
                   1636:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1637: 		  &escape("$new"),$home);
                   1638: }
                   1639: 
1.14      www      1640: # ------------------------------------------------------------------------- Log
                   1641: 
                   1642: sub log {
                   1643:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1644:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1645: }
                   1646: 
                   1647: # ------------------------------------------------------------------ Course Log
1.352     www      1648: #
                   1649: # This routine flushes several buffers of non-mission-critical nature
                   1650: #
1.157     www      1651: 
                   1652: sub flushcourselogs {
1.352     www      1653:     &logthis('Flushing log buffers');
                   1654: #
                   1655: # course logs
                   1656: # This is a log of all transactions in a course, which can be used
                   1657: # for data mining purposes
                   1658: #
                   1659: # It also collects the courseid database, which lists last transaction
                   1660: # times and course titles for all courseids
                   1661: #
                   1662:     my %courseidbuffer=();
1.191     harris41 1663:     foreach (keys %courselogs) {
1.157     www      1664:         my $crsid=$_;
1.352     www      1665:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1666: 		          &escape($courselogs{$crsid}),
                   1667: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1668: 	    delete $courselogs{$crsid};
                   1669:         } else {
                   1670:             &logthis('Failed to flush log buffer for '.$crsid);
                   1671:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1672:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1673:                         " exceeded maximum size, deleting.</font>");
                   1674:                delete $courselogs{$crsid};
                   1675:             }
1.352     www      1676:         }
                   1677:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1678:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1679: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1680:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1681:         } else {
                   1682:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1683: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1684:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1685:         }
1.191     harris41 1686:     }
1.352     www      1687: #
                   1688: # Write course id database (reverse lookup) to homeserver of courses 
                   1689: # Is used in pickcourse
                   1690: #
                   1691:     foreach (keys %courseidbuffer) {
1.353     www      1692:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1693:     }
                   1694: #
                   1695: # File accesses
                   1696: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1697: #
1.449     matthew  1698:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1699:         if ($entry =~ /___count$/) {
                   1700:             my ($dom,$name);
                   1701:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1702:             if (! defined($dom) || $dom eq '' || 
                   1703:                 ! defined($name) || $name eq '') {
1.620     albertel 1704:                 my $cid = $env{'request.course.id'};
                   1705:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1706:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1707:             }
1.450     matthew  1708:             my $value = $accesshash{$entry};
                   1709:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1710:             my %temphash=($url => $value);
1.449     matthew  1711:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1712:             if ($result eq 'ok') {
                   1713:                 delete $accesshash{$entry};
                   1714:             } elsif ($result eq 'unknown_cmd') {
                   1715:                 # Target server has old code running on it.
1.450     matthew  1716:                 my %temphash=($entry => $value);
1.449     matthew  1717:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1718:                     delete $accesshash{$entry};
                   1719:                 }
                   1720:             }
                   1721:         } else {
1.458     matthew  1722:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1723:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1724:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1725:                 delete $accesshash{$entry};
                   1726:             }
1.185     www      1727:         }
1.191     harris41 1728:     }
1.352     www      1729: #
                   1730: # Roles
                   1731: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1732: #
1.349     www      1733:     foreach (keys %userrolehash) {
                   1734:         my $entry=$_;
1.351     www      1735:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1736: 	    split(/\:/,$entry);
                   1737:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1738:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1739:                 $rudom,$runame) eq 'ok') {
                   1740: 	    delete $userrolehash{$entry};
                   1741:         }
                   1742:     }
1.662     raeburn  1743: #
                   1744: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1745: #
                   1746:     my %domrolebuffer = ();
                   1747:     foreach my $entry (keys %domainrolehash) {
                   1748:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1749:         if ($domrolebuffer{$rudom}) {
                   1750:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1751:                       '='.&escape($domainrolehash{$entry});
                   1752:         } else {
                   1753:             $domrolebuffer{$rudom}.=&escape($entry).
                   1754:                       '='.&escape($domainrolehash{$entry});
                   1755:         }
                   1756:         delete $domainrolehash{$entry};
                   1757:     }
                   1758:     foreach my $dom (keys(%domrolebuffer)) {
                   1759:         foreach my $tryserver (keys %libserv) {
                   1760:             if ($hostdom{$tryserver} eq $dom) {
                   1761:                 unless (&reply('domroleput:'.$dom.':'.
                   1762:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1763:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1764:                 }
                   1765:             }
                   1766:         }
                   1767:     }
1.186     www      1768:     $dumpcount++;
1.157     www      1769: }
                   1770: 
                   1771: sub courselog {
                   1772:     my $what=shift;
1.158     www      1773:     $what=time.':'.$what;
1.620     albertel 1774:     unless ($env{'request.course.id'}) { return ''; }
                   1775:     $coursedombuf{$env{'request.course.id'}}=
                   1776:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1777:     $coursenumbuf{$env{'request.course.id'}}=
                   1778:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1779:     $coursehombuf{$env{'request.course.id'}}=
                   1780:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1781:     $coursedescrbuf{$env{'request.course.id'}}=
                   1782:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1783:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1784:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1785:     $courseownerbuf{$env{'request.course.id'}}=
                   1786:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1787:     $coursetypebuf{$env{'request.course.id'}}=
                   1788:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1789:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1790: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1791:     } else {
1.620     albertel 1792: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1793:     }
1.620     albertel 1794:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1795: 	&flushcourselogs();
                   1796:     }
1.158     www      1797: }
                   1798: 
                   1799: sub courseacclog {
                   1800:     my $fnsymb=shift;
1.620     albertel 1801:     unless ($env{'request.course.id'}) { return ''; }
                   1802:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1803:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1804:         $what.=':POST';
1.583     matthew  1805:         # FIXME: Probably ought to escape things....
1.620     albertel 1806: 	foreach (keys %env) {
1.158     www      1807:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1808: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1809:             }
1.191     harris41 1810:         }
1.583     matthew  1811:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1812:         # FIXME: We should not be depending on a form parameter that someone
                   1813:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1814:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1815:             $what.= ':POST';
                   1816:             # FIXME: Probably ought to escape things....
                   1817:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1818:                                  'crsdiscuss') {
1.620     albertel 1819:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1820:             }
                   1821:         }
1.158     www      1822:     }
                   1823:     &courselog($what);
1.149     www      1824: }
                   1825: 
1.185     www      1826: sub countacc {
                   1827:     my $url=&declutter(shift);
1.458     matthew  1828:     return if (! defined($url) || $url eq '');
1.620     albertel 1829:     unless ($env{'request.course.id'}) { return ''; }
                   1830:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1831:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1832:     $accesshash{$key}++;
1.185     www      1833: }
1.349     www      1834: 
1.361     www      1835: sub linklog {
                   1836:     my ($from,$to)=@_;
                   1837:     $from=&declutter($from);
                   1838:     $to=&declutter($to);
                   1839:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1840:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1841: }
                   1842:   
1.349     www      1843: sub userrolelog {
                   1844:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1845:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1846:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1847:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1848:         ($trole=~/^ta/)) {
1.350     www      1849:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1850:        $userrolehash
                   1851:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1852:                     =$tend.':'.$tstart;
1.662     raeburn  1853:     }
                   1854:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1855:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1856:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1857:         ($trole=~/^sc/)) {
                   1858:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1859:        $domainrolehash
                   1860:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1861:                     = $tend.':'.$tstart;
                   1862:     }
1.351     www      1863: }
                   1864: 
                   1865: sub get_course_adv_roles {
                   1866:     my $cid=shift;
1.620     albertel 1867:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1868:     my %coursehash=&coursedescription($cid);
1.470     www      1869:     my %nothide=();
                   1870:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1871: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1872:     }
1.351     www      1873:     my %returnhash=();
                   1874:     my %dumphash=
                   1875:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1876:     my $now=time;
                   1877:     foreach (keys %dumphash) {
                   1878: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1879:         if (($tstart) && ($tstart<0)) { next; }
                   1880:         if (($tend) && ($tend<$now)) { next; }
                   1881:         if (($tstart) && ($now<$tstart)) { next; }
                   1882:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1883: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1884: 	if ((&privileged($username,$domain)) && 
                   1885: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1886: 	if ($role eq 'cr') { next; }
1.351     www      1887:         my $key=&plaintext($role);
                   1888:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1889:         if ($returnhash{$key}) {
                   1890: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1891:         } else {
                   1892:             $returnhash{$key}=$username.':'.$domain;
                   1893:         }
1.400     www      1894:      }
                   1895:     return %returnhash;
                   1896: }
                   1897: 
                   1898: sub get_my_roles {
                   1899:     my ($uname,$udom)=@_;
1.620     albertel 1900:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1901:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1902:     my %dumphash=
                   1903:             &dump('nohist_userroles',$udom,$uname);
                   1904:     my %returnhash=();
                   1905:     my $now=time;
                   1906:     foreach (keys %dumphash) {
                   1907: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1908:         if (($tstart) && ($tstart<0)) { next; }
                   1909:         if (($tend) && ($tend<$now)) { next; }
                   1910:         if (($tstart) && ($now<$tstart)) { next; }
                   1911:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1912: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1913:      }
                   1914:     return %returnhash;
1.399     www      1915: }
                   1916: 
                   1917: # ----------------------------------------------------- Frontpage Announcements
                   1918: #
                   1919: #
                   1920: 
                   1921: sub postannounce {
                   1922:     my ($server,$text)=@_;
                   1923:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1924:     unless ($text=~/\w/) { $text=''; }
                   1925:     return &reply('setannounce:'.&escape($text),$server);
                   1926: }
                   1927: 
                   1928: sub getannounce {
1.448     albertel 1929: 
                   1930:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1931: 	my $announcement='';
                   1932: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1933: 	close($fh);
1.399     www      1934: 	if ($announcement=~/\w/) { 
                   1935: 	    return 
                   1936:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1937:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1938: 	} else {
                   1939: 	    return '';
                   1940: 	}
                   1941:     } else {
                   1942: 	return '';
                   1943:     }
1.351     www      1944: }
1.353     www      1945: 
                   1946: # ---------------------------------------------------------- Course ID routines
                   1947: # Deal with domain's nohist_courseid.db files
                   1948: #
                   1949: 
                   1950: sub courseidput {
                   1951:     my ($domain,$what,$coursehome)=@_;
                   1952:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1953: }
                   1954: 
                   1955: sub courseiddump {
1.741     raeburn  1956:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1957:     my %returnhash=();
1.355     www      1958:     unless ($domfilter) { $domfilter=''; }
1.353     www      1959:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1960:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1961: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1962: 	        foreach (
                   1963:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1964: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1965:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1966:                                $tryserver))) {
1.506     raeburn  1967: 		    my ($key,$value)=split(/\=/,$_);
                   1968:                     if (($key) && ($value)) {
1.516     raeburn  1969: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1970:                     }
1.353     www      1971:                 }
                   1972:             }
                   1973:         }
                   1974:     }
                   1975:     return %returnhash;
                   1976: }
                   1977: 
1.658     raeburn  1978: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1979: 
                   1980: sub dcmailput {
1.685     raeburn  1981:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1982:     my $status = &Apache::lonnet::critical(
1.740     www      1983:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1984:        &escape($message),$server);
1.662     raeburn  1985:     return $status;
                   1986: }
                   1987: 
1.658     raeburn  1988: sub dcmaildump {
                   1989:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1990:     my %returnhash=();
                   1991:     if (exists($domain_primary{$dom})) {
                   1992:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1993:                                                          &escape($enddate).':';
                   1994: 	my @esc_senders=map { &escape($_)} @$senders;
                   1995: 	$cmd.=&escape(join('&',@esc_senders));
                   1996: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1997:             my ($key,$value) = split(/\=/,$_);
                   1998:             if (($key) && ($value)) {
                   1999:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2000:             }
                   2001:         }
                   2002:     }
                   2003:     return %returnhash;
                   2004: }
1.662     raeburn  2005: # ---------------------------------------------------------- Domain roles
                   2006: 
                   2007: sub get_domain_roles {
                   2008:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2009:     if (undef($startdate) || $startdate eq '') {
                   2010:         $startdate = '.';
                   2011:     }
                   2012:     if (undef($enddate) || $enddate eq '') {
                   2013:         $enddate = '.';
                   2014:     }
                   2015:     my $rolelist = join(':',@{$roles});
                   2016:     my %personnel = ();
                   2017:     foreach my $tryserver (keys(%libserv)) {
                   2018:         if ($hostdom{$tryserver} eq $dom) {
                   2019:             %{$personnel{$tryserver}}=();
                   2020:             foreach (
                   2021:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2022:                    &escape($startdate).':'.&escape($enddate).':'.
                   2023:                    &escape($rolelist), $tryserver))) {
                   2024:                 my($key,$value) = split(/\=/,$_);
                   2025:                 if (($key) && ($value)) {
                   2026:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2027:                 }
                   2028:             }
                   2029:         }
                   2030:     }
                   2031:     return %personnel;
                   2032: }
1.658     raeburn  2033: 
1.149     www      2034: # ----------------------------------------------------------- Check out an item
                   2035: 
1.504     albertel 2036: sub get_first_access {
                   2037:     my ($type,$argsymb)=@_;
                   2038:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2039:     if ($argsymb) { $symb=$argsymb; }
                   2040:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2041:     if ($type eq 'map') {
                   2042: 	$res=&symbread($map);
                   2043:     } else {
                   2044: 	$res=$symb;
                   2045:     }
                   2046:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2047:     return $times{"$courseid\0$res"};
1.504     albertel 2048: }
                   2049: 
                   2050: sub set_first_access {
                   2051:     my ($type)=@_;
                   2052:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2053:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2054:     if ($type eq 'map') {
                   2055: 	$res=&symbread($map);
                   2056:     } else {
                   2057: 	$res=$symb;
                   2058:     }
                   2059:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2060:     if (!$firstaccess) {
1.588     albertel 2061: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2062:     }
                   2063:     return 'already_set';
1.504     albertel 2064: }
                   2065: 
1.149     www      2066: sub checkout {
                   2067:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2068:     my $now=time;
                   2069:     my $lonhost=$perlvar{'lonHostID'};
                   2070:     my $infostr=&escape(
1.234     www      2071:                  'CHECKOUTTOKEN&'.
1.149     www      2072:                  $tuname.'&'.
                   2073:                  $tudom.'&'.
                   2074:                  $tcrsid.'&'.
                   2075:                  $symb.'&'.
                   2076: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2077:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2078:     if ($token=~/^error\:/) { 
1.672     albertel 2079:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2080:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2081:                  "</font>");
                   2082:         return ''; 
                   2083:     }
                   2084: 
1.149     www      2085:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2086:     $token=~tr/a-z/A-Z/;
                   2087: 
1.153     www      2088:     my %infohash=('resource.0.outtoken' => $token,
                   2089:                   'resource.0.checkouttime' => $now,
                   2090:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2091: 
                   2092:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2093:        return '';
1.151     www      2094:     } else {
1.672     albertel 2095:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2096:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2097:                  "</font>");
1.149     www      2098:     }    
                   2099: 
                   2100:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2101:                          &escape('Checkout '.$infostr.' - '.
                   2102:                                                  $token)) ne 'ok') {
                   2103: 	return '';
1.151     www      2104:     } else {
1.672     albertel 2105:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2106:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2107:                  "</font>");
1.149     www      2108:     }
1.151     www      2109:     return $token;
1.149     www      2110: }
                   2111: 
                   2112: # ------------------------------------------------------------ Check in an item
                   2113: 
                   2114: sub checkin {
                   2115:     my $token=shift;
1.150     www      2116:     my $now=time;
                   2117:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2118:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2119:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2120:     $dtoken=~s/\W/\_/g;
1.234     www      2121:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2122:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2123: 
1.154     www      2124:     unless (($tuname) && ($tudom)) {
                   2125:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2126:         return '';
                   2127:     }
                   2128:     
                   2129:     unless (&allowed('mgr',$tcrsid)) {
                   2130:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2131:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2132:         return '';
                   2133:     }
                   2134: 
1.153     www      2135:     my %infohash=('resource.0.intoken' => $token,
                   2136:                   'resource.0.checkintime' => $now,
                   2137:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2138: 
                   2139:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2140:        return '';
                   2141:     }    
                   2142: 
                   2143:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2144:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2145: 	return '';
                   2146:     }
                   2147: 
                   2148:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2149: }
                   2150: 
                   2151: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2152: 
                   2153: sub expirespread {
                   2154:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2155:     my $cid=$env{'request.course.id'}; 
1.110     www      2156:     if ($cid) {
                   2157:        my $now=time;
                   2158:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2159:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2160:                             $env{'course.'.$cid.'.num'}.
1.110     www      2161: 	        	    ':nohist_expirationdates:'.
                   2162:                             &escape($key).'='.$now,
1.620     albertel 2163:                             $env{'course.'.$cid.'.home'})
1.110     www      2164:     }
                   2165:     return 'ok';
1.14      www      2166: }
                   2167: 
1.109     www      2168: # ----------------------------------------------------- Devalidate Spreadsheets
                   2169: 
                   2170: sub devalidate {
1.325     www      2171:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2172:     my $cid=$env{'request.course.id'}; 
1.109     www      2173:     if ($cid) {
1.391     matthew  2174:         # delete the stored spreadsheets for
                   2175:         # - the student level sheet of this user in course's homespace
                   2176:         # - the assessment level sheet for this resource 
                   2177:         #   for this user in user's homespace
1.553     albertel 2178: 	# - current conditional state info
1.325     www      2179: 	my $key=$uname.':'.$udom.':';
1.109     www      2180:         my $status=
1.299     matthew  2181: 	    &del('nohist_calculatedsheets',
1.391     matthew  2182: 		 [$key.'studentcalc:'],
1.620     albertel 2183: 		 $env{'course.'.$cid.'.domain'},
                   2184: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2185: 		.' '.
                   2186: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2187: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2188:         unless ($status eq 'ok ok') {
                   2189:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2190:                     $uname.' at '.$udom.' for '.
1.109     www      2191: 		    $symb.': '.$status);
1.133     albertel 2192:         }
1.553     albertel 2193: 	&delenv('user.state.'.$cid);
1.109     www      2194:     }
                   2195: }
                   2196: 
1.265     albertel 2197: sub get_scalar {
                   2198:     my ($string,$end) = @_;
                   2199:     my $value;
                   2200:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2201: 	$value = $1;
                   2202:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2203: 	$value = $1;
                   2204:     }
                   2205:     return &unescape($value);
                   2206: }
                   2207: 
                   2208: sub array2str {
                   2209:   my (@array) = @_;
                   2210:   my $result=&arrayref2str(\@array);
                   2211:   $result=~s/^__ARRAY_REF__//;
                   2212:   $result=~s/__END_ARRAY_REF__$//;
                   2213:   return $result;
                   2214: }
                   2215: 
1.204     albertel 2216: sub arrayref2str {
                   2217:   my ($arrayref) = @_;
1.265     albertel 2218:   my $result='__ARRAY_REF__';
1.204     albertel 2219:   foreach my $elem (@$arrayref) {
1.265     albertel 2220:     if(ref($elem) eq 'ARRAY') {
                   2221:       $result.=&arrayref2str($elem).'&';
                   2222:     } elsif(ref($elem) eq 'HASH') {
                   2223:       $result.=&hashref2str($elem).'&';
                   2224:     } elsif(ref($elem)) {
                   2225:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2226:     } else {
                   2227:       $result.=&escape($elem).'&';
                   2228:     }
                   2229:   }
                   2230:   $result=~s/\&$//;
1.265     albertel 2231:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2232:   return $result;
                   2233: }
                   2234: 
1.168     albertel 2235: sub hash2str {
1.204     albertel 2236:   my (%hash) = @_;
                   2237:   my $result=&hashref2str(\%hash);
1.265     albertel 2238:   $result=~s/^__HASH_REF__//;
                   2239:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2240:   return $result;
                   2241: }
                   2242: 
                   2243: sub hashref2str {
                   2244:   my ($hashref)=@_;
1.265     albertel 2245:   my $result='__HASH_REF__';
1.495     albertel 2246:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2247:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2248:       $result.=&arrayref2str($_).'=';
1.204     albertel 2249:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2250:       $result.=&hashref2str($_).'=';
1.204     albertel 2251:     } elsif (ref($_)) {
1.265     albertel 2252:       $result.='=';
                   2253:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2254:     } else {
1.265     albertel 2255: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2256:     }
                   2257: 
1.265     albertel 2258:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2259:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2260:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2261:       $result.=&hashref2str($hashref->{$_}).'&';
                   2262:     } elsif(ref($hashref->{$_})) {
                   2263:        $result.='&';
                   2264:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2265:     } else {
1.265     albertel 2266:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2267:     }
                   2268:   }
1.168     albertel 2269:   $result=~s/\&$//;
1.265     albertel 2270:   $result .= '__END_HASH_REF__';
1.168     albertel 2271:   return $result;
                   2272: }
                   2273: 
                   2274: sub str2hash {
1.265     albertel 2275:     my ($string)=@_;
                   2276:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2277:     return %$hash;
                   2278: }
                   2279: 
                   2280: sub str2hashref {
1.168     albertel 2281:   my ($string) = @_;
1.265     albertel 2282: 
                   2283:   my %hash;
                   2284: 
                   2285:   if($string !~ /^__HASH_REF__/) {
                   2286:       if (! ($string eq '' || !defined($string))) {
                   2287: 	  $hash{'error'}='Not hash reference';
                   2288:       }
                   2289:       return (\%hash, $string);
                   2290:   }
                   2291: 
                   2292:   $string =~ s/^__HASH_REF__//;
                   2293: 
                   2294:   while($string !~ /^__END_HASH_REF__/) {
                   2295:       #key
                   2296:       my $key='';
                   2297:       if($string =~ /^__HASH_REF__/) {
                   2298:           ($key, $string)=&str2hashref($string);
                   2299:           if(defined($key->{'error'})) {
                   2300:               $hash{'error'}='Bad data';
                   2301:               return (\%hash, $string);
                   2302:           }
                   2303:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2304:           ($key, $string)=&str2arrayref($string);
                   2305:           if($key->[0] eq 'Array reference error') {
                   2306:               $hash{'error'}='Bad data';
                   2307:               return (\%hash, $string);
                   2308:           }
                   2309:       } else {
                   2310:           $string =~ s/^(.*?)=//;
1.267     albertel 2311: 	  $key=&unescape($1);
1.265     albertel 2312:       }
                   2313:       $string =~ s/^=//;
                   2314: 
                   2315:       #value
                   2316:       my $value='';
                   2317:       if($string =~ /^__HASH_REF__/) {
                   2318:           ($value, $string)=&str2hashref($string);
                   2319:           if(defined($value->{'error'})) {
                   2320:               $hash{'error'}='Bad data';
                   2321:               return (\%hash, $string);
                   2322:           }
                   2323:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2324:           ($value, $string)=&str2arrayref($string);
                   2325:           if($value->[0] eq 'Array reference error') {
                   2326:               $hash{'error'}='Bad data';
                   2327:               return (\%hash, $string);
                   2328:           }
                   2329:       } else {
                   2330: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2331:       }
                   2332:       $string =~ s/^&//;
                   2333: 
                   2334:       $hash{$key}=$value;
1.204     albertel 2335:   }
1.265     albertel 2336: 
                   2337:   $string =~ s/^__END_HASH_REF__//;
                   2338: 
                   2339:   return (\%hash, $string);
1.204     albertel 2340: }
                   2341: 
                   2342: sub str2array {
1.265     albertel 2343:     my ($string)=@_;
                   2344:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2345:     return @$array;
                   2346: }
                   2347: 
                   2348: sub str2arrayref {
1.204     albertel 2349:   my ($string) = @_;
1.265     albertel 2350:   my @array;
                   2351: 
                   2352:   if($string !~ /^__ARRAY_REF__/) {
                   2353:       if (! ($string eq '' || !defined($string))) {
                   2354: 	  $array[0]='Array reference error';
                   2355:       }
                   2356:       return (\@array, $string);
                   2357:   }
                   2358: 
                   2359:   $string =~ s/^__ARRAY_REF__//;
                   2360: 
                   2361:   while($string !~ /^__END_ARRAY_REF__/) {
                   2362:       my $value='';
                   2363:       if($string =~ /^__HASH_REF__/) {
                   2364:           ($value, $string)=&str2hashref($string);
                   2365:           if(defined($value->{'error'})) {
                   2366:               $array[0] ='Array reference error';
                   2367:               return (\@array, $string);
                   2368:           }
                   2369:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2370:           ($value, $string)=&str2arrayref($string);
                   2371:           if($value->[0] eq 'Array reference error') {
                   2372:               $array[0] ='Array reference error';
                   2373:               return (\@array, $string);
                   2374:           }
                   2375:       } else {
                   2376: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2377:       }
                   2378:       $string =~ s/^&//;
                   2379: 
                   2380:       push(@array, $value);
1.191     harris41 2381:   }
1.265     albertel 2382: 
                   2383:   $string =~ s/^__END_ARRAY_REF__//;
                   2384: 
                   2385:   return (\@array, $string);
1.168     albertel 2386: }
                   2387: 
1.167     albertel 2388: # -------------------------------------------------------------------Temp Store
                   2389: 
1.168     albertel 2390: sub tmpreset {
                   2391:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2392:   if (!$symb) {
                   2393:     $symb=&symbread();
1.620     albertel 2394:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2395:   }
                   2396:   $symb=escape($symb);
                   2397: 
1.620     albertel 2398:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2399:   $namespace=~s/\//\_/g;
                   2400:   $namespace=~s/\W//g;
                   2401: 
1.620     albertel 2402:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2403:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2404:   if ($domain eq 'public' && $stuname eq 'public') {
                   2405:       $stuname=$ENV{'REMOTE_ADDR'};
                   2406:   }
1.168     albertel 2407:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2408:   my %hash;
                   2409:   if (tie(%hash,'GDBM_File',
                   2410: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2411: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2412:     foreach my $key (keys %hash) {
1.180     albertel 2413:       if ($key=~ /:$symb/) {
1.168     albertel 2414: 	delete($hash{$key});
                   2415:       }
                   2416:     }
                   2417:   }
                   2418: }
                   2419: 
1.167     albertel 2420: sub tmpstore {
1.168     albertel 2421:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2422: 
                   2423:   if (!$symb) {
                   2424:     $symb=&symbread();
1.620     albertel 2425:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2426:   }
                   2427:   $symb=escape($symb);
                   2428: 
                   2429:   if (!$namespace) {
                   2430:     # I don't think we would ever want to store this for a course.
                   2431:     # it seems this will only be used if we don't have a course.
1.620     albertel 2432:     #$namespace=$env{'request.course.id'};
1.168     albertel 2433:     #if (!$namespace) {
1.620     albertel 2434:       $namespace=$env{'request.state'};
1.168     albertel 2435:     #}
                   2436:   }
                   2437:   $namespace=~s/\//\_/g;
                   2438:   $namespace=~s/\W//g;
1.620     albertel 2439:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2440:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2441:   if ($domain eq 'public' && $stuname eq 'public') {
                   2442:       $stuname=$ENV{'REMOTE_ADDR'};
                   2443:   }
1.168     albertel 2444:   my $now=time;
                   2445:   my %hash;
                   2446:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2447:   if (tie(%hash,'GDBM_File',
                   2448: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2449: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2450:     $hash{"version:$symb"}++;
                   2451:     my $version=$hash{"version:$symb"};
                   2452:     my $allkeys=''; 
                   2453:     foreach my $key (keys(%$storehash)) {
                   2454:       $allkeys.=$key.':';
1.591     albertel 2455:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2456:     }
                   2457:     $hash{"$version:$symb:timestamp"}=$now;
                   2458:     $allkeys.='timestamp';
                   2459:     $hash{"$version:keys:$symb"}=$allkeys;
                   2460:     if (untie(%hash)) {
                   2461:       return 'ok';
                   2462:     } else {
                   2463:       return "error:$!";
                   2464:     }
                   2465:   } else {
                   2466:     return "error:$!";
                   2467:   }
                   2468: }
1.167     albertel 2469: 
1.168     albertel 2470: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2471: 
1.168     albertel 2472: sub tmprestore {
                   2473:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2474: 
1.168     albertel 2475:   if (!$symb) {
                   2476:     $symb=&symbread();
1.620     albertel 2477:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2478:   }
                   2479:   $symb=escape($symb);
                   2480: 
1.620     albertel 2481:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2482: 
1.620     albertel 2483:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2484:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2485:   if ($domain eq 'public' && $stuname eq 'public') {
                   2486:       $stuname=$ENV{'REMOTE_ADDR'};
                   2487:   }
1.168     albertel 2488:   my %returnhash;
                   2489:   $namespace=~s/\//\_/g;
                   2490:   $namespace=~s/\W//g;
                   2491:   my %hash;
                   2492:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2493:   if (tie(%hash,'GDBM_File',
                   2494: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2495: 	  &GDBM_READER(),0640)) {
1.168     albertel 2496:     my $version=$hash{"version:$symb"};
                   2497:     $returnhash{'version'}=$version;
                   2498:     my $scope;
                   2499:     for ($scope=1;$scope<=$version;$scope++) {
                   2500:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2501:       my @keys=split(/:/,$vkeys);
                   2502:       my $key;
                   2503:       $returnhash{"$scope:keys"}=$vkeys;
                   2504:       foreach $key (@keys) {
1.591     albertel 2505: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2506: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2507:       }
                   2508:     }
1.168     albertel 2509:     if (!(untie(%hash))) {
                   2510:       return "error:$!";
                   2511:     }
                   2512:   } else {
                   2513:     return "error:$!";
                   2514:   }
                   2515:   return %returnhash;
1.167     albertel 2516: }
                   2517: 
1.9       www      2518: # ----------------------------------------------------------------------- Store
                   2519: 
                   2520: sub store {
1.124     www      2521:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2522:     my $home='';
                   2523: 
1.168     albertel 2524:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2525: 
1.213     www      2526:     $symb=&symbclean($symb);
1.122     albertel 2527:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2528: 
1.620     albertel 2529:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2530:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2531: 
                   2532:     &devalidate($symb,$stuname,$domain);
1.109     www      2533: 
                   2534:     $symb=escape($symb);
1.187     www      2535:     if (!$namespace) { 
1.620     albertel 2536:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2537:           return ''; 
                   2538:        } 
                   2539:     }
1.620     albertel 2540:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2541: 
                   2542:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2543:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2544: 
1.12      www      2545:     my $namevalue='';
1.191     harris41 2546:     foreach (keys %$storehash) {
1.591     albertel 2547:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2548:     }
1.12      www      2549:     $namevalue=~s/\&$//;
1.187     www      2550:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2551:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2552: }
                   2553: 
1.47      www      2554: # -------------------------------------------------------------- Critical Store
                   2555: 
                   2556: sub cstore {
1.124     www      2557:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2558:     my $home='';
                   2559: 
1.168     albertel 2560:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2561: 
1.213     www      2562:     $symb=&symbclean($symb);
1.122     albertel 2563:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2564: 
1.620     albertel 2565:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2566:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2567: 
                   2568:     &devalidate($symb,$stuname,$domain);
1.109     www      2569: 
                   2570:     $symb=escape($symb);
1.187     www      2571:     if (!$namespace) { 
1.620     albertel 2572:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2573:           return ''; 
                   2574:        } 
                   2575:     }
1.620     albertel 2576:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2577: 
                   2578:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2579:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2580: 
1.47      www      2581:     my $namevalue='';
1.191     harris41 2582:     foreach (keys %$storehash) {
1.591     albertel 2583:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2584:     }
1.47      www      2585:     $namevalue=~s/\&$//;
1.187     www      2586:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2587:     return critical
                   2588:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2589: }
                   2590: 
1.9       www      2591: # --------------------------------------------------------------------- Restore
                   2592: 
                   2593: sub restore {
1.124     www      2594:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2595:     my $home='';
                   2596: 
1.168     albertel 2597:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2598: 
1.122     albertel 2599:     if (!$symb) {
                   2600:       unless ($symb=escape(&symbread())) { return ''; }
                   2601:     } else {
1.213     www      2602:       $symb=&escape(&symbclean($symb));
1.122     albertel 2603:     }
1.188     www      2604:     if (!$namespace) { 
1.620     albertel 2605:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2606:           return ''; 
                   2607:        } 
                   2608:     }
1.620     albertel 2609:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2610:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2611:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2612:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2613: 
1.12      www      2614:     my %returnhash=();
1.191     harris41 2615:     foreach (split(/\&/,$answer)) {
1.12      www      2616: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2617:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2618:     }
1.75      www      2619:     my $version;
                   2620:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2621:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2622:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2623:        }
1.75      www      2624:     }
1.13      www      2625:     return %returnhash;
1.34      www      2626: }
                   2627: 
                   2628: # ---------------------------------------------------------- Course Description
                   2629: 
                   2630: sub coursedescription {
1.731     albertel 2631:     my ($courseid,$args)=@_;
1.34      www      2632:     $courseid=~s/^\///;
1.49      www      2633:     $courseid=~s/\_/\//g;
1.34      www      2634:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2635:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2636:     my $normalid=$cdomain.'_'.$cnum;
                   2637:     # need to always cache even if we get errors otherwise we keep 
                   2638:     # trying and trying and trying to get the course description.
                   2639:     my %envhash=();
                   2640:     my %returnhash=();
1.731     albertel 2641:     
                   2642:     my $expiretime=600;
                   2643:     if ($env{'request.course.id'} eq $normalid) {
                   2644: 	$expiretime=120;
                   2645:     }
                   2646: 
                   2647:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2648:     if (!$args->{'freshen_cache'}
                   2649: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2650: 	foreach my $key (keys(%env)) {
                   2651: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2652: 	    my ($setting) = $1;
                   2653: 	    $returnhash{$setting} = $env{$key};
                   2654: 	}
                   2655: 	return %returnhash;
                   2656:     }
                   2657: 
                   2658:     # get the data agin
                   2659:     if (!$args->{'one_time'}) {
                   2660: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2661:     }
1.34      www      2662:     if ($chome ne 'no_host') {
1.302     albertel 2663:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2664:        if (!exists($returnhash{'con_lost'})) {
                   2665:            $returnhash{'home'}= $chome;
                   2666: 	   $returnhash{'domain'} = $cdomain;
                   2667: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2668:            if (!defined($returnhash{'type'})) {
                   2669:                $returnhash{'type'} = 'Course';
                   2670:            }
1.130     albertel 2671:            while (my ($name,$value) = each %returnhash) {
1.53      www      2672:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2673:            }
1.270     www      2674:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2675:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2676: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2677:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2678:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2679:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2680:        }
                   2681:     }
1.731     albertel 2682:     if (!$args->{'one_time'}) {
                   2683: 	&appenv(%envhash);
                   2684:     }
1.302     albertel 2685:     return %returnhash;
1.461     www      2686: }
                   2687: 
                   2688: # -------------------------------------------------See if a user is privileged
                   2689: 
                   2690: sub privileged {
                   2691:     my ($username,$domain)=@_;
                   2692:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2693: 			&homeserver($username,$domain));
                   2694:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2695:     my $now=time;
                   2696:     if ($rolesdump ne '') {
                   2697:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2698: 	    if ($_!~/^rolesdef_/) {
1.461     www      2699: 		my ($area,$role)=split(/=/,$_);
                   2700: 		$area=~s/\_\w\w$//;
                   2701: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2702: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2703: 		    my $active=1;
                   2704: 		    if ($tend) {
                   2705: 			if ($tend<$now) { $active=0; }
                   2706: 		    }
                   2707: 		    if ($tstart) {
                   2708: 			if ($tstart>$now) { $active=0; }
                   2709: 		    }
                   2710: 		    if ($active) { return 1; }
                   2711: 		}
                   2712: 	    }
                   2713: 	}
                   2714:     }
                   2715:     return 0;
1.9       www      2716: }
1.1       albertel 2717: 
1.103     harris41 2718: # -------------------------------------------------------- Get user privileges
1.11      www      2719: 
                   2720: sub rolesinit {
                   2721:     my ($domain,$username,$authhost)=@_;
                   2722:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2723:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2724:     my %allroles=();
1.678     raeburn  2725:     my %allgroups=();   
1.11      www      2726:     my $now=time;
1.743     albertel 2727:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2728:     my $group_privs;
1.11      www      2729: 
                   2730:     if ($rolesdump ne '') {
1.191     harris41 2731:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2732: 	  if ($_!~/^rolesdef_/) {
1.11      www      2733:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2734: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2735:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2736: 	    if ($role=~/^cr/) { 
1.655     albertel 2737: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2738: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2739: 		    ($tend,$tstart)=split('_',$trest);
                   2740: 		} else {
                   2741: 		    $trole=$role;
                   2742: 		}
1.678     raeburn  2743:             } elsif ($role =~ m|^gr/|) {
                   2744:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2745:                 ($trole,$group_privs) = split(/\//,$trole);
                   2746:                 $group_privs = &unescape($group_privs);
1.587     albertel 2747: 	    } else {
                   2748: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2749: 	    }
1.743     albertel 2750: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2751: 					 $username);
                   2752: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2753:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2754:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2755:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2756: 		my $spec=$trole.'.'.$area;
                   2757: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2758: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2759:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2760:                 } elsif ($trole eq 'gr') {
                   2761:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2762: 		} else {
1.567     raeburn  2763:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2764: 		}
1.12      www      2765:             }
1.662     raeburn  2766:           }
1.191     harris41 2767:         }
1.743     albertel 2768:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2769:         $userroles{'user.adv'}    = $adv;
                   2770: 	$userroles{'user.author'} = $author;
1.620     albertel 2771:         $env{'user.adv'}=$adv;
1.11      www      2772:     }
1.743     albertel 2773:     return \%userroles;  
1.11      www      2774: }
                   2775: 
1.567     raeburn  2776: sub set_arearole {
                   2777:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2778: # log the associated role with the area
                   2779:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2780:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2781: }
                   2782: 
                   2783: sub custom_roleprivs {
                   2784:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2785:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2786:     my $homsvr=homeserver($rauthor,$rdomain);
                   2787:     if ($hostname{$homsvr} ne '') {
                   2788:         my ($rdummy,$roledef)=
                   2789:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2790:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2791:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2792:             if (defined($syspriv)) {
                   2793:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2794:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2795:             }
                   2796:             if ($tdomain ne '') {
                   2797:                 if (defined($dompriv)) {
                   2798:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2799:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2800:                 }
                   2801:                 if (($trest ne '') && (defined($coursepriv))) {
                   2802:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2803:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2804:                 }
                   2805:             }
                   2806:         }
                   2807:     }
                   2808: }
                   2809: 
1.678     raeburn  2810: sub group_roleprivs {
                   2811:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2812:     my $access = 1;
                   2813:     my $now = time;
                   2814:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2815:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2816:     if ($access) {
                   2817:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2818:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2819:     }
                   2820: }
1.567     raeburn  2821: 
                   2822: sub standard_roleprivs {
                   2823:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2824:     if (defined($pr{$trole.':s'})) {
                   2825:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2826:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2827:     }
                   2828:     if ($tdomain ne '') {
                   2829:         if (defined($pr{$trole.':d'})) {
                   2830:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2831:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2832:         }
                   2833:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2834:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2835:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2836:         }
                   2837:     }
                   2838: }
                   2839: 
                   2840: sub set_userprivs {
1.678     raeburn  2841:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2842:     my $author=0;
                   2843:     my $adv=0;
1.678     raeburn  2844:     my %grouproles = ();
                   2845:     if (keys(%{$allgroups}) > 0) {
                   2846:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2847:             my ($trole,$area,$sec,$extendedarea);
                   2848:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
1.678     raeburn  2849:                 $trole = $1;
                   2850:                 $area = $2;
1.681     raeburn  2851:                 $sec = $3;
                   2852:                 $extendedarea = $area.$sec;
                   2853:                 if (exists($$allgroups{$area})) {
                   2854:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2855:                         my $spec = $trole.'.'.$extendedarea;
                   2856:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2857:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2858:                     }
                   2859:                 }
                   2860:             }
                   2861:         }
                   2862:     }
                   2863:     foreach (keys(%grouproles)) {
                   2864:         $$allroles{$_} = $grouproles{$_};
                   2865:     }
1.567     raeburn  2866:     foreach (keys %{$allroles}) {
                   2867:         my %thesepriv=();
                   2868:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2869:         foreach (split(/:/,$$allroles{$_})) {
                   2870:             if ($_ ne '') {
                   2871:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2872:                 if ($restrictions eq '') {
                   2873:                     $thesepriv{$privilege}='F';
                   2874:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2875:                     $thesepriv{$privilege}.=$restrictions;
                   2876:                 }
                   2877:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2878:             }
                   2879:         }
                   2880:         my $thesestr='';
                   2881:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2882:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2883:     }
                   2884:     return ($author,$adv);
                   2885: }
                   2886: 
1.12      www      2887: # --------------------------------------------------------------- get interface
                   2888: 
                   2889: sub get {
1.131     albertel 2890:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2891:    my $items='';
1.191     harris41 2892:    foreach (@$storearr) {
1.12      www      2893:        $items.=escape($_).'&';
1.191     harris41 2894:    }
1.12      www      2895:    $items=~s/\&$//;
1.620     albertel 2896:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2897:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2898:    my $uhome=&homeserver($uname,$udomain);
                   2899: 
1.133     albertel 2900:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2901:    my @pairs=split(/\&/,$rep);
1.273     albertel 2902:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2903:      return @pairs;
                   2904:    }
1.15      www      2905:    my %returnhash=();
1.42      www      2906:    my $i=0;
1.191     harris41 2907:    foreach (@$storearr) {
1.557     albertel 2908:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2909:       $i++;
1.191     harris41 2910:    }
1.15      www      2911:    return %returnhash;
1.27      www      2912: }
                   2913: 
                   2914: # --------------------------------------------------------------- del interface
                   2915: 
                   2916: sub del {
1.133     albertel 2917:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2918:    my $items='';
1.191     harris41 2919:    foreach (@$storearr) {
1.27      www      2920:        $items.=escape($_).'&';
1.191     harris41 2921:    }
1.27      www      2922:    $items=~s/\&$//;
1.620     albertel 2923:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2924:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2925:    my $uhome=&homeserver($uname,$udomain);
                   2926: 
                   2927:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2928: }
                   2929: 
                   2930: # -------------------------------------------------------------- dump interface
                   2931: 
                   2932: sub dump {
1.755     albertel 2933:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2934:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2935:     if (!$uname) { $uname=$env{'user.name'}; }
                   2936:     my $uhome=&homeserver($uname,$udomain);
                   2937:     if ($regexp) {
                   2938: 	$regexp=&escape($regexp);
                   2939:     } else {
                   2940: 	$regexp='.';
                   2941:     }
                   2942:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2943:     my @pairs=split(/\&/,$rep);
                   2944:     my %returnhash=();
                   2945:     foreach my $item (@pairs) {
                   2946: 	my ($key,$value)=split(/=/,$item,2);
                   2947: 	$key = &unescape($key);
                   2948: 	next if ($key =~ /^error: 2 /);
                   2949: 	$returnhash{$key}=&thaw_unescape($value);
                   2950:     }
                   2951:     return %returnhash;
1.407     www      2952: }
                   2953: 
1.717     albertel 2954: # --------------------------------------------------------- dumpstore interface
                   2955: 
                   2956: sub dumpstore {
                   2957:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2958:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2959: }
                   2960: 
1.407     www      2961: # -------------------------------------------------------------- keys interface
                   2962: 
                   2963: sub getkeys {
                   2964:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2965:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2966:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2967:    my $uhome=&homeserver($uname,$udomain);
                   2968:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2969:    my @keyarray=();
                   2970:    foreach (split(/\&/,$rep)) {
                   2971:       push (@keyarray,&unescape($_));
                   2972:    }
                   2973:    return @keyarray;
1.318     matthew  2974: }
                   2975: 
1.319     matthew  2976: # --------------------------------------------------------------- currentdump
                   2977: sub currentdump {
1.328     matthew  2978:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2979:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2980:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2981:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2982:    my $uhome = &homeserver($sname,$sdom);
                   2983:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2984:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2985:    #
1.318     matthew  2986:    my %returnhash=();
1.319     matthew  2987:    #
                   2988:    if ($rep eq "unknown_cmd") { 
                   2989:        # an old lond will not know currentdump
                   2990:        # Do a dump and make it look like a currentdump
1.326     matthew  2991:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2992:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2993:        my %hash = @tmp;
                   2994:        @tmp=();
1.424     matthew  2995:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2996:    } else {
                   2997:        my @pairs=split(/\&/,$rep);
                   2998:        foreach (@pairs) {
                   2999:            my ($key,$value)=split(/=/,$_);
                   3000:            my ($symb,$param) = split(/:/,$key);
                   3001:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3002:                                                         &thaw_unescape($value);
1.319     matthew  3003:        }
1.191     harris41 3004:    }
1.12      www      3005:    return %returnhash;
1.424     matthew  3006: }
                   3007: 
                   3008: sub convert_dump_to_currentdump{
                   3009:     my %hash = %{shift()};
                   3010:     my %returnhash;
                   3011:     # Code ripped from lond, essentially.  The only difference
                   3012:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3013:     # we might run in to problems with parameter names =~ /^v\./
                   3014:     while (my ($key,$value) = each(%hash)) {
                   3015:         my ($v,$symb,$param) = split(/:/,$key);
                   3016:         next if ($v eq 'version' || $symb eq 'keys');
                   3017:         next if (exists($returnhash{$symb}) &&
                   3018:                  exists($returnhash{$symb}->{$param}) &&
                   3019:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3020:         $returnhash{$symb}->{$param}=$value;
                   3021:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3022:     }
                   3023:     #
                   3024:     # Remove all of the keys in the hashes which keep track of
                   3025:     # the version of the parameter.
                   3026:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3027:         # use a foreach because we are going to delete from the hash.
                   3028:         foreach my $key (keys(%$param_hash)) {
                   3029:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3030:         }
                   3031:     }
                   3032:     return \%returnhash;
1.12      www      3033: }
                   3034: 
1.627     albertel 3035: # ------------------------------------------------------ critical inc interface
                   3036: 
                   3037: sub cinc {
                   3038:     return &inc(@_,'critical');
                   3039: }
                   3040: 
1.449     matthew  3041: # --------------------------------------------------------------- inc interface
                   3042: 
                   3043: sub inc {
1.627     albertel 3044:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3045:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3046:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3047:     my $uhome=&homeserver($uname,$udomain);
                   3048:     my $items='';
                   3049:     if (! ref($store)) {
                   3050:         # got a single value, so use that instead
                   3051:         $items = &escape($store).'=&';
                   3052:     } elsif (ref($store) eq 'SCALAR') {
                   3053:         $items = &escape($$store).'=&';        
                   3054:     } elsif (ref($store) eq 'ARRAY') {
                   3055:         $items = join('=&',map {&escape($_);} @{$store});
                   3056:     } elsif (ref($store) eq 'HASH') {
                   3057:         while (my($key,$value) = each(%{$store})) {
                   3058:             $items.= &escape($key).'='.&escape($value).'&';
                   3059:         }
                   3060:     }
                   3061:     $items=~s/\&$//;
1.627     albertel 3062:     if ($critical) {
                   3063: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3064:     } else {
                   3065: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3066:     }
1.449     matthew  3067: }
                   3068: 
1.12      www      3069: # --------------------------------------------------------------- put interface
                   3070: 
                   3071: sub put {
1.134     albertel 3072:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3073:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3074:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3075:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3076:    my $items='';
1.191     harris41 3077:    foreach (keys %$storehash) {
1.557     albertel 3078:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3079:    }
1.12      www      3080:    $items=~s/\&$//;
1.134     albertel 3081:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3082: }
                   3083: 
1.631     albertel 3084: # ------------------------------------------------------------ newput interface
                   3085: 
                   3086: sub newput {
                   3087:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3088:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3089:    if (!$uname) { $uname=$env{'user.name'}; }
                   3090:    my $uhome=&homeserver($uname,$udomain);
                   3091:    my $items='';
                   3092:    foreach my $key (keys(%$storehash)) {
                   3093:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3094:    }
                   3095:    $items=~s/\&$//;
                   3096:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3097: }
                   3098: 
                   3099: # ---------------------------------------------------------  putstore interface
                   3100: 
1.524     raeburn  3101: sub putstore {
1.715     albertel 3102:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3104:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3105:    my $uhome=&homeserver($uname,$udomain);
                   3106:    my $items='';
1.715     albertel 3107:    foreach my $key (keys(%$storehash)) {
                   3108:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3109:    }
1.715     albertel 3110:    $items=~s/\&$//;
1.716     albertel 3111:    my $esc_symb=&escape($symb);
                   3112:    my $esc_v=&escape($version);
1.715     albertel 3113:    my $reply =
1.716     albertel 3114:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3115: 	      $uhome);
                   3116:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3117:        # gfall back to way things use to be done
1.715     albertel 3118:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3119: 			    $uname);
1.524     raeburn  3120:    }
1.715     albertel 3121:    return $reply;
                   3122: }
                   3123: 
                   3124: sub old_putstore {
1.716     albertel 3125:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3126:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3127:     if (!$uname) { $uname=$env{'user.name'}; }
                   3128:     my $uhome=&homeserver($uname,$udomain);
                   3129:     my %newstorehash;
                   3130:     foreach (keys %$storehash) {
                   3131: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3132: 	$newstorehash{$key} = $storehash->{$_};
                   3133:     }
                   3134:     my $items='';
                   3135:     my %allitems = ();
                   3136:     foreach (keys %newstorehash) {
                   3137: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3138: 	    my $key = $1.':keys:'.$2;
                   3139: 	    $allitems{$key} .= $3.':';
                   3140: 	}
                   3141: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3142:     }
                   3143:     foreach (keys %allitems) {
                   3144: 	$allitems{$_} =~ s/\:$//;
                   3145: 	$items.= $_.'='.$allitems{$_}.'&';
                   3146:     }
                   3147:     $items=~s/\&$//;
                   3148:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3149: }
                   3150: 
1.47      www      3151: # ------------------------------------------------------ critical put interface
                   3152: 
                   3153: sub cput {
1.134     albertel 3154:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3155:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3156:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3157:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3158:    my $items='';
1.191     harris41 3159:    foreach (keys %$storehash) {
1.715     albertel 3160:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3161:    }
1.47      www      3162:    $items=~s/\&$//;
1.134     albertel 3163:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3164: }
                   3165: 
                   3166: # -------------------------------------------------------------- eget interface
                   3167: 
                   3168: sub eget {
1.133     albertel 3169:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3170:    my $items='';
1.191     harris41 3171:    foreach (@$storearr) {
1.12      www      3172:        $items.=escape($_).'&';
1.191     harris41 3173:    }
1.12      www      3174:    $items=~s/\&$//;
1.620     albertel 3175:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3176:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3177:    my $uhome=&homeserver($uname,$udomain);
                   3178:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3179:    my @pairs=split(/\&/,$rep);
                   3180:    my %returnhash=();
1.42      www      3181:    my $i=0;
1.191     harris41 3182:    foreach (@$storearr) {
1.557     albertel 3183:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3184:       $i++;
1.191     harris41 3185:    }
1.12      www      3186:    return %returnhash;
                   3187: }
                   3188: 
1.667     albertel 3189: # ------------------------------------------------------------ tmpput interface
                   3190: sub tmpput {
                   3191:     my ($storehash,$server)=@_;
                   3192:     my $items='';
                   3193:     foreach (keys(%$storehash)) {
                   3194: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3195:     }
                   3196:     $items=~s/\&$//;
                   3197:     return &reply("tmpput:$items",$server);
                   3198: }
                   3199: 
                   3200: # ------------------------------------------------------------ tmpget interface
                   3201: sub tmpget {
1.688     albertel 3202:     my ($token,$server)=@_;
                   3203:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3204:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3205:     my %returnhash;
                   3206:     foreach my $item (split(/\&/,$rep)) {
                   3207: 	my ($key,$value)=split(/=/,$item);
                   3208: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3209:     }
                   3210:     return %returnhash;
                   3211: }
                   3212: 
1.688     albertel 3213: # ------------------------------------------------------------ tmpget interface
                   3214: sub tmpdel {
                   3215:     my ($token,$server)=@_;
                   3216:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3217:     return &reply("tmpdel:$token",$server);
                   3218: }
                   3219: 
1.765     albertel 3220: # -------------------------------------------------- portfolio access checking
                   3221: 
                   3222: sub portfolio_access {
1.766     albertel 3223:     my ($requrl) = @_;
1.765     albertel 3224:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3225:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3226:     if ($result eq 'ok') {
1.766     albertel 3227:        return 'F';
1.765     albertel 3228:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3229:        return 'A';
1.765     albertel 3230:     }
1.766     albertel 3231:     return '';
1.765     albertel 3232: }
                   3233: 
                   3234: sub get_portfolio_access {
1.767     albertel 3235:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3236: 
                   3237:     if (!ref($access_hash)) {
                   3238: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3239: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3240: 						   $file_name);
                   3241: 	$access_hash = $access_controls{$file_name};
                   3242:     }
                   3243: 
1.765     albertel 3244:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3245:     my $now = time;
                   3246:     if (ref($access_hash) eq 'HASH') {
                   3247:         foreach my $key (keys(%{$access_hash})) {
                   3248:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3249:             if ($start > $now) {
                   3250:                 next;
                   3251:             }
                   3252:             if ($end && $end<$now) {
                   3253:                 next;
                   3254:             }
                   3255:             if ($scope eq 'public') {
                   3256:                 $public = $key;
                   3257:                 last;
                   3258:             } elsif ($scope eq 'guest') {
                   3259:                 $guest = $key;
                   3260:             } elsif ($scope eq 'domains') {
                   3261:                 push(@domains,$key);
                   3262:             } elsif ($scope eq 'users') {
                   3263:                 push(@users,$key);
                   3264:             } elsif ($scope eq 'course') {
                   3265:                 push(@courses,$key);
                   3266:             } elsif ($scope eq 'group') {
                   3267:                 push(@groups,$key);
                   3268:             }
                   3269:         }
                   3270:         if ($public) {
                   3271:             return 'ok';
                   3272:         }
                   3273:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3274:             if ($guest) {
                   3275:                 return $guest;
                   3276:             }
                   3277:         } else {
                   3278:             if (@domains > 0) {
                   3279:                 foreach my $domkey (@domains) {
                   3280:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3281:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3282:                             return 'ok';
                   3283:                         }
                   3284:                     }
                   3285:                 }
                   3286:             }
                   3287:             if (@users > 0) {
                   3288:                 foreach my $userkey (@users) {
                   3289:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3290:                         return 'ok';
                   3291:                     }
                   3292:                 }
                   3293:             }
                   3294:             my %roleshash;
                   3295:             my @courses_and_groups = @courses;
                   3296:             push(@courses_and_groups,@groups); 
                   3297:             if (@courses_and_groups > 0) {
                   3298:                 my (%allgroups,%allroles); 
                   3299:                 my ($start,$end,$role,$sec,$group);
                   3300:                 foreach my $envkey (%env) {
                   3301:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3302:                         my $cid = $2.'_'.$3; 
                   3303:                         if ($1 eq 'gr') {
                   3304:                             $group = $4;
                   3305:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3306:                         } else {
                   3307:                             if ($4 eq '') {
                   3308:                                 $sec = 'none';
                   3309:                             } else {
                   3310:                                 $sec = $4;
                   3311:                             }
                   3312:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3313:                         }
                   3314:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3315:                         my $cid = $2.'_'.$3;
                   3316:                         if ($4 eq '') {
                   3317:                             $sec = 'none';
                   3318:                         } else {
                   3319:                             $sec = $4;
                   3320:                         }
                   3321:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3322:                     }
                   3323:                 }
                   3324:                 if (keys(%allroles) == 0) {
                   3325:                     return;
                   3326:                 }
                   3327:                 foreach my $key (@courses_and_groups) {
                   3328:                     my %content = %{$$access_hash{$key}};
                   3329:                     my $cnum = $content{'number'};
                   3330:                     my $cdom = $content{'domain'};
                   3331:                     my $cid = $cdom.'_'.$cnum;
                   3332:                     if (!exists($allroles{$cid})) {
                   3333:                         next;
                   3334:                     }    
                   3335:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3336:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3337:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3338:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3339:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3340:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3341:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3342:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3343:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3344:                                         if (grep/^all$/,@sections) {
                   3345:                                             return 'ok';
                   3346:                                         } else {
                   3347:                                             if (grep/^$sec$/,@sections) {
                   3348:                                                 return 'ok';
                   3349:                                             }
                   3350:                                         }
                   3351:                                     }
                   3352:                                 }
                   3353:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3354:                                     if (grep/^none$/,@groups) {
                   3355:                                         return 'ok';
                   3356:                                     }
                   3357:                                 } else {
                   3358:                                     if (grep/^all$/,@groups) {
                   3359:                                         return 'ok';
                   3360:                                     } 
                   3361:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3362:                                         if (grep/^$group$/,@groups) {
                   3363:                                             return 'ok';
                   3364:                                         }
                   3365:                                     }
                   3366:                                 } 
                   3367:                             }
                   3368:                         }
                   3369:                     }
                   3370:                 }
                   3371:             }
                   3372:             if ($guest) {
                   3373:                 return $guest;
                   3374:             }
                   3375:         }
                   3376:     }
                   3377:     return;
                   3378: }
                   3379: 
                   3380: sub course_group_datechecker {
                   3381:     my ($dates,$now,$status) = @_;
                   3382:     my ($start,$end) = split(/\./,$dates);
                   3383:     if (!$start && !$end) {
                   3384:         return 'ok';
                   3385:     }
                   3386:     if (grep/^active$/,@{$status}) {
                   3387:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3388:             return 'ok';
                   3389:         }
                   3390:     }
                   3391:     if (grep/^previous$/,@{$status}) {
                   3392:         if ($end > $now ) {
                   3393:             return 'ok';
                   3394:         }
                   3395:     }
                   3396:     if (grep/^future$/,@{$status}) {
                   3397:         if ($start > $now) {
                   3398:             return 'ok';
                   3399:         }
                   3400:     }
                   3401:     return; 
                   3402: }
                   3403: 
                   3404: sub parse_portfolio_url {
                   3405:     my ($url) = @_;
                   3406: 
                   3407:     my ($type,$udom,$unum,$group,$file_name);
                   3408:     
                   3409:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3410: 	$type = 1;
                   3411:         $udom = $1;
                   3412:         $unum = $2;
                   3413:         $file_name = $3;
                   3414:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3415: 	$type = 2;
                   3416:         $udom = $1;
                   3417:         $unum = $2;
                   3418:         $group = $3;
                   3419:         $file_name = $3.'/'.$4;
                   3420:     }
                   3421:     if (wantarray) {
                   3422: 	return ($type,$udom,$unum,$file_name,$group);
                   3423:     }
                   3424:     return $type;
                   3425: }
                   3426: 
                   3427: sub is_portfolio_url {
                   3428:     my ($url) = @_;
                   3429:     return scalar(&parse_portfolio_url($url));
                   3430: }
                   3431: 
1.341     www      3432: # ---------------------------------------------- Custom access rule evaluation
                   3433: 
                   3434: sub customaccess {
                   3435:     my ($priv,$uri)=@_;
1.620     albertel 3436:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3437:     $urealm=~s/^\W//;
                   3438:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3439:     my $access=0;
                   3440:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3441: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3442:         if ($role) {
                   3443: 	   if ($role ne $urole) { next; }
                   3444:         }
                   3445:         foreach (split(/\s*\,\s*/,$realm)) {
                   3446:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3447:             if ($tdom) {
                   3448: 		if ($tdom ne $udom) { next; }
                   3449:             }
                   3450:             if ($tcrs) {
                   3451: 		if ($tcrs ne $ucrs) { next; }
                   3452:             }
                   3453:             if ($tsec) {
                   3454: 		if ($tsec ne $usec) { next; }
                   3455:             }
                   3456:             $access=($effect eq 'allow');
                   3457:             last;
1.342     www      3458:         }
1.402     bowersj2 3459: 	if ($realm eq '' && $role eq '') {
                   3460:             $access=($effect eq 'allow');
                   3461: 	}
1.341     www      3462:     }
                   3463:     return $access;
                   3464: }
                   3465: 
1.103     harris41 3466: # ------------------------------------------------- Check for a user privilege
1.12      www      3467: 
                   3468: sub allowed {
1.579     albertel 3469:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3470:     my $ver_orguri=$uri;
1.439     www      3471:     $uri=&deversion($uri);
1.152     www      3472:     my $orguri=$uri;
1.52      www      3473:     $uri=&declutter($uri);
1.545     banghart 3474:     
1.620     albertel 3475:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3476: # Free bre access to adm and meta resources
1.529     albertel 3477:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   3478: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      3479: 	return 'F';
1.159     www      3480:     }
                   3481: 
1.545     banghart 3482: # Free bre access to user's own portfolio contents
1.714     raeburn  3483:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3484:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3485: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3486:         return 'F';
                   3487:     }
                   3488: 
1.762     raeburn  3489: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3490:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3491:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3492:         if (exists($env{'request.course.id'})) {
                   3493:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3494:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3495:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3496:                 my $courseprivid=$env{'request.course.id'};
                   3497:                 $courseprivid=~s/\_/\//;
                   3498:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3499:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3500:                     return $1; 
1.762     raeburn  3501:                 } else {
                   3502:                     if ($env{'request.course.sec'}) {
                   3503:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3504:                     }
                   3505:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3506:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3507:                         return $2;
                   3508:                     }
1.714     raeburn  3509:                 }
                   3510:             }
                   3511:         }
                   3512:     }
                   3513: 
1.159     www      3514: # Free bre to public access
                   3515: 
                   3516:     if ($priv eq 'bre') {
1.238     www      3517:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3518: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3519:            return 'F'; 
                   3520:         }
1.238     www      3521:         if ($copyright eq 'priv') {
                   3522:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3523: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3524: 		return '';
                   3525:             }
                   3526:         }
                   3527:         if ($copyright eq 'domain') {
                   3528:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3529: 	    unless (($env{'user.domain'} eq $1) ||
                   3530:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3531: 		return '';
                   3532:             }
1.262     matthew  3533:         }
1.620     albertel 3534:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3535:             # Library role, so allow browsing of resources in this domain.
                   3536:             return 'F';
1.238     www      3537:         }
1.341     www      3538:         if ($copyright eq 'custom') {
                   3539: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3540:         }
1.14      www      3541:     }
1.264     matthew  3542:     # Domain coordinator is trying to create a course
1.620     albertel 3543:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3544:         # uri is the requested domain in this case.
                   3545:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3546:         # a role of dc for the domain in question.
1.620     albertel 3547:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3548:     }
1.29      www      3549: 
1.52      www      3550:     my $thisallowed='';
                   3551:     my $statecond=0;
                   3552:     my $courseprivid='';
                   3553: 
                   3554: # Course
                   3555: 
1.620     albertel 3556:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3557:        $thisallowed.=$1;
                   3558:     }
1.29      www      3559: 
1.52      www      3560: # Domain
                   3561: 
1.620     albertel 3562:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3563:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3564:        $thisallowed.=$1;
                   3565:     }
1.52      www      3566: 
                   3567: # Course: uri itself is a course
1.66      www      3568:     my $courseuri=$uri;
                   3569:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3570:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3571: 
1.620     albertel 3572:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3573:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3574:        $thisallowed.=$1;
                   3575:     }
1.29      www      3576: 
1.665     albertel 3577: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3578: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3579:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3580: 	$thisallowed='';
1.671     raeburn  3581:         my ($match)=&is_on_map($uri);
                   3582:         if ($match) {
                   3583:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3584:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3585:                 $thisallowed.=$1;
                   3586:             }
                   3587:         } else {
1.705     albertel 3588:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3589:             if ($refuri) {
                   3590:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3591:                     $thisallowed='F';
1.671     raeburn  3592:                 } else {
                   3593:                     $refuri=&declutter($refuri);
                   3594:                     my ($match) = &is_on_map($refuri);
                   3595:                     if ($match) {
                   3596:                         $thisallowed='F';
                   3597:                     }
1.669     raeburn  3598:                 }
1.671     raeburn  3599:             }
                   3600:         }
1.314     www      3601:     }
1.492     albertel 3602: 
1.766     albertel 3603:     if ($priv eq 'bre'
                   3604: 	&& $thisallowed ne 'F' 
                   3605: 	&& $thisallowed ne '2'
                   3606: 	&& &is_portfolio_url($uri)) {
                   3607: 	$thisallowed = &portfolio_access($uri);
                   3608:     }
                   3609:     
1.52      www      3610: # Full access at system, domain or course-wide level? Exit.
1.29      www      3611: 
                   3612:     if ($thisallowed=~/F/) {
                   3613: 	return 'F';
                   3614:     }
                   3615: 
1.52      www      3616: # If this is generating or modifying users, exit with special codes
1.29      www      3617: 
1.643     www      3618:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3619: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3620: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3621: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3622: 	    unless ($auname) { return $thisallowed; }
                   3623: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3624: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3625: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3626: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3627: 	}
1.52      www      3628: 	return $thisallowed;
                   3629:     }
                   3630: #
1.103     harris41 3631: # Gathered so far: system, domain and course wide privileges
1.52      www      3632: #
                   3633: # Course: See if uri or referer is an individual resource that is part of 
                   3634: # the course
                   3635: 
1.620     albertel 3636:     if ($env{'request.course.id'}) {
1.232     www      3637: 
1.620     albertel 3638:        $courseprivid=$env{'request.course.id'};
                   3639:        if ($env{'request.course.sec'}) {
                   3640:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3641:        }
                   3642:        $courseprivid=~s/\_/\//;
                   3643:        my $checkreferer=1;
1.232     www      3644:        my ($match,$cond)=&is_on_map($uri);
                   3645:        if ($match) {
                   3646:            $statecond=$cond;
1.620     albertel 3647:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3648:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3649:                $thisallowed.=$1;
                   3650:                $checkreferer=0;
                   3651:            }
1.29      www      3652:        }
1.83      www      3653:        
1.148     www      3654:        if ($checkreferer) {
1.620     albertel 3655: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3656:             unless ($refuri) {
1.620     albertel 3657:                 foreach (keys %env) {
1.148     www      3658: 		    if ($_=~/^httpref\..*\*/) {
                   3659: 			my $pattern=$_;
1.156     www      3660:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3661:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3662:                         $pattern=~s/\//\\\//g;
1.152     www      3663:                         if ($orguri=~/$pattern/) {
1.620     albertel 3664: 			    $refuri=$env{$_};
1.148     www      3665:                         }
                   3666:                     }
1.191     harris41 3667:                 }
1.148     www      3668:             }
1.232     www      3669: 
1.148     www      3670:          if ($refuri) { 
1.152     www      3671: 	  $refuri=&declutter($refuri);
1.232     www      3672:           my ($match,$cond)=&is_on_map($refuri);
                   3673:             if ($match) {
                   3674:               my $refstatecond=$cond;
1.620     albertel 3675:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3676:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3677:                   $thisallowed.=$1;
1.53      www      3678:                   $uri=$refuri;
                   3679:                   $statecond=$refstatecond;
1.52      www      3680:               }
                   3681:           }
1.148     www      3682:         }
1.29      www      3683:        }
1.52      www      3684:    }
1.29      www      3685: 
1.52      www      3686: #
1.103     harris41 3687: # Gathered now: all privileges that could apply, and condition number
1.52      www      3688: # 
                   3689: #
                   3690: # Full or no access?
                   3691: #
1.29      www      3692: 
1.52      www      3693:     if ($thisallowed=~/F/) {
                   3694: 	return 'F';
                   3695:     }
1.29      www      3696: 
1.52      www      3697:     unless ($thisallowed) {
                   3698:         return '';
                   3699:     }
1.29      www      3700: 
1.52      www      3701: # Restrictions exist, deal with them
                   3702: #
                   3703: #   C:according to course preferences
                   3704: #   R:according to resource settings
                   3705: #   L:unless locked
                   3706: #   X:according to user session state
                   3707: #
                   3708: 
                   3709: # Possibly locked functionality, check all courses
1.54      www      3710: # Locks might take effect only after 10 minutes cache expiration for other
                   3711: # courses, and 2 minutes for current course
1.52      www      3712: 
                   3713:     my $envkey;
                   3714:     if ($thisallowed=~/L/) {
1.620     albertel 3715:         foreach $envkey (keys %env) {
1.54      www      3716:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3717:                my $courseid=$2;
                   3718:                my $roleid=$1.'.'.$2;
1.92      www      3719:                $courseid=~s/^\///;
1.54      www      3720:                my $expiretime=600;
1.620     albertel 3721:                if ($env{'request.role'} eq $roleid) {
1.54      www      3722: 		  $expiretime=120;
                   3723:                }
                   3724: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3725:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3726:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3727: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3728:                }
1.620     albertel 3729:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3730:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3731: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3732:                        &log($env{'user.domain'},$env{'user.name'},
                   3733:                             $env{'user.home'},
1.57      www      3734:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3735:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3736:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3737: 		       return '';
                   3738:                    }
                   3739:                }
1.620     albertel 3740:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3741:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3742: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3743:                        &log($env{'user.domain'},$env{'user.name'},
                   3744:                             $env{'user.home'},
1.57      www      3745:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3746:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3747:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3748: 		       return '';
                   3749:                    }
                   3750:                }
                   3751: 	   }
1.29      www      3752:        }
1.52      www      3753:     }
                   3754:    
                   3755: #
                   3756: # Rest of the restrictions depend on selected course
                   3757: #
                   3758: 
1.620     albertel 3759:     unless ($env{'request.course.id'}) {
1.766     albertel 3760: 	if ($thisallowed eq 'A') {
                   3761: 	    return 'A';
                   3762: 	} else {
                   3763: 	    return '1';
                   3764: 	}
1.52      www      3765:     }
1.29      www      3766: 
1.52      www      3767: #
                   3768: # Now user is definitely in a course
                   3769: #
1.53      www      3770: 
                   3771: 
                   3772: # Course preferences
                   3773: 
                   3774:    if ($thisallowed=~/C/) {
1.620     albertel 3775:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3776:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3777:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3778: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3779: 	   if ($priv ne 'pch') { 
                   3780: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3781: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3782: 			$env{'request.course.id'});
                   3783: 	   }
1.237     www      3784:            return '';
                   3785:        }
                   3786: 
1.620     albertel 3787:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3788: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3789: 	   if ($priv ne 'pch') { 
                   3790: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3791: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3792: 			$env{'request.course.id'});
                   3793: 	   }
1.54      www      3794:            return '';
                   3795:        }
1.53      www      3796:    }
                   3797: 
                   3798: # Resource preferences
                   3799: 
                   3800:    if ($thisallowed=~/R/) {
1.620     albertel 3801:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3802:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3803: 	   if ($priv ne 'pch') { 
                   3804: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3805: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3806: 	   }
                   3807: 	   return '';
1.54      www      3808:        }
1.53      www      3809:    }
1.30      www      3810: 
1.246     www      3811: # Restricted by state or randomout?
1.30      www      3812: 
1.52      www      3813:    if ($thisallowed=~/X/) {
1.620     albertel 3814:       if ($env{'acc.randomout'}) {
1.579     albertel 3815: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3816:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3817:             return ''; 
                   3818:          }
1.247     www      3819:       }
                   3820:       if (&condval($statecond)) {
1.52      www      3821: 	 return '2';
                   3822:       } else {
                   3823:          return '';
                   3824:       }
                   3825:    }
1.30      www      3826: 
1.766     albertel 3827:     if ($thisallowed eq 'A') {
                   3828: 	return 'A';
                   3829:     }
1.52      www      3830:    return 'F';
1.232     www      3831: }
                   3832: 
1.710     albertel 3833: sub split_uri_for_cond {
                   3834:     my $uri=&deversion(&declutter(shift));
                   3835:     my @uriparts=split(/\//,$uri);
                   3836:     my $filename=pop(@uriparts);
                   3837:     my $pathname=join('/',@uriparts);
                   3838:     return ($pathname,$filename);
                   3839: }
1.232     www      3840: # --------------------------------------------------- Is a resource on the map?
                   3841: 
                   3842: sub is_on_map {
1.710     albertel 3843:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3844:     #Trying to find the conditional for the file
1.620     albertel 3845:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3846: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3847:     if ($match) {
1.289     bowersj2 3848: 	return (1,$1);
                   3849:     } else {
1.434     www      3850: 	return (0,0);
1.289     bowersj2 3851:     }
1.12      www      3852: }
                   3853: 
1.427     www      3854: # --------------------------------------------------------- Get symb from alias
                   3855: 
                   3856: sub get_symb_from_alias {
                   3857:     my $symb=shift;
                   3858:     my ($map,$resid,$url)=&decode_symb($symb);
                   3859: # Already is a symb
                   3860:     if ($url) { return $symb; }
                   3861: # Must be an alias
                   3862:     my $aliassymb='';
                   3863:     my %bighash;
1.620     albertel 3864:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3865:                             &GDBM_READER(),0640)) {
                   3866:         my $rid=$bighash{'mapalias_'.$symb};
                   3867: 	if ($rid) {
                   3868: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3869: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3870: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3871: 	}
                   3872:         untie %bighash;
                   3873:     }
                   3874:     return $aliassymb;
                   3875: }
                   3876: 
1.12      www      3877: # ----------------------------------------------------------------- Define Role
                   3878: 
                   3879: sub definerole {
                   3880:   if (allowed('mcr','/')) {
                   3881:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3882:     foreach (split(':',$sysrole)) {
1.21      www      3883: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3884:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3885:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3886: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3887:                return "refused:s:$crole&$cqual"; 
                   3888:             }
                   3889:         }
1.191     harris41 3890:     }
1.392     www      3891:     foreach (split(':',$domrole)) {
1.21      www      3892: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3893:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3894:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3895: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3896:                return "refused:d:$crole&$cqual"; 
                   3897:             }
                   3898:         }
1.191     harris41 3899:     }
1.392     www      3900:     foreach (split(':',$courole)) {
1.21      www      3901: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3902:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3903:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3904: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3905:                return "refused:c:$crole&$cqual"; 
                   3906:             }
                   3907:         }
1.191     harris41 3908:     }
1.620     albertel 3909:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3910:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3911: 	        "rolesdef_$rolename=".
                   3912:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3913:     return reply($command,$env{'user.home'});
1.12      www      3914:   } else {
                   3915:     return 'refused';
                   3916:   }
1.105     harris41 3917: }
                   3918: 
                   3919: # ---------------- Make a metadata query against the network of library servers
                   3920: 
                   3921: sub metadata_query {
1.244     matthew  3922:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3923:     my %rhash;
1.244     matthew  3924:     my @server_list = (defined($server_array) ? @$server_array
                   3925:                                               : keys(%libserv) );
                   3926:     for my $server (@server_list) {
1.118     harris41 3927: 	unless ($custom or $customshow) {
                   3928: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3929: 	    $rhash{$server}=$reply;
                   3930: 	}
                   3931: 	else {
                   3932: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3933: 			     &escape($custom).':'.&escape($customshow),
                   3934: 			     $server);
                   3935: 	    $rhash{$server}=$reply;
                   3936: 	}
1.112     harris41 3937:     }
1.118     harris41 3938:     return \%rhash;
1.240     www      3939: }
                   3940: 
                   3941: # ----------------------------------------- Send log queries and wait for reply
                   3942: 
                   3943: sub log_query {
                   3944:     my ($uname,$udom,$query,%filters)=@_;
                   3945:     my $uhome=&homeserver($uname,$udom);
                   3946:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3947:     my $uhost=$hostname{$uhome};
1.241     www      3948:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3949:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3950:                        $uhome);
1.479     albertel 3951:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3952:     return get_query_reply($queryid);
                   3953: }
                   3954: 
1.508     raeburn  3955: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3956: 
                   3957: sub fetch_enrollment_query {
1.511     raeburn  3958:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3959:     my $homeserver;
1.547     raeburn  3960:     my $maxtries = 1;
1.508     raeburn  3961:     if ($context eq 'automated') {
                   3962:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3963:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3964:     } else {
                   3965:         $homeserver = &homeserver($cnum,$dom);
                   3966:     }
1.506     raeburn  3967:     my $host=$hostname{$homeserver};
                   3968:     my $cmd = '';
                   3969:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3970:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3971:     }
                   3972:     $cmd =~ s/%%$//;
                   3973:     $cmd = &escape($cmd);
                   3974:     my $query = 'fetchenrollment';
1.620     albertel 3975:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3976:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3977:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3978:         return 'error: '.$queryid;
                   3979:     }
1.506     raeburn  3980:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3981:     my $tries = 1;
                   3982:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3983:         $reply = &get_query_reply($queryid);
                   3984:         $tries ++;
                   3985:     }
1.526     raeburn  3986:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3987:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3988:     } else {
1.515     raeburn  3989:         my @responses = split/:/,$reply;
                   3990:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3991:             foreach (@responses) {
                   3992:                 my ($key,$value) = split/=/,$_;
                   3993:                 $$replyref{$key} = $value;
                   3994:             }
                   3995:         } else {
1.506     raeburn  3996:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3997:             foreach (@responses) {
                   3998:                 my ($key,$value) = split/=/,$_;
                   3999:                 $$replyref{$key} = $value;
                   4000:                 if ($value > 0) {
                   4001:                     foreach (@{$$affiliatesref{$key}}) {
                   4002:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   4003:                         my $destname = $pathname.'/'.$filename;
                   4004:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4005:                         if ($xml_classlist =~ /^error/) {
                   4006:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4007:                         } else {
1.506     raeburn  4008:                             if ( open(FILE,">$destname") ) {
                   4009:                                 print FILE &unescape($xml_classlist);
                   4010:                                 close(FILE);
1.526     raeburn  4011:                             } else {
                   4012:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4013:                             }
                   4014:                         }
                   4015:                     }
                   4016:                 }
                   4017:             }
                   4018:         }
                   4019:         return 'ok';
                   4020:     }
                   4021:     return 'error';
                   4022: }
                   4023: 
1.242     www      4024: sub get_query_reply {
                   4025:     my $queryid=shift;
1.240     www      4026:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4027:     my $reply='';
                   4028:     for (1..100) {
                   4029: 	sleep 2;
                   4030:         if (-e $replyfile.'.end') {
1.448     albertel 4031: 	    if (open(my $fh,$replyfile)) {
1.240     www      4032:                $reply.=<$fh>;
1.448     albertel 4033:                close($fh);
1.240     www      4034: 	   } else { return 'error: reply_file_error'; }
1.242     www      4035:            return &unescape($reply);
                   4036: 	}
1.240     www      4037:     }
1.242     www      4038:     return 'timeout:'.$queryid;
1.240     www      4039: }
                   4040: 
                   4041: sub courselog_query {
1.241     www      4042: #
                   4043: # possible filters:
                   4044: # url: url or symb
                   4045: # username
                   4046: # domain
                   4047: # action: view, submit, grade
                   4048: # start: timestamp
                   4049: # end: timestamp
                   4050: #
1.240     www      4051:     my (%filters)=@_;
1.620     albertel 4052:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4053:     if ($filters{'url'}) {
                   4054: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4055:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4056:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4057:     }
1.620     albertel 4058:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4059:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4060:     return &log_query($cname,$cdom,'courselog',%filters);
                   4061: }
                   4062: 
                   4063: sub userlog_query {
                   4064:     my ($uname,$udom,%filters)=@_;
                   4065:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4066: }
                   4067: 
1.506     raeburn  4068: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4069: 
                   4070: sub auto_run {
1.508     raeburn  4071:     my ($cnum,$cdom) = @_;
                   4072:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4073:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4074:     return $response;
                   4075: }
                   4076:                                                                                    
                   4077: sub auto_get_sections {
1.508     raeburn  4078:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4079:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4080:     my @secs = ();
1.511     raeburn  4081:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4082:     unless ($response eq 'refused') {
                   4083:         @secs = split/:/,$response;
                   4084:     }
                   4085:     return @secs;
                   4086: }
                   4087:                                                                                    
                   4088: sub auto_new_course {
1.508     raeburn  4089:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4090:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4091:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4092:     return $response;
                   4093: }
                   4094:                                                                                    
                   4095: sub auto_validate_courseID {
1.508     raeburn  4096:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4097:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4098:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4099:     return $response;
                   4100: }
                   4101:                                                                                    
                   4102: sub auto_create_password {
1.508     raeburn  4103:     my ($cnum,$cdom,$authparam) = @_;
                   4104:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4105:     my $create_passwd = 0;
                   4106:     my $authchk = '';
1.511     raeburn  4107:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4108:     if ($response eq 'refused') {
                   4109:         $authchk = 'refused';
                   4110:     } else {
                   4111:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4112:     }
                   4113:     return ($authparam,$create_passwd,$authchk);
                   4114: }
                   4115: 
1.706     raeburn  4116: sub auto_photo_permission {
                   4117:     my ($cnum,$cdom,$students) = @_;
                   4118:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4119:     my ($outcome,$perm_reqd,$conditions) = 
                   4120: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4121:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4122: 	return (undef,undef);
                   4123:     }
1.706     raeburn  4124:     return ($outcome,$perm_reqd,$conditions);
                   4125: }
                   4126: 
                   4127: sub auto_checkphotos {
                   4128:     my ($uname,$udom,$pid) = @_;
                   4129:     my $homeserver = &homeserver($uname,$udom);
                   4130:     my ($result,$resulttype);
                   4131:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4132: 				   &escape($uname).':'.&escape($pid),
                   4133: 				   $homeserver));
1.709     albertel 4134:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4135: 	return (undef,undef);
                   4136:     }
1.706     raeburn  4137:     if ($outcome) {
                   4138:         ($result,$resulttype) = split(/:/,$outcome);
                   4139:     } 
                   4140:     return ($result,$resulttype);
                   4141: }
                   4142: 
                   4143: sub auto_photochoice {
                   4144:     my ($cnum,$cdom) = @_;
                   4145:     my $homeserver = &homeserver($cnum,$cdom);
                   4146:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4147: 						       &escape($cdom),
                   4148: 						       $homeserver)));
1.709     albertel 4149:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4150: 	return (undef,undef);
                   4151:     }
1.706     raeburn  4152:     return ($update,$comment);
                   4153: }
                   4154: 
                   4155: sub auto_photoupdate {
                   4156:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4157:     my $homeserver = &homeserver($cnum,$dom);
                   4158:     my $host=$hostname{$homeserver};
                   4159:     my $cmd = '';
                   4160:     my $maxtries = 1;
                   4161:     foreach (keys %{$affiliatesref}) {
                   4162:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4163:     }
                   4164:     $cmd =~ s/%%$//;
                   4165:     $cmd = &escape($cmd);
                   4166:     my $query = 'institutionalphotos';
                   4167:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4168:     unless ($queryid=~/^\Q$host\E\_/) {
                   4169:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4170:         return 'error: '.$queryid;
                   4171:     }
                   4172:     my $reply = &get_query_reply($queryid);
                   4173:     my $tries = 1;
                   4174:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4175:         $reply = &get_query_reply($queryid);
                   4176:         $tries ++;
                   4177:     }
                   4178:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4179:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4180:     } else {
                   4181:         my @responses = split(/:/,$reply);
                   4182:         my $outcome = shift(@responses); 
                   4183:         foreach my $item (@responses) {
                   4184:             my ($key,$value) = split(/=/,$item);
                   4185:             $$photo{$key} = $value;
                   4186:         }
                   4187:         return $outcome;
                   4188:     }
                   4189:     return 'error';
                   4190: }
                   4191: 
1.521     raeburn  4192: sub auto_instcode_format {
                   4193:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   4194:     my $courses = '';
                   4195:     my $homeserver;
                   4196:     if ($caller eq 'global') {
1.584     raeburn  4197:         foreach my $tryserver (keys %libserv) {
                   4198:             if ($hostdom{$tryserver} eq $codedom) {
                   4199:                 $homeserver = $tryserver;
                   4200:                 last;
                   4201:             }
                   4202:         }
1.620     albertel 4203:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   4204:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  4205:         }
1.521     raeburn  4206:     } else {
                   4207:         $homeserver = &homeserver($caller,$codedom);
                   4208:     }
                   4209:     foreach (keys %{$instcodes}) {
                   4210:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   4211:     }
                   4212:     chop($courses);
                   4213:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   4214:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   4215:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   4216:         %{$codes} = &str2hash($codes_str);
                   4217:         @{$codetitles} = &str2array($codetitles_str);
                   4218:         %{$cat_titles} = &str2hash($cat_titles_str);
                   4219:         %{$cat_order} = &str2hash($cat_order_str);
                   4220:         return 'ok';
                   4221:     }
                   4222:     return $response;
                   4223: }
                   4224: 
1.679     raeburn  4225: # ------------------------------------------------------- Course Group routines
                   4226: 
                   4227: sub get_coursegroups {
1.683     raeburn  4228:     my ($cdom,$cnum,$group) = @_;
                   4229:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4230: }
                   4231: 
                   4232: sub modify_coursegroup {
                   4233:     my ($cdom,$cnum,$groupsettings) = @_;
                   4234:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4235: }
                   4236: 
                   4237: sub modify_group_roles {
                   4238:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4239:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4240:     my $role = 'gr/'.&escape($userprivs);
                   4241:     my ($uname,$udom) = split(/:/,$user);
                   4242:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4243:     if ($result eq 'ok') {
                   4244:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4245:     }
1.679     raeburn  4246:     return $result;
                   4247: }
                   4248: 
                   4249: sub modify_coursegroup_membership {
                   4250:     my ($cdom,$cnum,$membership) = @_;
                   4251:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4252:     return $result;
                   4253: }
                   4254: 
1.682     raeburn  4255: sub get_active_groups {
                   4256:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4257:     my $now = time;
                   4258:     my %groups = ();
                   4259:     foreach my $key (keys(%env)) {
                   4260:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4261:             my ($start,$end) = split(/\./,$env{$key});
                   4262:             if (($end!=0) && ($end<$now)) { next; }
                   4263:             if (($start!=0) && ($start>$now)) { next; }
                   4264:             if ($1 eq $cdom && $2 eq $cnum) {
                   4265:                 $groups{$3} = $env{$key} ;
                   4266:             }
                   4267:         }
                   4268:     }
                   4269:     return %groups;
                   4270: }
                   4271: 
1.683     raeburn  4272: sub get_group_membership {
                   4273:     my ($cdom,$cnum,$group) = @_;
                   4274:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4275: }
                   4276: 
                   4277: sub get_users_groups {
                   4278:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4279:     my @usersgroups;
1.683     raeburn  4280:     my $cachetime=1800;
                   4281:     $courseid=~s/\_/\//g;
                   4282:     $courseid=~s/^(\w)/\/$1/;
                   4283: 
                   4284:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4285:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4286:     if (defined($cached)) {
1.734     albertel 4287:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4288:     } else {  
                   4289:         $grouplist = '';
                   4290:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4291:         my ($tmp) = keys(%roleshash);
                   4292:         if ($tmp=~/^error:/) {
                   4293:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4294:         } else {
                   4295:             my $access_end = $env{'course.'.$courseid.
                   4296:                                   '.default_enrollment_end_date'};
                   4297:             my $now = time;
1.734     albertel 4298:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4299:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4300:                     my $group = $1;
                   4301:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4302:                         my $start = $2;
                   4303:                         my $end = $1;
                   4304:                         if ($start == -1) { next; } # deleted from group
                   4305:                         if (($start!=0) && ($start>$now)) { next; }
                   4306:                         if (($end!=0) && ($end<$now)) {
                   4307:                             if ($access_end && $access_end < $now) {
                   4308:                                 if ($access_end - $end < 86400) {
                   4309:                                     push(@usersgroups,$group);
                   4310:                                 }
                   4311:                             }
                   4312:                             next;
                   4313:                         }
                   4314:                         push(@usersgroups,$group);
                   4315:                     }
1.683     raeburn  4316:                 }
                   4317:             }
1.733     raeburn  4318:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4319:             $grouplist = join(':',@usersgroups);
                   4320:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4321:         }
                   4322:     }
1.733     raeburn  4323:     return @usersgroups;
1.683     raeburn  4324: }
                   4325: 
                   4326: sub devalidate_getgroups_cache {
                   4327:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4328:     my $courseid = $cdom.'_'.$cnum;
                   4329:     $courseid=~s/\_/\//g;
                   4330:     $courseid=~s/^(\w)/\/$1/;
                   4331:     my $hashid="$udom:$uname:$courseid";
                   4332:     &devalidate_cache_new('getgroups',$hashid);
                   4333: }
                   4334: 
1.12      www      4335: # ------------------------------------------------------------------ Plain Text
                   4336: 
                   4337: sub plaintext {
1.742     raeburn  4338:     my ($short,$type,$cid) = @_;
1.758     albertel 4339:     if ($short =~ /^cr/) {
                   4340: 	return (split('/',$short))[-1];
                   4341:     }
1.742     raeburn  4342:     if (!defined($cid)) {
                   4343:         $cid = $env{'request.course.id'};
                   4344:     }
                   4345:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4346:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4347:                                           '.plaintext'});
                   4348:     }
                   4349:     my %rolenames = (
                   4350:                       Course => 'std',
                   4351:                       Group => 'alt1',
                   4352:                     );
                   4353:     if (defined($type) && 
                   4354:          defined($rolenames{$type}) && 
                   4355:          defined($prp{$short}{$rolenames{$type}})) {
                   4356:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4357:     } else {
                   4358:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4359:     }
1.12      www      4360: }
                   4361: 
                   4362: # ----------------------------------------------------------------- Assign Role
                   4363: 
                   4364: sub assignrole {
1.357     www      4365:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4366:     my $mrole;
                   4367:     if ($role =~ /^cr\//) {
1.393     www      4368:         my $cwosec=$url;
                   4369:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4370: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4371:            &logthis('Refused custom assignrole: '.
                   4372:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4373: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4374:            return 'refused'; 
                   4375:         }
1.21      www      4376:         $mrole='cr';
1.678     raeburn  4377:     } elsif ($role =~ /^gr\//) {
                   4378:         my $cwogrp=$url;
                   4379:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4380:         unless (&allowed('mdg',$cwogrp)) {
                   4381:             &logthis('Refused group assignrole: '.
                   4382:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4383:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4384:             return 'refused';
                   4385:         }
                   4386:         $mrole='gr';
1.21      www      4387:     } else {
1.82      www      4388:         my $cwosec=$url;
1.83      www      4389:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4390:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4391:            &logthis('Refused assignrole: '.
                   4392:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4393: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4394:            return 'refused'; 
                   4395:         }
1.21      www      4396:         $mrole=$role;
                   4397:     }
1.620     albertel 4398:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4399:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4400:     if ($end) { $command.='_'.$end; }
1.21      www      4401:     if ($start) {
                   4402: 	if ($end) { 
1.81      www      4403:            $command.='_'.$start; 
1.21      www      4404:         } else {
1.81      www      4405:            $command.='_0_'.$start;
1.21      www      4406:         }
                   4407:     }
1.739     raeburn  4408:     my $origstart = $start;
                   4409:     my $origend = $end;
1.357     www      4410: # actually delete
                   4411:     if ($deleteflag) {
1.373     www      4412: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4413: # modify command to delete the role
1.620     albertel 4414:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4415:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4416: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4417: # set start and finish to negative values for userrolelog
                   4418:            $start=-1;
                   4419:            $end=-1;
                   4420:         }
                   4421:     }
                   4422: # send command
1.349     www      4423:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4424: # log new user role if status is ok
1.349     www      4425:     if ($answer eq 'ok') {
1.663     raeburn  4426: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4427: # for course roles, perform group memberships changes triggered by role change.
                   4428:         unless ($role =~ /^gr/) {
                   4429:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4430:                                              $origstart);
                   4431:         }
1.349     www      4432:     }
                   4433:     return $answer;
1.169     harris41 4434: }
                   4435: 
                   4436: # -------------------------------------------------- Modify user authentication
1.197     www      4437: # Overrides without validation
                   4438: 
1.169     harris41 4439: sub modifyuserauth {
                   4440:     my ($udom,$uname,$umode,$upass)=@_;
                   4441:     my $uhome=&homeserver($uname,$udom);
1.197     www      4442:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4443:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4444:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4445:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4446:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4447: 		     &escape($upass),$uhome);
1.620     albertel 4448:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4449:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4450:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4451:     &log($udom,,$uname,$uhome,
1.620     albertel 4452:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4453:                                      $env{'user.name'}.', '.$umode.
1.197     www      4454:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4455:     unless ($reply eq 'ok') {
1.197     www      4456:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4457: 	return 'error: '.$reply;
                   4458:     }   
1.170     harris41 4459:     return 'ok';
1.80      www      4460: }
                   4461: 
1.81      www      4462: # --------------------------------------------------------------- Modify a user
1.80      www      4463: 
1.81      www      4464: sub modifyuser {
1.206     matthew  4465:     my ($udom,    $uname, $uid,
                   4466:         $umode,   $upass, $first,
                   4467:         $middle,  $last,  $gene,
1.387     www      4468:         $forceid, $desiredhome, $email)=@_;
1.198     www      4469:     $udom=~s/\W//g;
                   4470:     $uname=~s/\W//g;
1.81      www      4471:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4472:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4473: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4474:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4475:                                      ' desiredhome not specified'). 
1.620     albertel 4476:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4477:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4478:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4479: # ----------------------------------------------------------------- Create User
1.406     albertel 4480:     if (($uhome eq 'no_host') && 
                   4481: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4482:         my $unhome='';
1.209     matthew  4483:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4484:             $unhome = $desiredhome;
1.620     albertel 4485: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4486: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4487:         } else { # load balancing routine for determining $unhome
1.80      www      4488:             my $tryserver;
1.81      www      4489:             my $loadm=10000000;
1.80      www      4490:             foreach $tryserver (keys %libserv) {
                   4491: 	       if ($hostdom{$tryserver} eq $udom) {
                   4492:                   my $answer=reply('load',$tryserver);
                   4493:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4494: 		      $loadm=$answer;
                   4495:                       $unhome=$tryserver;
                   4496:                   }
                   4497: 	       }
                   4498: 	    }
                   4499:         }
                   4500:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4501: 	    return 'error: unable to find a home server for '.$uname.
                   4502:                    ' in domain '.$udom;
1.80      www      4503:         }
                   4504:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4505:                          &escape($upass),$unhome);
                   4506: 	unless ($reply eq 'ok') {
                   4507:             return 'error: '.$reply;
                   4508:         }   
1.230     stredwic 4509:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4510:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4511: 	    return 'error: unable verify users home machine.';
1.80      www      4512:         }
1.209     matthew  4513:     }   # End of creation of new user
1.80      www      4514: # ---------------------------------------------------------------------- Add ID
                   4515:     if ($uid) {
                   4516:        $uid=~tr/A-Z/a-z/;
                   4517:        my %uidhash=&idrget($udom,$uname);
1.196     www      4518:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4519:          && (!$forceid)) {
1.80      www      4520: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4521: 	      return 'error: user id "'.$uid.'" does not match '.
                   4522:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4523:           }
                   4524:        } else {
                   4525: 	  &idput($udom,($uname => $uid));
                   4526:        }
                   4527:     }
                   4528: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4529:     my @tmp=&get('environment',
1.134     albertel 4530: 		   ['firstname','middlename','lastname','generation'],
                   4531: 		   $udom,$uname);
1.313     matthew  4532:     my %names;
                   4533:     if ($tmp[0] =~ m/^error:.*/) { 
                   4534:         %names=(); 
                   4535:     } else {
                   4536:         %names = @tmp;
                   4537:     }
1.388     www      4538: #
                   4539: # Make sure to not trash student environment if instructor does not bother
                   4540: # to supply name and email information
                   4541: #
                   4542:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4543:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4544:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4545:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4546:     if ($email) {
                   4547:        $email=~s/[^\w\@\.\-\,]//gs;
                   4548:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4549: 			   $names{'critnotification'} = $email;
                   4550: 			   $names{'permanentemail'} = $email; }
                   4551:     }
1.134     albertel 4552:     my $reply = &put('environment', \%names, $udom,$uname);
                   4553:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4554:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4555:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4556:              $umode.', '.$first.', '.$middle.', '.
                   4557: 	     $last.', '.$gene.' by '.
1.620     albertel 4558:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4559:     return 'ok';
1.80      www      4560: }
                   4561: 
1.81      www      4562: # -------------------------------------------------------------- Modify student
1.80      www      4563: 
1.81      www      4564: sub modifystudent {
                   4565:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4566:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4567:     if (!$cid) {
1.620     albertel 4568: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4569: 	    return 'not_in_class';
                   4570: 	}
1.80      www      4571:     }
                   4572: # --------------------------------------------------------------- Make the user
1.81      www      4573:     my $reply=&modifyuser
1.209     matthew  4574: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4575:          $desiredhome,$email);
1.80      www      4576:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4577:     # This will cause &modify_student_enrollment to get the uid from the
                   4578:     # students environment
                   4579:     $uid = undef if (!$forceid);
1.455     albertel 4580:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4581: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4582:     return $reply;
                   4583: }
                   4584: 
                   4585: sub modify_student_enrollment {
1.515     raeburn  4586:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4587:     my ($cdom,$cnum,$chome);
                   4588:     if (!$cid) {
1.620     albertel 4589: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4590: 	    return 'not_in_class';
                   4591: 	}
1.620     albertel 4592: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4593: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4594:     } else {
                   4595: 	($cdom,$cnum)=split(/_/,$cid);
                   4596:     }
1.620     albertel 4597:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4598:     if (!$chome) {
1.457     raeburn  4599: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4600:     }
1.455     albertel 4601:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4602:     # Make sure the user exists
1.81      www      4603:     my $uhome=&homeserver($uname,$udom);
                   4604:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4605: 	return 'error: no such user';
                   4606:     }
1.297     matthew  4607:     # Get student data if we were not given enough information
                   4608:     if (!defined($first)  || $first  eq '' || 
                   4609:         !defined($last)   || $last   eq '' || 
                   4610:         !defined($uid)    || $uid    eq '' || 
                   4611:         !defined($middle) || $middle eq '' || 
                   4612:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4613:         # They did not supply us with enough data to enroll the student, so
                   4614:         # we need to pick up more information.
1.297     matthew  4615:         my %tmp = &get('environment',
1.294     matthew  4616:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4617:                        ,$udom,$uname);
                   4618: 
1.455     albertel 4619:         #foreach (keys(%tmp)) {
                   4620:         #    &logthis("key $_ = ".$tmp{$_});
                   4621:         #}
1.294     matthew  4622:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4623:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4624:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4625:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4626:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4627:     }
1.556     albertel 4628:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4629:     my $reply=cput('classlist',
                   4630: 		   {"$uname:$udom" => 
1.515     raeburn  4631: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4632: 		   $cdom,$cnum);
1.81      www      4633:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4634: 	return 'error: '.$reply;
1.652     albertel 4635:     } else {
                   4636: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4637:     }
1.297     matthew  4638:     # Add student role to user
1.83      www      4639:     my $uurl='/'.$cid;
1.81      www      4640:     $uurl=~s/\_/\//g;
                   4641:     if ($usec) {
                   4642: 	$uurl.='/'.$usec;
                   4643:     }
                   4644:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4645: }
                   4646: 
1.556     albertel 4647: sub format_name {
                   4648:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4649:     my $name;
                   4650:     if ($first ne 'lastname') {
                   4651: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4652:     } else {
                   4653: 	if ($lastname=~/\S/) {
                   4654: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4655: 	    $name=~s/\s+,/,/;
                   4656: 	} else {
                   4657: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4658: 	}
                   4659:     }
                   4660:     $name=~s/^\s+//;
                   4661:     $name=~s/\s+$//;
                   4662:     $name=~s/\s+/ /g;
                   4663:     return $name;
                   4664: }
                   4665: 
1.84      www      4666: # ------------------------------------------------- Write to course preferences
                   4667: 
                   4668: sub writecoursepref {
                   4669:     my ($courseid,%prefs)=@_;
                   4670:     $courseid=~s/^\///;
                   4671:     $courseid=~s/\_/\//g;
                   4672:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4673:     my $chome=homeserver($cnum,$cdomain);
                   4674:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4675: 	return 'error: no such course';
                   4676:     }
                   4677:     my $cstring='';
1.191     harris41 4678:     foreach (keys %prefs) {
1.84      www      4679: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4680:     }
1.84      www      4681:     $cstring=~s/\&$//;
                   4682:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4683: }
                   4684: 
                   4685: # ---------------------------------------------------------- Make/modify course
                   4686: 
                   4687: sub createcourse {
1.741     raeburn  4688:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4689:         $course_owner,$crstype)=@_;
1.84      www      4690:     $url=&declutter($url);
                   4691:     my $cid='';
1.264     matthew  4692:     unless (&allowed('ccc',$udom)) {
1.84      www      4693:         return 'refused';
                   4694:     }
                   4695: # ------------------------------------------------------------------- Create ID
1.674     www      4696:    my $uname=int(1+rand(9)).
                   4697:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4698:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4699:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4700: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4701:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4702:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4703:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4704:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4705:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4706:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4707:            return 'error: unable to generate unique course-ID';
                   4708:        } 
                   4709:    }
1.264     matthew  4710: # ------------------------------------------------ Check supplied server name
1.620     albertel 4711:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4712:     if (! exists($libserv{$course_server})) {
                   4713:         return 'error:bad server name '.$course_server;
                   4714:     }
1.84      www      4715: # ------------------------------------------------------------- Make the course
                   4716:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4717:                       $course_server);
1.84      www      4718:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4719:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4720:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4721: 	return 'error: no such course';
                   4722:     }
1.271     www      4723: # ----------------------------------------------------------------- Course made
1.516     raeburn  4724: # log existence
                   4725:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4726:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4727:                   &escape($crstype),$uhome);
1.358     www      4728:     &flushcourselogs();
                   4729: # set toplevel url
1.271     www      4730:     my $topurl=$url;
                   4731:     unless ($nonstandard) {
                   4732: # ------------------------------------------ For standard courses, make top url
                   4733:         my $mapurl=&clutter($url);
1.278     www      4734:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4735:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4736: <map>
                   4737: <resource id="1" type="start"></resource>
                   4738: <resource id="2" src="$mapurl"></resource>
                   4739: <resource id="3" type="finish"></resource>
                   4740: <link index="1" from="1" to="2"></link>
                   4741: <link index="2" from="2" to="3"></link>
                   4742: </map>
                   4743: ENDINITMAP
                   4744:         $topurl=&declutter(
1.638     albertel 4745:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4746:                           );
                   4747:     }
                   4748: # ----------------------------------------------------------- Write preferences
1.84      www      4749:     &writecoursepref($udom.'_'.$uname,
                   4750:                      ('description' => $description,
1.271     www      4751:                       'url'         => $topurl));
1.84      www      4752:     return '/'.$udom.'/'.$uname;
                   4753: }
                   4754: 
1.21      www      4755: # ---------------------------------------------------------- Assign Custom Role
                   4756: 
                   4757: sub assigncustomrole {
1.357     www      4758:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4759:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4760:                        $end,$start,$deleteflag);
1.21      www      4761: }
                   4762: 
                   4763: # ----------------------------------------------------------------- Revoke Role
                   4764: 
                   4765: sub revokerole {
1.357     www      4766:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4767:     my $now=time;
1.357     www      4768:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4769: }
                   4770: 
                   4771: # ---------------------------------------------------------- Revoke Custom Role
                   4772: 
                   4773: sub revokecustomrole {
1.357     www      4774:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4775:     my $now=time;
1.357     www      4776:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4777:            $deleteflag);
1.17      www      4778: }
                   4779: 
1.533     banghart 4780: # ------------------------------------------------------------ Disk usage
1.535     albertel 4781: sub diskusage {
1.533     banghart 4782:     my ($udom,$uname,$directoryRoot)=@_;
                   4783:     $directoryRoot =~ s/\/$//;
1.535     albertel 4784:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4785:     return $listing;
1.512     banghart 4786: }
                   4787: 
1.566     banghart 4788: sub is_locked {
                   4789:     my ($file_name, $domain, $user) = @_;
                   4790:     my @check;
                   4791:     my $is_locked;
                   4792:     push @check, $file_name;
1.613     albertel 4793:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4794: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4795:     my ($tmp)=keys(%locked);
                   4796:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4797:     
1.566     banghart 4798:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4799:         $is_locked = 'false';
                   4800:         foreach my $entry (@{$locked{$file_name}}) {
                   4801:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4802:                $is_locked = 'true';
                   4803:                last;
1.745     raeburn  4804:            }
                   4805:        }
1.566     banghart 4806:     } else {
                   4807:         $is_locked = 'false';
                   4808:     }
                   4809: }
                   4810: 
1.759     albertel 4811: sub declutter_portfile {
                   4812:     my ($file) = @_;
                   4813:     &logthis("got $file");
                   4814:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4815:     &logthis("ret $file");
                   4816:     return $file;
                   4817: }
                   4818: 
1.559     banghart 4819: # ------------------------------------------------------------- Mark as Read Only
                   4820: 
                   4821: sub mark_as_readonly {
                   4822:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4823:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4824:     my ($tmp)=keys(%current_permissions);
                   4825:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4826:     foreach my $file (@{$files}) {
1.759     albertel 4827: 	$file = &declutter_portfile($file);
1.561     banghart 4828:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4829:     }
1.613     albertel 4830:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4831:     return;
                   4832: }
                   4833: 
1.572     banghart 4834: # ------------------------------------------------------------Save Selected Files
                   4835: 
                   4836: sub save_selected_files {
                   4837:     my ($user, $path, @files) = @_;
                   4838:     my $filename = $user."savedfiles";
1.573     banghart 4839:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4840:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4841:     foreach my $file (@files) {
1.620     albertel 4842:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4843:     }
                   4844:     foreach my $file (@other_files) {
1.574     banghart 4845:         print (OUT $file."\n");
1.572     banghart 4846:     }
1.574     banghart 4847:     close (OUT);
1.572     banghart 4848:     return 'ok';
                   4849: }
                   4850: 
1.574     banghart 4851: sub clear_selected_files {
                   4852:     my ($user) = @_;
                   4853:     my $filename = $user."savedfiles";
                   4854:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4855:     print (OUT undef);
                   4856:     close (OUT);
                   4857:     return ("ok");    
                   4858: }
                   4859: 
1.572     banghart 4860: sub files_in_path {
                   4861:     my ($user, $path) = @_;
                   4862:     my $filename = $user."savedfiles";
                   4863:     my %return_files;
1.574     banghart 4864:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4865:     while (my $line_in = <IN>) {
1.574     banghart 4866:         chomp ($line_in);
                   4867:         my @paths_and_file = split (m!/!, $line_in);
                   4868:         my $file_part = pop (@paths_and_file);
                   4869:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4870:         $path_part.='/';
                   4871:         my $path_and_file = $path_part.$file_part;
                   4872:         if ($path_part eq $path) {
                   4873:             $return_files{$file_part}= 'selected';
                   4874:         }
                   4875:     }
1.574     banghart 4876:     close (IN);
                   4877:     return (\%return_files);
1.572     banghart 4878: }
                   4879: 
                   4880: # called in portfolio select mode, to show files selected NOT in current directory
                   4881: sub files_not_in_path {
                   4882:     my ($user, $path) = @_;
                   4883:     my $filename = $user."savedfiles";
                   4884:     my @return_files;
                   4885:     my $path_part;
1.574     banghart 4886:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4887:     while (<IN>) {
                   4888:         #ok, I know it's clunky, but I want it to work
                   4889:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4890:         my $file_part = pop (@paths_and_file);
                   4891:         chomp ($file_part);
                   4892:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4893:         $path_part .= '/';
                   4894:         my $path_and_file = $path_part.$file_part;
                   4895:         if ($path_part ne $path) {
1.574     banghart 4896:             push (@return_files, ($path_and_file));
1.572     banghart 4897:         }
                   4898:     }
1.574     banghart 4899:     close (OUT);
                   4900:     return (@return_files);
1.572     banghart 4901: }
                   4902: 
1.745     raeburn  4903: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4904: 
1.745     raeburn  4905: sub get_portfile_permissions {
                   4906:     my ($domain,$user) = @_;
1.613     albertel 4907:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4908:     my ($tmp)=keys(%current_permissions);
                   4909:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4910:     return \%current_permissions;
                   4911: }
                   4912: 
                   4913: #---------------------------------------------Get portfolio file access controls
                   4914: 
1.749     raeburn  4915: sub get_access_controls {
1.745     raeburn  4916:     my ($current_permissions,$group,$file) = @_;
                   4917:     my %access; 
                   4918:     if (defined($file)) {
1.749     raeburn  4919:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4920:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
                   4921:                 $access{$file}{$control} = $$current_permissions{$file."\0".$control};
                   4922:             }
                   4923:         }
1.745     raeburn  4924:     } else {
1.749     raeburn  4925:         foreach my $key (keys(%{$current_permissions})) {
                   4926:             if ($key =~ /\0accesscontrol$/) {
                   4927:                 if (defined($group)) {
                   4928:                     if ($key !~ m-^\Q$group\E/-) {
                   4929:                         next;
                   4930:                     }
                   4931:                 }
                   4932:                 my ($fullpath) = split(/\0/,$key);
                   4933:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4934:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4935:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4936:                     }
                   4937:                 }
                   4938:             }
                   4939:         }
                   4940:     }
                   4941:     return %access;
                   4942: }
                   4943: 
                   4944: sub modify_access_controls {
                   4945:     my ($file_name,$changes,$domain,$user)=@_;
                   4946:     my ($outcome,$deloutcome);
                   4947:     my %store_permissions;
                   4948:     my %new_values;
                   4949:     my %new_control;
                   4950:     my %translation;
                   4951:     my @deletions = ();
                   4952:     my $now = time;
                   4953:     if (exists($$changes{'activate'})) {
                   4954:         if (ref($$changes{'activate'}) eq 'HASH') {
                   4955:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   4956:             my $numnew = scalar(@newitems);
                   4957:             for (my $i=0; $i<$numnew; $i++) {
                   4958:                 my $newkey = $newitems[$i];
                   4959:                 my $newid = &Apache::loncommon::get_cgi_id();
                   4960:                 $newkey =~ s/^(\d+)/$newid/;
                   4961:                 $translation{$1} = $newid;
                   4962:                 $new_values{$file_name."\0".$newkey} = 
                   4963:                                           $$changes{'activate'}{$newitems[$i]};
                   4964:                 $new_control{$newkey} = $now;
                   4965:             }
                   4966:         }
                   4967:     }
                   4968:     my %todelete;
                   4969:     my %changed_items;
                   4970:     foreach my $action ('delete','update') {
                   4971:         if (exists($$changes{$action})) {
                   4972:             if (ref($$changes{$action}) eq 'HASH') {
                   4973:                 foreach my $key (keys(%{$$changes{$action}})) {
                   4974:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   4975:                     if ($action eq 'delete') { 
                   4976:                         $todelete{$itemnum} = 1;
                   4977:                     } else {
                   4978:                         $changed_items{$itemnum} = $key;
                   4979:                     }
                   4980:                 }
1.745     raeburn  4981:             }
                   4982:         }
1.749     raeburn  4983:     }
                   4984:     # get lock on access controls for file.
                   4985:     my $lockhash = {
                   4986:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   4987:                                                        ':'.$env{'user.domain'},
                   4988:                    }; 
                   4989:     my $tries = 0;
                   4990:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   4991:    
                   4992:     while (($gotlock ne 'ok') && $tries <3) {
                   4993:         $tries ++;
                   4994:         sleep 1;
                   4995:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   4996:     }
                   4997:     if ($gotlock eq 'ok') {
                   4998:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   4999:         my ($tmp)=keys(%curr_permissions);
                   5000:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5001:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5002:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5003:             if (ref($curr_controls) eq 'HASH') {
                   5004:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5005:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5006:                     if (defined($todelete{$itemnum})) {
                   5007:                         push(@deletions,$file_name."\0".$control_item);
                   5008:                     } else {
                   5009:                         if (defined($changed_items{$itemnum})) {
                   5010:                             $new_control{$changed_items{$itemnum}} = $now;
                   5011:                             push(@deletions,$file_name."\0".$control_item);
                   5012:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5013:                         } else {
                   5014:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5015:                         }
                   5016:                     }
1.745     raeburn  5017:                 }
                   5018:             }
                   5019:         }
1.749     raeburn  5020:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5021:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5022:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5023:         #  remove lock
                   5024:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5025:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5026:     } else {
                   5027:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5028:     }
1.749     raeburn  5029:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5030: }
                   5031: 
                   5032: #------------------------------------------------------Get Marked as Read Only
                   5033: 
                   5034: sub get_marked_as_readonly {
                   5035:     my ($domain,$user,$what,$group) = @_;
                   5036:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5037:     my @readonly_files;
1.629     banghart 5038:     my $cmp1=$what;
                   5039:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5040:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5041:         if (defined($group)) {
                   5042:             if ($file_name !~ m-^\Q$group\E/-) {
                   5043:                 next;
                   5044:             }
                   5045:         }
1.561     banghart 5046:         if (ref($value) eq "ARRAY"){
                   5047:             foreach my $stored_what (@{$value}) {
1.629     banghart 5048:                 my $cmp2=$stored_what;
1.759     albertel 5049:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5050:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5051:                 }
1.629     banghart 5052:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5053:                     push(@readonly_files, $file_name);
1.745     raeburn  5054:                     last;
1.563     banghart 5055:                 } elsif (!defined($what)) {
                   5056:                     push(@readonly_files, $file_name);
1.745     raeburn  5057:                     last;
1.561     banghart 5058:                 }
                   5059:             }
1.745     raeburn  5060:         }
1.561     banghart 5061:     }
                   5062:     return @readonly_files;
                   5063: }
1.577     banghart 5064: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5065: 
1.577     banghart 5066: sub get_marked_as_readonly_hash {
1.745     raeburn  5067:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5068:     my %readonly_files;
1.745     raeburn  5069:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5070:         if (defined($group)) {
                   5071:             if ($file_name !~ m-^\Q$group\E/-) {
                   5072:                 next;
                   5073:             }
                   5074:         }
1.577     banghart 5075:         if (ref($value) eq "ARRAY"){
                   5076:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5077:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5078:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5079:                         if ($lock_descriptor eq 'graded') {
                   5080:                             $readonly_files{$file_name} = 'graded';
                   5081:                         } elsif ($lock_descriptor eq 'handback') {
                   5082:                             $readonly_files{$file_name} = 'handback';
                   5083:                         } else {
                   5084:                             if (!exists($readonly_files{$file_name})) {
                   5085:                                 $readonly_files{$file_name} = 'locked';
                   5086:                             }
                   5087:                         }
1.745     raeburn  5088:                     }
1.750     banghart 5089:                 } 
1.577     banghart 5090:             }
                   5091:         } 
                   5092:     }
                   5093:     return %readonly_files;
                   5094: }
1.559     banghart 5095: # ------------------------------------------------------------ Unmark as Read Only
                   5096: 
                   5097: sub unmark_as_readonly {
1.629     banghart 5098:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5099:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5100:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5101:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5102:     my $symb_crs = $what;
                   5103:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5104:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5105:     my ($tmp)=keys(%current_permissions);
                   5106:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5107:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5108:     foreach my $file (@readonly_files) {
1.759     albertel 5109: 	my $clean_file = &declutter_portfile($file);
                   5110: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5111: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5112:         my @new_locks;
                   5113:         my @del_keys;
                   5114:         if (ref($current_locks) eq "ARRAY"){
                   5115:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5116:                 my $compare=$locker;
1.749     raeburn  5117:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5118:                     $compare=join('',@{$locker});
1.746     raeburn  5119:                     if ($compare ne $symb_crs) {
                   5120:                         push(@new_locks, $locker);
                   5121:                     }
1.563     banghart 5122:                 }
                   5123:             }
1.650     albertel 5124:             if (scalar(@new_locks) > 0) {
1.563     banghart 5125:                 $current_permissions{$file} = \@new_locks;
                   5126:             } else {
                   5127:                 push(@del_keys, $file);
1.613     albertel 5128:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5129:                 delete($current_permissions{$file});
1.563     banghart 5130:             }
                   5131:         }
1.561     banghart 5132:     }
1.613     albertel 5133:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5134:     return;
                   5135: }
1.512     banghart 5136: 
1.17      www      5137: # ------------------------------------------------------------ Directory lister
                   5138: 
                   5139: sub dirlist {
1.253     stredwic 5140:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5141: 
1.18      www      5142:     $uri=~s/^\///;
                   5143:     $uri=~s/\/$//;
1.253     stredwic 5144:     my ($udom, $uname);
                   5145:     (undef,$udom,$uname)=split(/\//,$uri);
                   5146:     if(defined($userdomain)) {
                   5147:         $udom = $userdomain;
                   5148:     }
                   5149:     if(defined($username)) {
                   5150:         $uname = $username;
                   5151:     }
                   5152: 
                   5153:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5154:     if(defined($alternateDirectoryRoot)) {
                   5155:         $dirRoot = $alternateDirectoryRoot;
                   5156:         $dirRoot =~ s/\/$//;
1.751     banghart 5157:     }
1.253     stredwic 5158: 
                   5159:     if($udom) {
                   5160:         if($uname) {
1.605     matthew  5161:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5162:                               homeserver($uname,$udom));
1.605     matthew  5163:             my @listing_results;
                   5164:             if ($listing eq 'unknown_cmd') {
                   5165:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5166:                                homeserver($uname,$udom));
                   5167:                 @listing_results = split(/:/,$listing);
                   5168:             } else {
                   5169:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5170:             }
                   5171:             return @listing_results;
1.253     stredwic 5172:         } elsif(!defined($alternateDirectoryRoot)) {
                   5173:             my $tryserver;
                   5174:             my %allusers=();
                   5175:             foreach $tryserver (keys %libserv) {
                   5176:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5177:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5178:                                       $udom, $tryserver);
1.605     matthew  5179:                     my @listing_results;
                   5180:                     if ($listing eq 'unknown_cmd') {
                   5181:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5182:                                        $udom, $tryserver);
                   5183:                         @listing_results = split(/:/,$listing);
                   5184:                     } else {
                   5185:                         @listing_results =
                   5186:                             map { &unescape($_); } split(/:/,$listing);
                   5187:                     }
                   5188:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5189:                         $listing_results[0] ne 'empty'       &&
                   5190:                         $listing_results[0] ne 'con_lost') {
                   5191:                         foreach (@listing_results) {
1.253     stredwic 5192:                             my ($entry,@stat)=split(/&/,$_);
                   5193:                             $allusers{$entry}=1;
                   5194:                         }
                   5195:                     }
1.191     harris41 5196:                 }
1.253     stredwic 5197:             }
                   5198:             my $alluserstr='';
                   5199:             foreach (sort keys %allusers) {
                   5200:                 $alluserstr.=$_.'&user:';
                   5201:             }
                   5202:             $alluserstr=~s/:$//;
                   5203:             return split(/:/,$alluserstr);
                   5204:         } else {
                   5205:             my @emptyResults = ();
                   5206:             push(@emptyResults, 'missing user name');
                   5207:             return split(':',@emptyResults);
                   5208:         }
                   5209:     } elsif(!defined($alternateDirectoryRoot)) {
                   5210:         my $tryserver;
                   5211:         my %alldom=();
                   5212:         foreach $tryserver (keys %libserv) {
                   5213:             $alldom{$hostdom{$tryserver}}=1;
                   5214:         }
                   5215:         my $alldomstr='';
                   5216:         foreach (sort keys %alldom) {
1.397     albertel 5217:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5218:         }
                   5219:         $alldomstr=~s/:$//;
                   5220:         return split(/:/,$alldomstr);       
                   5221:     } else {
                   5222:         my @emptyResults = ();
                   5223:         push(@emptyResults, 'missing domain');
                   5224:         return split(':',@emptyResults);
1.275     stredwic 5225:     }
                   5226: }
                   5227: 
                   5228: # --------------------------------------------- GetFileTimestamp
                   5229: # This function utilizes dirlist and returns the date stamp for
                   5230: # when it was last modified.  It will also return an error of -1
                   5231: # if an error occurs
                   5232: 
1.410     matthew  5233: ##
                   5234: ## FIXME: This subroutine assumes its caller knows something about the
                   5235: ## directory structure of the home server for the student ($root).
                   5236: ## Not a good assumption to make.  Since this is for looking up files
                   5237: ## in user directories, the full path should be constructed by lond, not
                   5238: ## whatever machine we request data from.
                   5239: ##
1.275     stredwic 5240: sub GetFileTimestamp {
                   5241:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5242:     $studentDomain=~s/\W//g;
                   5243:     $studentName=~s/\W//g;
                   5244:     my $subdir=$studentName.'__';
                   5245:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5246:     my $proname="$studentDomain/$subdir/$studentName";
                   5247:     $proname .= '/'.$filename;
1.375     matthew  5248:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5249:                                               $studentName, $root);
1.275     stredwic 5250:     my @stats = split('&', $fileStat);
                   5251:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5252:         # @stats contains first the filename, then the stat output
                   5253:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5254:     } else {
                   5255:         return -1;
1.253     stredwic 5256:     }
1.26      www      5257: }
                   5258: 
1.712     albertel 5259: sub stat_file {
                   5260:     my ($uri) = @_;
1.722     albertel 5261:     $uri = &clutter($uri);
                   5262: 
                   5263:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 5264:     if ($uri =~ m-^/adm/-) {
                   5265: 	$uri=~s-^/adm/wrapper/-/-;
                   5266: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 5267:     }
1.712     albertel 5268:     my ($udom,$uname,$file,$dir);
                   5269:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5270: 	($udom,$uname,$file) =
                   5271: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5272: 	$file = 'userfiles/'.$file;
1.740     www      5273: 	$dir = &propath($udom,$uname);
1.712     albertel 5274:     }
                   5275:     if ($uri =~ m-^/res/-) {
                   5276: 	($udom,$uname) = 
                   5277: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5278: 	$file = $uri;
                   5279:     }
                   5280: 
                   5281:     if (!$udom || !$uname || !$file) {
                   5282: 	# unable to handle the uri
                   5283: 	return ();
                   5284:     }
                   5285: 
                   5286:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5287:     my @stats = split('&', $result);
1.721     banghart 5288:     
1.712     albertel 5289:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5290: 	shift(@stats); #filename is first
                   5291: 	return @stats;
                   5292:     }
                   5293:     return ();
                   5294: }
                   5295: 
1.26      www      5296: # -------------------------------------------------------- Value of a Condition
                   5297: 
1.713     albertel 5298: # gets the value of a specific preevaluated condition
                   5299: #    stored in the string  $env{user.state.<cid>}
                   5300: # or looks up a condition reference in the bighash and if if hasn't
                   5301: # already been evaluated recurses into docondval to get the value of
                   5302: # the condition, then memoizing it to 
                   5303: #   $env{user.state.<cid>.<condition>}
1.40      www      5304: sub directcondval {
                   5305:     my $number=shift;
1.620     albertel 5306:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5307: 	&Apache::lonuserstate::evalstate();
                   5308:     }
1.713     albertel 5309:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5310: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5311:     } elsif ($number =~ /^_/) {
                   5312: 	my $sub_condition;
                   5313: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5314: 		&GDBM_READER(),0640)) {
                   5315: 	    $sub_condition=$bighash{'conditions'.$number};
                   5316: 	    untie(%bighash);
                   5317: 	}
                   5318: 	my $value = &docondval($sub_condition);
                   5319: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5320: 	return $value;
                   5321:     }
1.620     albertel 5322:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5323:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5324:     } else {
                   5325:        return 2;
                   5326:     }
                   5327: }
                   5328: 
1.713     albertel 5329: # get the collection of conditions for this resource
1.26      www      5330: sub condval {
                   5331:     my $condidx=shift;
1.54      www      5332:     my $allpathcond='';
1.713     albertel 5333:     foreach my $cond (split(/\|/,$condidx)) {
                   5334: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5335: 	    $allpathcond.=
                   5336: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5337: 	}
1.191     harris41 5338:     }
1.54      www      5339:     $allpathcond=~s/\|$//;
1.713     albertel 5340:     return &docondval($allpathcond);
                   5341: }
                   5342: 
                   5343: #evaluates an expression of conditions
                   5344: sub docondval {
                   5345:     my ($allpathcond) = @_;
                   5346:     my $result=0;
                   5347:     if ($env{'request.course.id'}
                   5348: 	&& defined($allpathcond)) {
                   5349: 	my $operand='|';
                   5350: 	my @stack;
                   5351: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5352: 	    if ($chunk eq '(') {
                   5353: 		push @stack,($operand,$result);
                   5354: 	    } elsif ($chunk eq ')') {
                   5355: 		my $before=pop @stack;
                   5356: 		if (pop @stack eq '&') {
                   5357: 		    $result=$result>$before?$before:$result;
                   5358: 		} else {
                   5359: 		    $result=$result>$before?$result:$before;
                   5360: 		}
                   5361: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5362: 		$operand=$chunk;
                   5363: 	    } else {
                   5364: 		my $new=directcondval($chunk);
                   5365: 		if ($operand eq '&') {
                   5366: 		    $result=$result>$new?$new:$result;
                   5367: 		} else {
                   5368: 		    $result=$result>$new?$result:$new;
                   5369: 		}
                   5370: 	    }
                   5371: 	}
1.26      www      5372:     }
                   5373:     return $result;
1.421     albertel 5374: }
                   5375: 
                   5376: # ---------------------------------------------------- Devalidate courseresdata
                   5377: 
                   5378: sub devalidatecourseresdata {
                   5379:     my ($coursenum,$coursedomain)=@_;
                   5380:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5381:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5382: }
                   5383: 
1.763     www      5384: 
1.200     www      5385: # --------------------------------------------------- Course Resourcedata Query
                   5386: 
1.624     albertel 5387: sub get_courseresdata {
                   5388:     my ($coursenum,$coursedomain)=@_;
1.200     www      5389:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5390:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5391:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5392:     my %dumpreply;
1.417     albertel 5393:     unless (defined($cached)) {
1.624     albertel 5394: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5395: 	$result=\%dumpreply;
1.251     albertel 5396: 	my ($tmp) = keys(%dumpreply);
                   5397: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5398: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5399: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5400: 	    return $tmp;
1.416     albertel 5401: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5402: 	    $result=undef;
1.599     albertel 5403: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5404: 	}
                   5405:     }
1.624     albertel 5406:     return $result;
                   5407: }
                   5408: 
1.633     albertel 5409: sub devalidateuserresdata {
                   5410:     my ($uname,$udom)=@_;
                   5411:     my $hashid="$udom:$uname";
                   5412:     &devalidate_cache_new('userres',$hashid);
                   5413: }
                   5414: 
1.624     albertel 5415: sub get_userresdata {
                   5416:     my ($uname,$udom)=@_;
                   5417:     #most student don\'t have any data set, check if there is some data
                   5418:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5419: 
                   5420:     my $hashid="$udom:$uname";
                   5421:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5422:     if (!defined($cached)) {
                   5423: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5424: 	$result=\%resourcedata;
                   5425: 	&do_cache_new('userres',$hashid,$result,600);
                   5426:     }
                   5427:     my ($tmp)=keys(%$result);
                   5428:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5429: 	return $result;
                   5430:     }
                   5431:     #error 2 occurs when the .db doesn't exist
                   5432:     if ($tmp!~/error: 2 /) {
1.672     albertel 5433: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5434: 		 " Trying to get resource data for ".
                   5435: 		 $uname." at ".$udom.": ".
                   5436: 		 $tmp."</font>");
                   5437:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5438: 	#&EXT_cache_set($udom,$uname);
                   5439: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5440: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5441:     }
                   5442:     return $tmp;
                   5443: }
                   5444: 
                   5445: sub resdata {
                   5446:     my ($name,$domain,$type,@which)=@_;
                   5447:     my $result;
                   5448:     if ($type eq 'course') {
                   5449: 	$result=&get_courseresdata($name,$domain);
                   5450:     } elsif ($type eq 'user') {
                   5451: 	$result=&get_userresdata($name,$domain);
                   5452:     }
                   5453:     if (!ref($result)) { return $result; }    
1.251     albertel 5454:     foreach my $item (@which) {
1.417     albertel 5455: 	if (defined($result->{$item})) {
                   5456: 	    return $result->{$item};
1.251     albertel 5457: 	}
1.250     albertel 5458:     }
1.291     albertel 5459:     return undef;
1.200     www      5460: }
                   5461: 
1.379     matthew  5462: #
                   5463: # EXT resource caching routines
                   5464: #
                   5465: 
                   5466: sub clear_EXT_cache_status {
1.383     albertel 5467:     &delenv('cache.EXT.');
1.379     matthew  5468: }
                   5469: 
                   5470: sub EXT_cache_status {
                   5471:     my ($target_domain,$target_user) = @_;
1.383     albertel 5472:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5473:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5474:         # We know already the user has no data
                   5475:         return 1;
                   5476:     } else {
                   5477:         return 0;
                   5478:     }
                   5479: }
                   5480: 
                   5481: sub EXT_cache_set {
                   5482:     my ($target_domain,$target_user) = @_;
1.383     albertel 5483:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5484:     #&appenv($cachename => time);
1.379     matthew  5485: }
                   5486: 
1.28      www      5487: # --------------------------------------------------------- Value of a Variable
1.58      www      5488: sub EXT {
1.715     albertel 5489: 
1.395     albertel 5490:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5491:     unless ($varname) { return ''; }
1.218     albertel 5492:     #get real user name/domain, courseid and symb
                   5493:     my $courseid;
1.359     albertel 5494:     my $publicuser;
1.427     www      5495:     if ($symbparm) {
                   5496: 	$symbparm=&get_symb_from_alias($symbparm);
                   5497:     }
1.218     albertel 5498:     if (!($uname && $udom)) {
1.360     albertel 5499:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5500: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5501:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5502:     } else {
1.620     albertel 5503: 	$courseid=$env{'request.course.id'};
1.218     albertel 5504:     }
1.48      www      5505:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5506:     my $rest;
1.320     albertel 5507:     if (defined($therest[0])) {
1.48      www      5508:        $rest=join('.',@therest);
                   5509:     } else {
                   5510:        $rest='';
                   5511:     }
1.320     albertel 5512: 
1.57      www      5513:     my $qualifierrest=$qualifier;
                   5514:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5515:     my $spacequalifierrest=$space;
                   5516:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5517:     if ($realm eq 'user') {
1.48      www      5518: # --------------------------------------------------------------- user.resource
                   5519: 	if ($space eq 'resource') {
1.651     albertel 5520: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5521: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5522: 		 &&
1.744     albertel 5523: 		 ($symbparm eq &symbread()) ) {	
                   5524: 		# if we are in the middle of processing the resource the
                   5525: 		# get the value we are planning on committing
                   5526:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5527:                     return $Apache::lonhomework::results{$qualifierrest};
                   5528:                 } else {
                   5529:                     return $Apache::lonhomework::history{$qualifierrest};
                   5530:                 }
1.335     albertel 5531: 	    } else {
1.359     albertel 5532: 		my %restored;
1.620     albertel 5533: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5534: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5535: 		} else {
                   5536: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5537: 		}
1.335     albertel 5538: 		return $restored{$qualifierrest};
                   5539: 	    }
1.48      www      5540: # ----------------------------------------------------------------- user.access
                   5541:         } elsif ($space eq 'access') {
1.218     albertel 5542: 	    # FIXME - not supporting calls for a specific user
1.48      www      5543:             return &allowed($qualifier,$rest);
                   5544: # ------------------------------------------ user.preferences, user.environment
                   5545:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5546: 	    if (($uname eq $env{'user.name'}) &&
                   5547: 		($udom eq $env{'user.domain'})) {
                   5548: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5549: 	    } else {
1.359     albertel 5550: 		my %returnhash;
                   5551: 		if (!$publicuser) {
                   5552: 		    %returnhash=&userenvironment($udom,$uname,
                   5553: 						 $qualifierrest);
                   5554: 		}
1.218     albertel 5555: 		return $returnhash{$qualifierrest};
                   5556: 	    }
1.48      www      5557: # ----------------------------------------------------------------- user.course
                   5558:         } elsif ($space eq 'course') {
1.218     albertel 5559: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5560:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5561: # ------------------------------------------------------------------- user.role
                   5562:         } elsif ($space eq 'role') {
1.218     albertel 5563: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5564:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5565:             if ($qualifier eq 'value') {
                   5566: 		return $role;
                   5567:             } elsif ($qualifier eq 'extent') {
                   5568:                 return $where;
                   5569:             }
                   5570: # ----------------------------------------------------------------- user.domain
                   5571:         } elsif ($space eq 'domain') {
1.218     albertel 5572:             return $udom;
1.48      www      5573: # ------------------------------------------------------------------- user.name
                   5574:         } elsif ($space eq 'name') {
1.218     albertel 5575:             return $uname;
1.48      www      5576: # ---------------------------------------------------- Any other user namespace
1.29      www      5577:         } else {
1.359     albertel 5578: 	    my %reply;
                   5579: 	    if (!$publicuser) {
                   5580: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5581: 	    }
                   5582: 	    return $reply{$qualifierrest};
1.48      www      5583:         }
1.236     www      5584:     } elsif ($realm eq 'query') {
                   5585: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5586:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5587: 						[$spacequalifierrest]);
1.620     albertel 5588: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5589:    } elsif ($realm eq 'request') {
1.48      www      5590: # ------------------------------------------------------------- request.browser
                   5591:         if ($space eq 'browser') {
1.430     www      5592: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5593: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5594: 		    return 1;
                   5595: 		} else {
                   5596: 		    return 0;
                   5597: 		}
                   5598: 	    } else {
1.620     albertel 5599: 		return $env{'browser.'.$qualifier};
1.430     www      5600: 	    }
1.57      www      5601: # ------------------------------------------------------------ request.filename
                   5602:         } else {
1.620     albertel 5603:             return $env{'request.'.$spacequalifierrest};
1.29      www      5604:         }
1.28      www      5605:     } elsif ($realm eq 'course') {
1.48      www      5606: # ---------------------------------------------------------- course.description
1.620     albertel 5607:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5608:     } elsif ($realm eq 'resource') {
1.165     www      5609: 
1.620     albertel 5610: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5611: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5612: 	}
1.693     albertel 5613: 
                   5614: 	if ($space eq 'title') {
                   5615: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5616: 	    return &gettitle($symbparm);
                   5617: 	}
                   5618: 	
                   5619: 	if ($space eq 'map') {
                   5620: 	    my ($map) = &decode_symb($symbparm);
                   5621: 	    return &symbread($map);
                   5622: 	}
                   5623: 
                   5624: 	my ($section, $group, @groups);
1.593     albertel 5625: 	my ($courselevelm,$courselevel);
1.539     albertel 5626: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5627: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5628: 
1.218     albertel 5629: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5630: 
1.60      www      5631: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5632: 	    my $symbp=$symbparm;
1.735     albertel 5633: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5634: 
                   5635: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5636: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5637: 
1.620     albertel 5638: 	    if (($env{'user.name'} eq $uname) &&
                   5639: 		($env{'user.domain'} eq $udom)) {
                   5640: 		$section=$env{'request.course.sec'};
1.733     raeburn  5641:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5642:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5643: 	    } else {
1.539     albertel 5644: 		if (! defined($usection)) {
1.551     albertel 5645: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5646: 		} else {
                   5647: 		    $section = $usection;
                   5648: 		}
1.733     raeburn  5649:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5650: 	    }
                   5651: 
                   5652: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5653: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5654: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5655: 
1.593     albertel 5656: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5657: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5658: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5659: 
1.60      www      5660: # ----------------------------------------------------------- first, check user
1.624     albertel 5661: 
                   5662: 	    my $userreply=&resdata($uname,$udom,'user',
                   5663: 				       ($courselevelr,$courselevelm,
                   5664: 					$courselevel));
                   5665: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5666: 
1.594     albertel 5667: # ------------------------------------------------ second, check some of course
1.684     raeburn  5668:             my $coursereply;
1.691     raeburn  5669:             if (@groups > 0) {
                   5670:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5671:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5672:                 if (defined($coursereply)) { return $coursereply; }
                   5673:             }
1.96      www      5674: 
1.684     raeburn  5675: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5676: 				     $env{'course.'.$courseid.'.domain'},
                   5677: 				     'course',
                   5678: 				     ($seclevelr,$seclevelm,$seclevel,
                   5679: 				      $courselevelr));
1.287     albertel 5680: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5681: 
1.60      www      5682: # ------------------------------------------------------ third, check map parms
1.218     albertel 5683: 	    my %parmhash=();
                   5684: 	    my $thisparm='';
                   5685: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5686: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5687: 		    &GDBM_READER(),0640)) {
1.218     albertel 5688: 		$thisparm=$parmhash{$symbparm};
                   5689: 		untie(%parmhash);
                   5690: 	    }
                   5691: 	    if ($thisparm) { return $thisparm; }
                   5692: 	}
1.594     albertel 5693: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5694: 
1.218     albertel 5695: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5696: 	my $filename;
                   5697: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5698: 	if ($symbparm) {
1.409     www      5699: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5700: 	} else {
1.620     albertel 5701: 	    $filename=$env{'request.filename'};
1.282     albertel 5702: 	}
                   5703: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5704: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5705: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5706: 	if (defined($metadata)) { return $metadata; }
1.142     www      5707: 
1.594     albertel 5708: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5709: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5710: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5711: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5712: 				     $env{'course.'.$courseid.'.domain'},
                   5713: 				     'course',
                   5714: 				     ($courselevelm,$courselevel));
1.593     albertel 5715: 	    if (defined($coursereply)) { return $coursereply; }
                   5716: 	}
1.145     www      5717: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5718: 	unless ($space eq '0') {
1.336     albertel 5719: 	    my @parts=split(/_/,$space);
                   5720: 	    my $id=pop(@parts);
                   5721: 	    my $part=join('_',@parts);
                   5722: 	    if ($part eq '') { $part='0'; }
                   5723: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5724: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5725: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5726: 	}
1.395     albertel 5727: 	if ($recurse) { return undef; }
                   5728: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5729: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5730: 
1.48      www      5731: # ---------------------------------------------------- Any other user namespace
                   5732:     } elsif ($realm eq 'environment') {
                   5733: # ----------------------------------------------------------------- environment
1.620     albertel 5734: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5735: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5736: 	} else {
                   5737: 	    my %returnhash=&userenvironment($udom,$uname,
                   5738: 					    $spacequalifierrest);
                   5739: 	    return $returnhash{$spacequalifierrest};
                   5740: 	}
1.28      www      5741:     } elsif ($realm eq 'system') {
1.48      www      5742: # ----------------------------------------------------------------- system.time
                   5743: 	if ($space eq 'time') {
                   5744: 	    return time;
                   5745:         }
1.696     albertel 5746:     } elsif ($realm eq 'server') {
                   5747: # ----------------------------------------------------------------- system.time
                   5748: 	if ($space eq 'name') {
                   5749: 	    return $ENV{'SERVER_NAME'};
                   5750:         }
1.28      www      5751:     }
1.48      www      5752:     return '';
1.61      www      5753: }
                   5754: 
1.691     raeburn  5755: sub check_group_parms {
                   5756:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5757:     my @groupitems = ();
                   5758:     my $resultitem;
                   5759:     my @levels = ($symbparm,$mapparm,$what);
                   5760:     foreach my $group (@{$groups}) {
                   5761:         foreach my $level (@levels) {
                   5762:              my $item = $courseid.'.['.$group.'].'.$level;
                   5763:              push(@groupitems,$item);
                   5764:         }
                   5765:     }
                   5766:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5767:                             $env{'course.'.$courseid.'.domain'},
                   5768:                                      'course',@groupitems);
                   5769:     return $coursereply;
                   5770: }
                   5771: 
                   5772: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5773:     my ($courseid,@groups) = @_;
                   5774:     @groups = sort(@groups);
1.691     raeburn  5775:     return @groups;
                   5776: }
                   5777: 
1.395     albertel 5778: sub packages_tab_default {
                   5779:     my ($uri,$varname)=@_;
                   5780:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5781: 
                   5782:     my (@extension,@specifics,$do_default);
                   5783:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5784: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5785: 	if ($pack_type eq 'default') {
                   5786: 	    $do_default=1;
                   5787: 	} elsif ($pack_type eq 'extension') {
                   5788: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5789: 	} else {
                   5790: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5791: 	}
                   5792:     }
                   5793:     # first look for a package that matches the requested part id
                   5794:     foreach my $package (@specifics) {
                   5795: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5796: 	next if ($pack_part ne $part);
                   5797: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5798: 	    return $packagetab{"$pack_type&$name&default"};
                   5799: 	}
                   5800:     }
                   5801:     # look for any possible matching non extension_ package
                   5802:     foreach my $package (@specifics) {
                   5803: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5804: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5805: 	    return $packagetab{"$pack_type&$name&default"};
                   5806: 	}
1.585     albertel 5807: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5808: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5809: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5810: 	}
                   5811:     }
1.738     albertel 5812:     # look for any posible extension_ match
                   5813:     foreach my $package (@extension) {
                   5814: 	my ($package,$pack_type)=@{$package};
                   5815: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5816: 	    return $packagetab{"$pack_type&$name&default"};
                   5817: 	}
                   5818: 	if (defined($packagetab{$package."&$name&default"})) {
                   5819: 	    return $packagetab{$package."&$name&default"};
                   5820: 	}
                   5821:     }
                   5822:     # look for a global default setting
                   5823:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5824: 	return $packagetab{"default&$name&default"};
                   5825:     }
1.395     albertel 5826:     return undef;
                   5827: }
                   5828: 
1.334     albertel 5829: sub add_prefix_and_part {
                   5830:     my ($prefix,$part)=@_;
                   5831:     my $keyroot;
                   5832:     if (defined($prefix) && $prefix !~ /^__/) {
                   5833: 	# prefix that has a part already
                   5834: 	$keyroot=$prefix;
                   5835:     } elsif (defined($prefix)) {
                   5836: 	# prefix that is missing a part
                   5837: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5838:     } else {
                   5839: 	# no prefix at all
                   5840: 	if (defined($part)) { $keyroot='_'.$part; }
                   5841:     }
                   5842:     return $keyroot;
                   5843: }
                   5844: 
1.71      www      5845: # ---------------------------------------------------------------- Get metadata
                   5846: 
1.599     albertel 5847: my %metaentry;
1.71      www      5848: sub metadata {
1.176     www      5849:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5850:     $uri=&declutter($uri);
1.288     albertel 5851:     # if it is a non metadata possible uri return quickly
1.529     albertel 5852:     if (($uri eq '') || 
                   5853: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5854: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5855:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5856: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5857: 	return undef;
1.288     albertel 5858:     }
1.73      www      5859:     my $filename=$uri;
                   5860:     $uri=~s/\.meta$//;
1.172     www      5861: #
                   5862: # Is the metadata already cached?
1.177     www      5863: # Look at timestamp of caching
1.172     www      5864: # Everything is cached by the main uri, libraries are never directly cached
                   5865: #
1.428     albertel 5866:     if (!defined($liburi)) {
1.599     albertel 5867: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5868: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5869:     }
                   5870:     {
1.172     www      5871: #
                   5872: # Is this a recursive call for a library?
                   5873: #
1.599     albertel 5874: #	if (! exists($metacache{$uri})) {
                   5875: #	    $metacache{$uri}={};
                   5876: #	}
1.171     www      5877:         if ($liburi) {
                   5878: 	    $liburi=&declutter($liburi);
                   5879:             $filename=$liburi;
1.401     bowersj2 5880:         } else {
1.599     albertel 5881: 	    &devalidate_cache_new('meta',$uri);
                   5882: 	    undef(%metaentry);
1.401     bowersj2 5883: 	}
1.140     www      5884:         my %metathesekeys=();
1.73      www      5885:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5886: 	my $metastring;
1.768   ! albertel 5887: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5888: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5889: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5890: 	    $metastring=&getfile($file);
1.489     albertel 5891: 	}
1.208     albertel 5892:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5893:         my $token;
1.140     www      5894:         undef %metathesekeys;
1.71      www      5895:         while ($token=$parser->get_token) {
1.339     albertel 5896: 	    if ($token->[0] eq 'S') {
                   5897: 		if (defined($token->[2]->{'package'})) {
1.172     www      5898: #
                   5899: # This is a package - get package info
                   5900: #
1.339     albertel 5901: 		    my $package=$token->[2]->{'package'};
                   5902: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5903: 		    if (defined($token->[2]->{'id'})) { 
                   5904: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5905: 		    }
1.599     albertel 5906: 		    if ($metaentry{':packages'}) {
                   5907: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5908: 		    } else {
1.599     albertel 5909: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5910: 		    }
1.736     albertel 5911: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5912: 			my $part=$keyroot;
                   5913: 			$part=~s/^\_//;
1.736     albertel 5914: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5915: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5916: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5917: 			    # ignore package.tab specified default values
                   5918:                             # here &package_tab_default() will fetch those
                   5919: 			    if ($subp eq 'default') { next; }
1.736     albertel 5920: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5921: 			    my $unikey;
                   5922: 			    if ($pack =~ /_0$/) {
                   5923: 				$unikey='parameter_0_'.$name;
                   5924: 				$part=0;
                   5925: 			    } else {
                   5926: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5927: 			    }
1.339     albertel 5928: 			    if ($subp eq 'display') {
                   5929: 				$value.=' [Part: '.$part.']';
                   5930: 			    }
1.599     albertel 5931: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5932: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5933: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5934: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5935: 			    }
1.599     albertel 5936: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5937: 				$metaentry{':'.$unikey}=
                   5938: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5939: 			    }
1.339     albertel 5940: 			}
                   5941: 		    }
                   5942: 		} else {
1.172     www      5943: #
                   5944: # This is not a package - some other kind of start tag
1.339     albertel 5945: #
                   5946: 		    my $entry=$token->[1];
                   5947: 		    my $unikey;
                   5948: 		    if ($entry eq 'import') {
                   5949: 			$unikey='';
                   5950: 		    } else {
                   5951: 			$unikey=$entry;
                   5952: 		    }
                   5953: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5954: 
                   5955: 		    if (defined($token->[2]->{'id'})) { 
                   5956: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5957: 		    }
1.175     www      5958: 
1.339     albertel 5959: 		    if ($entry eq 'import') {
1.175     www      5960: #
                   5961: # Importing a library here
1.339     albertel 5962: #
                   5963: 			if ($depthcount<20) {
                   5964: 			    my $location=$parser->get_text('/import');
                   5965: 			    my $dir=$filename;
                   5966: 			    $dir=~s|[^/]*$||;
                   5967: 			    $location=&filelocation($dir,$location);
1.736     albertel 5968: 			    my $metadata = 
                   5969: 				&metadata($uri,'keys', $location,$unikey,
                   5970: 					  $depthcount+1);
                   5971: 			    foreach my $meta (split(',',$metadata)) {
                   5972: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   5973: 				$metathesekeys{$meta}=1;
1.339     albertel 5974: 			    }
                   5975: 			}
                   5976: 		    } else { 
                   5977: 			
                   5978: 			if (defined($token->[2]->{'name'})) { 
                   5979: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5980: 			}
                   5981: 			$metathesekeys{$unikey}=1;
1.736     albertel 5982: 			foreach my $param (@{$token->[3]}) {
                   5983: 			    $metaentry{':'.$unikey.'.'.$param} =
                   5984: 				$token->[2]->{$param};
1.339     albertel 5985: 			}
                   5986: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5987: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5988: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5989: 		 # only ws inside the tag, and not in default, so use default
                   5990: 		 # as value
1.599     albertel 5991: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5992: 			} else {
1.321     albertel 5993: 		  # either something interesting inside the tag or default
                   5994:                   # uninteresting
1.599     albertel 5995: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5996: 			}
1.172     www      5997: # end of not-a-package not-a-library import
1.339     albertel 5998: 		    }
1.172     www      5999: # end of not-a-package start tag
1.339     albertel 6000: 		}
1.172     www      6001: # the next is the end of "start tag"
1.339     albertel 6002: 	    }
                   6003: 	}
1.483     albertel 6004: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6005: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6006: 	    #no specific packages #how's our extension
                   6007: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6008: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6009: 					 \%metathesekeys);
                   6010: 	}
1.599     albertel 6011: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6012: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6013: 		#no specific packages well let's get default then
                   6014: 		if ($key!~/^default&/) { next; }
1.488     albertel 6015: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6016: 					     \%metathesekeys);
                   6017: 	    }
                   6018: 	}
1.338     www      6019: # are there custom rights to evaluate
1.599     albertel 6020: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6021: 
1.338     www      6022:     #
                   6023:     # Importing a rights file here
1.339     albertel 6024:     #
                   6025: 	    unless ($depthcount) {
1.599     albertel 6026: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6027: 		my $dir=$filename;
                   6028: 		$dir=~s|[^/]*$||;
                   6029: 		$location=&filelocation($dir,$location);
1.736     albertel 6030: 		my $rights_metadata =
                   6031: 		    &metadata($uri,'keys',$location,'_rights',
                   6032: 			      $depthcount+1);
                   6033: 		foreach my $rights (split(',',$rights_metadata)) {
                   6034: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6035: 		    $metathesekeys{$rights}=1;
1.339     albertel 6036: 		}
                   6037: 	    }
                   6038: 	}
1.737     albertel 6039: 	# uniqifiy package listing
                   6040: 	my %seen;
                   6041: 	my @uniq_packages =
                   6042: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6043: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6044: 
                   6045: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6046: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6047: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6048: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6049: # this is the end of "was not already recently cached
1.71      www      6050:     }
1.599     albertel 6051:     return $metaentry{':'.$what};
1.261     albertel 6052: }
                   6053: 
1.488     albertel 6054: sub metadata_create_package_def {
1.483     albertel 6055:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6056:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6057:     if ($subp eq 'default') { next; }
                   6058:     
1.599     albertel 6059:     if (defined($metaentry{':packages'})) {
                   6060: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6061:     } else {
1.599     albertel 6062: 	$metaentry{':packages'}=$package;
1.483     albertel 6063:     }
                   6064:     my $value=$packagetab{$key};
                   6065:     my $unikey;
                   6066:     $unikey='parameter_0_'.$name;
1.599     albertel 6067:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6068:     $$metathesekeys{$unikey}=1;
1.599     albertel 6069:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6070: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6071:     }
1.599     albertel 6072:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6073: 	$metaentry{':'.$unikey}=
                   6074: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6075:     }
                   6076: }
                   6077: 
1.261     albertel 6078: sub metadata_generate_part0 {
                   6079:     my ($metadata,$metacache,$uri) = @_;
                   6080:     my %allnames;
1.737     albertel 6081:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6082: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6083: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6084: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6085: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6086: 	    $allnames{$name}=$part;
                   6087: 	  }
                   6088: 	}
                   6089:     }
                   6090:     foreach my $name (keys(%allnames)) {
                   6091:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6092:       my $key=":parameter_0_$name";
1.261     albertel 6093:       $$metacache{"$key.part"}='0';
                   6094:       $$metacache{"$key.name"}=$name;
1.428     albertel 6095:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6096: 					   $allnames{$name}.'_'.$name.
                   6097: 					   '.type'};
1.428     albertel 6098:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6099: 			     '.display'};
1.644     www      6100:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6101:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6102:       $$metacache{"$key.display"}=$olddis;
                   6103:     }
1.71      www      6104: }
                   6105: 
1.764     albertel 6106: # ------------------------------------------------------ Devalidate title cache
                   6107: 
                   6108: sub devalidate_title_cache {
                   6109:     my ($url)=@_;
                   6110:     if (!$env{'request.course.id'}) { return; }
                   6111:     my $symb=&symbread($url);
                   6112:     if (!$symb) { return; }
                   6113:     my $key=$env{'request.course.id'}."\0".$symb;
                   6114:     &devalidate_cache_new('title',$key);
                   6115: }
                   6116: 
1.301     www      6117: # ------------------------------------------------- Get the title of a resource
                   6118: 
                   6119: sub gettitle {
                   6120:     my $urlsymb=shift;
                   6121:     my $symb=&symbread($urlsymb);
1.534     albertel 6122:     if ($symb) {
1.620     albertel 6123: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6124: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6125: 	if (defined($cached)) { 
                   6126: 	    return $result;
                   6127: 	}
1.534     albertel 6128: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6129: 	my $title='';
                   6130: 	my %bighash;
1.620     albertel 6131: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6132: 		&GDBM_READER(),0640)) {
                   6133: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6134: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6135: 	    untie %bighash;
                   6136: 	}
                   6137: 	$title=~s/\&colon\;/\:/gs;
                   6138: 	if ($title) {
1.599     albertel 6139: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6140: 	}
                   6141: 	$urlsymb=$url;
                   6142:     }
                   6143:     my $title=&metadata($urlsymb,'title');
                   6144:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6145:     return $title;
1.301     www      6146: }
1.613     albertel 6147: 
1.614     albertel 6148: sub get_slot {
                   6149:     my ($which,$cnum,$cdom)=@_;
                   6150:     if (!$cnum || !$cdom) {
                   6151: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 6152: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6153: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6154:     }
1.703     albertel 6155:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6156:     my %slotinfo;
                   6157:     if (exists($remembered{$key})) {
                   6158: 	$slotinfo{$which} = $remembered{$key};
                   6159:     } else {
                   6160: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6161: 	&Apache::lonhomework::showhash(%slotinfo);
                   6162: 	my ($tmp)=keys(%slotinfo);
                   6163: 	if ($tmp=~/^error:/) { return (); }
                   6164: 	$remembered{$key} = $slotinfo{$which};
                   6165:     }
1.616     albertel 6166:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6167: 	return %{$slotinfo{$which}};
                   6168:     }
                   6169:     return $slotinfo{$which};
1.614     albertel 6170: }
1.31      www      6171: # ------------------------------------------------- Update symbolic store links
                   6172: 
                   6173: sub symblist {
                   6174:     my ($mapname,%newhash)=@_;
1.438     www      6175:     $mapname=&deversion(&declutter($mapname));
1.31      www      6176:     my %hash;
1.620     albertel 6177:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6178:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6179:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6180: 	    foreach my $url (keys %newhash) {
                   6181: 		next if ($url eq 'last_known'
                   6182: 			 && $env{'form.no_update_last_known'});
                   6183: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6184: 						    $newhash{$url}->[1],
                   6185: 						    $newhash{$url}->[0]);
1.191     harris41 6186:             }
1.31      www      6187:             if (untie(%hash)) {
                   6188: 		return 'ok';
                   6189:             }
                   6190:         }
                   6191:     }
                   6192:     return 'error';
1.212     www      6193: }
                   6194: 
                   6195: # --------------------------------------------------------------- Verify a symb
                   6196: 
                   6197: sub symbverify {
1.510     www      6198:     my ($symb,$thisurl)=@_;
                   6199:     my $thisfn=$thisurl;
                   6200: # wrapper not part of symbs
                   6201:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 6202:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      6203:     $thisfn=&declutter($thisfn);
1.215     www      6204: # direct jump to resource in page or to a sequence - will construct own symbs
                   6205:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6206: # check URL part
1.409     www      6207:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6208: 
1.431     www      6209:     unless ($url eq $thisfn) { return 0; }
1.213     www      6210: 
1.216     www      6211:     $symb=&symbclean($symb);
1.510     www      6212:     $thisurl=&deversion($thisurl);
1.439     www      6213:     $thisfn=&deversion($thisfn);
1.213     www      6214: 
                   6215:     my %bighash;
                   6216:     my $okay=0;
1.431     www      6217: 
1.620     albertel 6218:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6219:                             &GDBM_READER(),0640)) {
1.510     www      6220:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6221:         unless ($ids) { 
1.510     www      6222:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6223:         }
                   6224:         if ($ids) {
                   6225: # ------------------------------------------------------------------- Has ID(s)
                   6226: 	    foreach (split(/\,/,$ids)) {
1.644     www      6227: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6228:                if (
                   6229:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6230:    eq $symb) { 
1.620     albertel 6231: 		   if (($env{'request.role.adv'}) ||
                   6232: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6233: 		       $okay=1; 
                   6234: 		   }
                   6235: 	       }
1.216     www      6236: 	   }
                   6237:         }
1.213     www      6238: 	untie(%bighash);
                   6239:     }
                   6240:     return $okay;
1.31      www      6241: }
                   6242: 
1.210     www      6243: # --------------------------------------------------------------- Clean-up symb
                   6244: 
                   6245: sub symbclean {
                   6246:     my $symb=shift;
1.568     albertel 6247:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6248: # remove version from map
                   6249:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6250: 
1.210     www      6251: # remove version from URL
                   6252:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6253: 
1.507     www      6254: # remove wrapper
                   6255: 
1.510     www      6256:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6257:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6258:     return $symb;
1.409     www      6259: }
                   6260: 
                   6261: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6262: 
                   6263: sub encode_symb {
                   6264:     my ($map,$resid,$url)=@_;
                   6265:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6266: }
1.409     www      6267: 
                   6268: sub decode_symb {
1.568     albertel 6269:     my $symb=shift;
                   6270:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6271:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6272:     return (&fixversion($map),$resid,&fixversion($url));
                   6273: }
                   6274: 
                   6275: sub fixversion {
                   6276:     my $fn=shift;
1.609     banghart 6277:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6278:     my %bighash;
                   6279:     my $uri=&clutter($fn);
1.620     albertel 6280:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6281: # is this cached?
1.599     albertel 6282:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6283:     if (defined($cached)) { return $result; }
                   6284: # unfortunately not cached, or expired
1.620     albertel 6285:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6286: 	    &GDBM_READER(),0640)) {
                   6287:  	if ($bighash{'version_'.$uri}) {
                   6288:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6289:  	    unless (($version eq 'mostrecent') || 
                   6290: 		    ($version==&getversion($uri))) {
1.440     www      6291:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6292:  	    }
                   6293:  	}
                   6294:  	untie %bighash;
1.413     www      6295:     }
1.599     albertel 6296:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6297: }
                   6298: 
                   6299: sub deversion {
                   6300:     my $url=shift;
                   6301:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6302:     return $url;
1.210     www      6303: }
                   6304: 
1.31      www      6305: # ------------------------------------------------------ Return symb list entry
                   6306: 
                   6307: sub symbread {
1.249     www      6308:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6309:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6310:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6311: # no filename provided? try from environment
1.44      www      6312:     unless ($thisfn) {
1.620     albertel 6313:         if ($env{'request.symb'}) {
                   6314: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6315: 	}
1.620     albertel 6316: 	$thisfn=$env{'request.filename'};
1.44      www      6317:     }
1.569     albertel 6318:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6319: # is that filename actually a symb? Verify, clean, and return
                   6320:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6321: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6322: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6323: 	}
1.242     www      6324:     }
1.44      www      6325:     $thisfn=declutter($thisfn);
1.31      www      6326:     my %hash;
1.37      www      6327:     my %bighash;
                   6328:     my $syval='';
1.620     albertel 6329:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6330:         my $targetfn = $thisfn;
1.609     banghart 6331:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6332:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6333:         }
1.687     albertel 6334: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6335: 	    $targetfn=$1;
                   6336: 	}
1.620     albertel 6337:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6338:                       &GDBM_READER(),0640)) {
1.481     raeburn  6339: 	    $syval=$hash{$targetfn};
1.37      www      6340:             untie(%hash);
                   6341:         }
                   6342: # ---------------------------------------------------------- There was an entry
                   6343:         if ($syval) {
1.601     albertel 6344: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6345: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6346: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6347: 		    #return $env{$cache_str}='';
1.601     albertel 6348: 		#}    
                   6349: 		#$syval.=$1;
                   6350: 	    #}
1.37      www      6351:         } else {
                   6352: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6353:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6354:                             &GDBM_READER(),0640)) {
1.37      www      6355: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6356:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6357:               unless ($ids) { 
                   6358:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6359:               }
                   6360:               unless ($ids) {
                   6361: # alias?
                   6362: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6363:               }
1.37      www      6364:               if ($ids) {
                   6365: # ------------------------------------------------------------------- Has ID(s)
                   6366:                  my @possibilities=split(/\,/,$ids);
1.39      www      6367:                  if ($#possibilities==0) {
                   6368: # ----------------------------------------------- There is only one possibility
1.37      www      6369: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6370: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6371: 						    $resid,$thisfn);
1.249     www      6372:                  } elsif (!$donotrecurse) {
1.39      www      6373: # ------------------------------------------ There is more than one possibility
                   6374:                      my $realpossible=0;
1.191     harris41 6375:                      foreach (@possibilities) {
1.39      www      6376: 			 my $file=$bighash{'src_'.$_};
                   6377:                          if (&allowed('bre',$file)) {
                   6378:          		    my ($mapid,$resid)=split(/\./,$_);
                   6379:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6380: 				$realpossible++;
1.626     albertel 6381:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6382: 						    $resid,$thisfn);
1.39      www      6383:                             }
                   6384: 			 }
1.191     harris41 6385:                      }
1.39      www      6386: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6387:                  } else {
                   6388:                      $syval='';
1.37      www      6389:                  }
                   6390: 	      }
                   6391:               untie(%bighash)
1.481     raeburn  6392:            }
1.31      www      6393:         }
1.62      www      6394:         if ($syval) {
1.620     albertel 6395: 	    return $env{$cache_str}=$syval;
1.62      www      6396:         }
1.31      www      6397:     }
1.44      www      6398:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6399:     return $env{$cache_str}='';
1.31      www      6400: }
                   6401: 
                   6402: # ---------------------------------------------------------- Return random seed
                   6403: 
1.32      www      6404: sub numval {
                   6405:     my $txt=shift;
                   6406:     $txt=~tr/A-J/0-9/;
                   6407:     $txt=~tr/a-j/0-9/;
                   6408:     $txt=~tr/K-T/0-9/;
                   6409:     $txt=~tr/k-t/0-9/;
                   6410:     $txt=~tr/U-Z/0-5/;
                   6411:     $txt=~tr/u-z/0-5/;
                   6412:     $txt=~s/\D//g;
1.564     albertel 6413:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6414:     return int($txt);
1.368     albertel 6415: }
                   6416: 
1.484     albertel 6417: sub numval2 {
                   6418:     my $txt=shift;
                   6419:     $txt=~tr/A-J/0-9/;
                   6420:     $txt=~tr/a-j/0-9/;
                   6421:     $txt=~tr/K-T/0-9/;
                   6422:     $txt=~tr/k-t/0-9/;
                   6423:     $txt=~tr/U-Z/0-5/;
                   6424:     $txt=~tr/u-z/0-5/;
                   6425:     $txt=~s/\D//g;
                   6426:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6427:     my $total;
                   6428:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6429:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6430:     return int($total);
                   6431: }
                   6432: 
1.575     albertel 6433: sub numval3 {
                   6434:     use integer;
                   6435:     my $txt=shift;
                   6436:     $txt=~tr/A-J/0-9/;
                   6437:     $txt=~tr/a-j/0-9/;
                   6438:     $txt=~tr/K-T/0-9/;
                   6439:     $txt=~tr/k-t/0-9/;
                   6440:     $txt=~tr/U-Z/0-5/;
                   6441:     $txt=~tr/u-z/0-5/;
                   6442:     $txt=~s/\D//g;
                   6443:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6444:     my $total;
                   6445:     foreach my $val (@txts) { $total+=$val; }
                   6446:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6447:     return $total;
                   6448: }
                   6449: 
1.675     albertel 6450: sub digest {
                   6451:     my ($data)=@_;
                   6452:     my $digest=&Digest::MD5::md5($data);
                   6453:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6454:     my ($e,$f);
                   6455:     {
                   6456:         use integer;
                   6457:         $e=($a+$b);
                   6458:         $f=($c+$d);
                   6459:         if ($_64bit) {
                   6460:             $e=(($e<<32)>>32);
                   6461:             $f=(($f<<32)>>32);
                   6462:         }
                   6463:     }
                   6464:     if (wantarray) {
                   6465: 	return ($e,$f);
                   6466:     } else {
                   6467: 	my $g;
                   6468: 	{
                   6469: 	    use integer;
                   6470: 	    $g=($e+$f);
                   6471: 	    if ($_64bit) {
                   6472: 		$g=(($g<<32)>>32);
                   6473: 	    }
                   6474: 	}
                   6475: 	return $g;
                   6476:     }
                   6477: }
                   6478: 
1.368     albertel 6479: sub latest_rnd_algorithm_id {
1.675     albertel 6480:     return '64bit5';
1.366     albertel 6481: }
1.32      www      6482: 
1.503     albertel 6483: sub get_rand_alg {
                   6484:     my ($courseid)=@_;
                   6485:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6486:     if ($courseid) {
1.620     albertel 6487: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6488:     }
                   6489:     return &latest_rnd_algorithm_id();
                   6490: }
                   6491: 
1.562     albertel 6492: sub validCODE {
                   6493:     my ($CODE)=@_;
                   6494:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6495:     return 0;
                   6496: }
                   6497: 
1.491     albertel 6498: sub getCODE {
1.620     albertel 6499:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6500:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6501: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6502: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6503: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6504:     }
                   6505:     return undef;
                   6506: }
                   6507: 
1.31      www      6508: sub rndseed {
1.155     albertel 6509:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6510: 
                   6511:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6512:     if (!$symb) {
1.366     albertel 6513: 	unless ($symb=$wsymb) { return time; }
                   6514:     }
                   6515:     if (!$courseid) { $courseid=$wcourseid; }
                   6516:     if (!$domain) { $domain=$wdomain; }
                   6517:     if (!$username) { $username=$wusername }
1.503     albertel 6518:     my $which=&get_rand_alg();
1.491     albertel 6519:     if (defined(&getCODE())) {
1.675     albertel 6520: 	if ($which eq '64bit5') {
                   6521: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6522: 	} elsif ($which eq '64bit4') {
1.575     albertel 6523: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6524: 	} else {
                   6525: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6526: 	}
1.675     albertel 6527:     } elsif ($which eq '64bit5') {
                   6528: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6529:     } elsif ($which eq '64bit4') {
                   6530: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6531:     } elsif ($which eq '64bit3') {
                   6532: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6533:     } elsif ($which eq '64bit2') {
                   6534: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6535:     } elsif ($which eq '64bit') {
                   6536: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6537:     }
                   6538:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6539: }
                   6540: 
                   6541: sub rndseed_32bit {
                   6542:     my ($symb,$courseid,$domain,$username)=@_;
                   6543:     {
                   6544: 	use integer;
                   6545: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6546: 	my $symbseed=numval($symb) << 22;
                   6547: 	my $namechck=unpack("%32C*",$username) << 17;
                   6548: 	my $nameseed=numval($username) << 12;
                   6549: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6550: 	my $courseseed=unpack("%32C*",$courseid);
                   6551: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6552: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6553: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6554: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6555: 	return $num;
                   6556:     }
                   6557: }
                   6558: 
                   6559: sub rndseed_64bit {
                   6560:     my ($symb,$courseid,$domain,$username)=@_;
                   6561:     {
                   6562: 	use integer;
                   6563: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6564: 	my $symbseed=numval($symb) << 10;
                   6565: 	my $namechck=unpack("%32S*",$username);
                   6566: 	
                   6567: 	my $nameseed=numval($username) << 21;
                   6568: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6569: 	my $courseseed=unpack("%32S*",$courseid);
                   6570: 	
                   6571: 	my $num1=$symbchck+$symbseed+$namechck;
                   6572: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6573: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6574: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6575: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6576: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6577: 	return "$num1,$num2";
1.155     albertel 6578:     }
1.366     albertel 6579: }
                   6580: 
1.443     albertel 6581: sub rndseed_64bit2 {
                   6582:     my ($symb,$courseid,$domain,$username)=@_;
                   6583:     {
                   6584: 	use integer;
                   6585: 	# strings need to be an even # of cahracters long, it it is odd the
                   6586:         # last characters gets thrown away
                   6587: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6588: 	my $symbseed=numval($symb) << 10;
                   6589: 	my $namechck=unpack("%32S*",$username.' ');
                   6590: 	
                   6591: 	my $nameseed=numval($username) << 21;
1.501     albertel 6592: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6593: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6594: 	
                   6595: 	my $num1=$symbchck+$symbseed+$namechck;
                   6596: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6597: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6598: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6599: 	return "$num1,$num2";
                   6600:     }
                   6601: }
                   6602: 
                   6603: sub rndseed_64bit3 {
                   6604:     my ($symb,$courseid,$domain,$username)=@_;
                   6605:     {
                   6606: 	use integer;
                   6607: 	# strings need to be an even # of cahracters long, it it is odd the
                   6608:         # last characters gets thrown away
                   6609: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6610: 	my $symbseed=numval2($symb) << 10;
                   6611: 	my $namechck=unpack("%32S*",$username.' ');
                   6612: 	
                   6613: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6614: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6615: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6616: 	
                   6617: 	my $num1=$symbchck+$symbseed+$namechck;
                   6618: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6619: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6620: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6621: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6622: 	
1.503     albertel 6623: 	return "$num1:$num2";
1.443     albertel 6624:     }
                   6625: }
                   6626: 
1.575     albertel 6627: sub rndseed_64bit4 {
                   6628:     my ($symb,$courseid,$domain,$username)=@_;
                   6629:     {
                   6630: 	use integer;
                   6631: 	# strings need to be an even # of cahracters long, it it is odd the
                   6632:         # last characters gets thrown away
                   6633: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6634: 	my $symbseed=numval3($symb) << 10;
                   6635: 	my $namechck=unpack("%32S*",$username.' ');
                   6636: 	
                   6637: 	my $nameseed=numval3($username) << 21;
                   6638: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6639: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6640: 	
                   6641: 	my $num1=$symbchck+$symbseed+$namechck;
                   6642: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6643: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6644: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6645: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6646: 	
                   6647: 	return "$num1:$num2";
                   6648:     }
                   6649: }
                   6650: 
1.675     albertel 6651: sub rndseed_64bit5 {
                   6652:     my ($symb,$courseid,$domain,$username)=@_;
                   6653:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6654:     return "$num1:$num2";
                   6655: }
                   6656: 
1.366     albertel 6657: sub rndseed_CODE_64bit {
                   6658:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6659:     {
1.366     albertel 6660: 	use integer;
1.443     albertel 6661: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6662: 	my $symbseed=numval2($symb);
1.491     albertel 6663: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6664: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6665: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6666: 	my $num1=$symbseed+$CODEchck;
                   6667: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6668: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6669: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6670: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6671: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6672: 	return "$num1:$num2";
1.366     albertel 6673:     }
                   6674: }
                   6675: 
1.575     albertel 6676: sub rndseed_CODE_64bit4 {
                   6677:     my ($symb,$courseid,$domain,$username)=@_;
                   6678:     {
                   6679: 	use integer;
                   6680: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6681: 	my $symbseed=numval3($symb);
                   6682: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6683: 	my $CODEseed=numval3(&getCODE());
                   6684: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6685: 	my $num1=$symbseed+$CODEchck;
                   6686: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6687: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6688: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6689: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6690: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6691: 	return "$num1:$num2";
                   6692:     }
                   6693: }
                   6694: 
1.675     albertel 6695: sub rndseed_CODE_64bit5 {
                   6696:     my ($symb,$courseid,$domain,$username)=@_;
                   6697:     my $code = &getCODE();
                   6698:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6699:     return "$num1:$num2";
                   6700: }
                   6701: 
1.366     albertel 6702: sub setup_random_from_rndseed {
                   6703:     my ($rndseed)=@_;
1.503     albertel 6704:     if ($rndseed =~/([,:])/) {
                   6705: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6706: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6707:     } else {
                   6708: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6709:     }
1.36      albertel 6710: }
                   6711: 
1.474     albertel 6712: sub latest_receipt_algorithm_id {
                   6713:     return 'receipt2';
                   6714: }
                   6715: 
1.480     www      6716: sub recunique {
                   6717:     my $fucourseid=shift;
                   6718:     my $unique;
1.620     albertel 6719:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6720: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6721:     } else {
                   6722: 	$unique=$perlvar{'lonReceipt'};
                   6723:     }
                   6724:     return unpack("%32C*",$unique);
                   6725: }
                   6726: 
                   6727: sub recprefix {
                   6728:     my $fucourseid=shift;
                   6729:     my $prefix;
1.620     albertel 6730:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6731: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6732:     } else {
                   6733: 	$prefix=$perlvar{'lonHostID'};
                   6734:     }
                   6735:     return unpack("%32C*",$prefix);
                   6736: }
                   6737: 
1.76      www      6738: sub ireceipt {
1.474     albertel 6739:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6740:     my $cuname=unpack("%32C*",$funame);
                   6741:     my $cudom=unpack("%32C*",$fudom);
                   6742:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6743:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6744:     my $cunique=&recunique($fucourseid);
1.474     albertel 6745:     my $cpart=unpack("%32S*",$part);
1.480     www      6746:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6747:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6748: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6749: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6750: 			       " and ".($cpart%$cudom));
                   6751: 			       
                   6752: 	$return.= ($cunique%$cuname+
                   6753: 		   $cunique%$cudom+
                   6754: 		   $cusymb%$cuname+
                   6755: 		   $cusymb%$cudom+
                   6756: 		   $cucourseid%$cuname+
                   6757: 		   $cucourseid%$cudom+
                   6758: 		   $cpart%$cuname+
                   6759: 		   $cpart%$cudom);
                   6760:     } else {
                   6761: 	$return.= ($cunique%$cuname+
                   6762: 		   $cunique%$cudom+
                   6763: 		   $cusymb%$cuname+
                   6764: 		   $cusymb%$cudom+
                   6765: 		   $cucourseid%$cuname+
                   6766: 		   $cucourseid%$cudom);
                   6767:     }
                   6768:     return $return;
1.76      www      6769: }
                   6770: 
                   6771: sub receipt {
1.474     albertel 6772:     my ($part)=@_;
                   6773:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6774:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6775: }
1.260     ng       6776: 
1.36      albertel 6777: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6778: # returns either the contents of the file or 
                   6779: # -1 if the file doesn't exist
1.481     raeburn  6780: #
                   6781: # if the target is a file that was uploaded via DOCS, 
                   6782: # a check will be made to see if a current copy exists on the local server,
                   6783: # if it does this will be served, otherwise a copy will be retrieved from
                   6784: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6785: # the local server.   
1.472     albertel 6786: 
1.36      albertel 6787: sub getfile {
1.538     albertel 6788:     my ($file) = @_;
1.609     banghart 6789:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6790:     &repcopy($file);
                   6791:     return &readfile($file);
                   6792: }
                   6793: 
                   6794: sub repcopy_userfile {
                   6795:     my ($file)=@_;
1.609     banghart 6796:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6797:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6798:     my ($cdom,$cnum,$filename) = 
                   6799: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6800:     my ($info,$rtncode);
                   6801:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6802:     if (-e "$file") {
                   6803: 	my @fileinfo = stat($file);
                   6804: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6805: 	if ($lwpresp ne 'ok') {
                   6806: 	    if ($rtncode eq '404') {
1.538     albertel 6807: 		unlink($file);
1.482     albertel 6808: 	    }
1.517     albertel 6809: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6810: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6811: 	    #my $response=$ua->request($request);
                   6812: 	    #if ($response->is_success()) {
                   6813: 	#	return $response->content;
                   6814: 	#    } else {
                   6815: 	#	return -1;
                   6816: 	#    }
1.482     albertel 6817: 	    return -1;
                   6818: 	}
                   6819: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6820: 	    return 'ok';
1.482     albertel 6821: 	}
                   6822: 	$info = '';
1.538     albertel 6823: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6824: 	if ($lwpresp ne 'ok') {
                   6825: 	    return -1;
                   6826: 	}
                   6827:     } else {
1.538     albertel 6828: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6829: 	if ($lwpresp ne 'ok') {
1.517     albertel 6830: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6831: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6832: 	    my $response=$ua->request($request);
                   6833: 	    if ($response->is_success()) {
1.538     albertel 6834: 		$info=$response->content;
1.517     albertel 6835: 	    } else {
                   6836: 		return -1;
                   6837: 	    }
1.482     albertel 6838: 	}
                   6839: 	my @parts = ($cdom,$cnum); 
                   6840: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6841: 	    push @parts, split(/\//,$1);
1.518     albertel 6842: 	}
1.538     albertel 6843: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6844: 	foreach my $part (@parts) {
                   6845: 	    $path .= '/'.$part;
                   6846: 	    if (!-e $path) {
                   6847: 		mkdir($path,0770);
                   6848: 	    }
                   6849: 	}
                   6850:     }
1.538     albertel 6851:     open(FILE,">$file");
1.482     albertel 6852:     print FILE $info;
                   6853:     close(FILE);
1.607     raeburn  6854:     return 'ok';
1.481     raeburn  6855: }
                   6856: 
1.517     albertel 6857: sub tokenwrapper {
                   6858:     my $uri=shift;
1.552     albertel 6859:     $uri=~s|^http\://([^/]+)||;
                   6860:     $uri=~s|^/||;
1.620     albertel 6861:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6862:     my $token=$1;
1.552     albertel 6863:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6864:     if ($udom && $uname && $file) {
                   6865: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6866:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6867:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6868:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6869:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6870:     } else {
                   6871:         return '/adm/notfound.html';
                   6872:     }
                   6873: }
                   6874: 
1.481     raeburn  6875: sub getuploaded {
                   6876:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6877:     $uri=~s/^\///;
                   6878:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6879:     my $ua=new LWP::UserAgent;
                   6880:     my $request=new HTTP::Request($reqtype,$uri);
                   6881:     my $response=$ua->request($request);
                   6882:     $$rtncode = $response->code;
1.482     albertel 6883:     if (! $response->is_success()) {
                   6884: 	return 'failed';
                   6885:     }      
                   6886:     if ($reqtype eq 'HEAD') {
1.486     www      6887: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6888:     } elsif ($reqtype eq 'GET') {
                   6889: 	$$info = $response->content;
1.472     albertel 6890:     }
1.482     albertel 6891:     return 'ok';
1.36      albertel 6892: }
                   6893: 
1.481     raeburn  6894: sub readfile {
                   6895:     my $file = shift;
                   6896:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6897:     my $fh;
                   6898:     open($fh,"<$file");
                   6899:     my $a='';
                   6900:     while (<$fh>) { $a .=$_; }
                   6901:     return $a;
                   6902: }
                   6903: 
1.36      albertel 6904: sub filelocation {
1.590     banghart 6905:     my ($dir,$file) = @_;
                   6906:     my $location;
                   6907:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6908: 
                   6909:     if ($file =~ m-^/adm/-) {
                   6910: 	$file=~s-^/adm/wrapper/-/-;
                   6911: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6912:     }
1.590     banghart 6913:     if ($file=~m:^/~:) { # is a contruction space reference
                   6914:         $location = $file;
                   6915:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6916:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6917: 	# is a correct contruction space reference
                   6918:         $location = $file;
1.609     banghart 6919:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6920:         my ($udom,$uname,$filename)=
1.609     banghart 6921:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6922:         my $home=&homeserver($uname,$udom);
                   6923:         my $is_me=0;
                   6924:         my @ids=&current_machine_ids();
                   6925:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6926:         if ($is_me) {
1.740     www      6927:   	    $location=&propath($udom,$uname).
1.590     banghart 6928:   	      '/userfiles/'.$filename;
                   6929:         } else {
                   6930:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6931:   	      $udom.'/'.$uname.'/'.$filename;
                   6932:         }
                   6933:     } else {
                   6934:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6935:         $file=~s:^/res/:/:;
                   6936:         if ( !( $file =~ m:^/:) ) {
                   6937:             $location = $dir. '/'.$file;
                   6938:         } else {
                   6939:             $location = '/home/httpd/html/res'.$file;
                   6940:         }
1.59      albertel 6941:     }
1.590     banghart 6942:     $location=~s://+:/:g; # remove duplicate /
                   6943:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6944:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6945:     return $location;
1.46      www      6946: }
1.36      albertel 6947: 
1.46      www      6948: sub hreflocation {
                   6949:     my ($dir,$file)=@_;
1.460     albertel 6950:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6951: 	$file=filelocation($dir,$file);
1.700     albertel 6952:     } elsif ($file=~m-^/adm/-) {
                   6953: 	$file=~s-^/adm/wrapper/-/-;
                   6954: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6955:     }
                   6956:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6957: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6958:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6959: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6960:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6961: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6962: 	    -/uploaded/$1/$2/-x;
1.46      www      6963:     }
1.462     albertel 6964:     return $file;
1.465     albertel 6965: }
                   6966: 
                   6967: sub current_machine_domains {
                   6968:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6969:     my @domains;
                   6970:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6971: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6972: 	if ($hostname eq $name) {
                   6973: 	    push(@domains,$hostdom{$id});
                   6974: 	}
                   6975:     }
                   6976:     return @domains;
                   6977: }
                   6978: 
                   6979: sub current_machine_ids {
                   6980:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6981:     my @ids;
                   6982:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6983: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6984: 	if ($hostname eq $name) {
                   6985: 	    push(@ids,$id);
                   6986: 	}
                   6987:     }
                   6988:     return @ids;
1.31      www      6989: }
                   6990: 
                   6991: # ------------------------------------------------------------- Declutters URLs
                   6992: 
                   6993: sub declutter {
                   6994:     my $thisfn=shift;
1.569     albertel 6995:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6996:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6997:     $thisfn=~s/^\///;
1.697     albertel 6998:     $thisfn=~s|^adm/wrapper/||;
                   6999:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7000:     $thisfn=~s/^res\///;
1.235     www      7001:     $thisfn=~s/\?.+$//;
1.268     www      7002:     return $thisfn;
                   7003: }
                   7004: 
                   7005: # ------------------------------------------------------------- Clutter up URLs
                   7006: 
                   7007: sub clutter {
                   7008:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7009:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7010:        $thisfn='/res'.$thisfn; 
                   7011:     }
1.694     albertel 7012:     if ($thisfn !~m|/adm|) {
1.695     albertel 7013: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7014: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7015: 	} else {
                   7016: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7017: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7018: 	    if ($embstyle eq 'ssi'
                   7019: 		|| ($embstyle eq 'hdn')
                   7020: 		|| ($embstyle eq 'rat')
                   7021: 		|| ($embstyle eq 'prv')
                   7022: 		|| ($embstyle eq 'ign')) {
                   7023: 		#do nothing with these
                   7024: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7025: 		|| ($embstyle eq 'emb')
                   7026: 		|| ($embstyle eq 'wrp')) {
                   7027: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7028: 	    } elsif ($embstyle eq 'unk'
                   7029: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7030: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7031: 	    } else {
1.718     www      7032: #		&logthis("Got a blank emb style");
1.695     albertel 7033: 	    }
1.694     albertel 7034: 	}
                   7035:     }
1.31      www      7036:     return $thisfn;
1.12      www      7037: }
                   7038: 
1.557     albertel 7039: sub freeze_escape {
                   7040:     my ($value)=@_;
                   7041:     if (ref($value)) {
                   7042: 	$value=&nfreeze($value);
                   7043: 	return '__FROZEN__'.&escape($value);
                   7044:     }
                   7045:     return &escape($value);
                   7046: }
                   7047: 
1.11      www      7048: 
1.557     albertel 7049: sub thaw_unescape {
                   7050:     my ($value)=@_;
                   7051:     if ($value =~ /^__FROZEN__/) {
                   7052: 	substr($value,0,10,undef);
                   7053: 	$value=&unescape($value);
                   7054: 	return &thaw($value);
                   7055:     }
                   7056:     return &unescape($value);
                   7057: }
                   7058: 
1.436     albertel 7059: sub correct_line_ends {
                   7060:     my ($result)=@_;
                   7061:     $$result =~s/\r\n/\n/mg;
                   7062:     $$result =~s/\r/\n/mg;
1.415     albertel 7063: }
1.1       albertel 7064: # ================================================================ Main Program
                   7065: 
1.184     www      7066: sub goodbye {
1.204     albertel 7067:    &logthis("Starting Shut down");
1.443     albertel 7068: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7069:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7070: #converted
1.599     albertel 7071: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7072:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7073: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7074: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7075: #1.1 only
1.599     albertel 7076: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7077: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7078: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7079: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7080:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7081:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7082:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7083:    &flushcourselogs();
                   7084:    &logthis("Shutting down");
                   7085: }
                   7086: 
1.179     www      7087: BEGIN {
1.228     harris41 7088: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7089:     unless ($readit) {
1.217     harris41 7090: {
1.581     matthew  7091:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 7092:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 7093: 
                   7094:     while (my $configline=<$config>) {
1.484     albertel 7095:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 7096: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      7097:            chomp($varvalue);
1.1       albertel 7098:            $perlvar{$varname}=$varvalue;
                   7099:         }
                   7100:     }
1.448     albertel 7101:     close($config);
1.1       albertel 7102: }
1.227     harris41 7103: {
1.448     albertel 7104:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 7105: 
                   7106:     while (my $configline=<$config>) {
                   7107:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   7108: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   7109:            chomp($varvalue);
                   7110:            $perlvar{$varname}=$varvalue;
                   7111:         }
                   7112:     }
1.448     albertel 7113:     close($config);
1.227     harris41 7114: }
1.1       albertel 7115: 
1.327     albertel 7116: # ------------------------------------------------------------ Read domain file
                   7117: {
                   7118:     %domaindescription = ();
                   7119:     %domain_auth_def = ();
                   7120:     %domain_auth_arg_def = ();
1.448     albertel 7121:     my $fh;
                   7122:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7123:        while (<$fh>) {
1.390     matthew  7124:            next if (/^(\#|\s*$)/);
                   7125: #           next if /^\#/;
1.327     albertel 7126:            chomp;
1.403     www      7127:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7128: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7129: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7130:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7131: 	   $domaindescription{$domain}=$domain_description;
                   7132: 	   $domain_lang_def{$domain}=$def_lang;
                   7133: 	   $domain_city{$domain}=$city;
                   7134: 	   $domain_longi{$domain}=$longi;
                   7135: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7136:            $domain_primary{$domain}=$primary;
1.403     www      7137: 
1.448     albertel 7138:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7139: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7140: 	}
1.327     albertel 7141:     }
1.448     albertel 7142:     close ($fh);
1.327     albertel 7143: }
                   7144: 
                   7145: 
1.1       albertel 7146: # ------------------------------------------------------------- Read hosts file
                   7147: {
1.448     albertel 7148:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7149: 
                   7150:     while (my $configline=<$config>) {
1.303     matthew  7151:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7152:        chomp($configline);
1.595     albertel 7153:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7154:        $name=~s/\s//g;
1.595     albertel 7155:        if ($id && $domain && $role && $name) {
1.252     albertel 7156: 	 $hostname{$id}=$name;
                   7157: 	 $hostdom{$id}=$domain;
                   7158: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7159:        }
1.1       albertel 7160:     }
1.448     albertel 7161:     close($config);
1.619     albertel 7162:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7163:     #&get_iphost();
1.1       albertel 7164: }
                   7165: 
1.598     albertel 7166: sub get_iphost {
                   7167:     if (%iphost) { return %iphost; }
1.653     albertel 7168:     my %name_to_ip;
1.598     albertel 7169:     foreach my $id (keys(%hostname)) {
                   7170: 	my $name=$hostname{$id};
1.653     albertel 7171: 	my $ip;
                   7172: 	if (!exists($name_to_ip{$name})) {
                   7173: 	    $ip = gethostbyname($name);
                   7174: 	    if (!$ip || length($ip) ne 4) {
                   7175: 		&logthis("Skipping host $id name $name no IP found\n");
                   7176: 		next;
                   7177: 	    }
                   7178: 	    $ip=inet_ntoa($ip);
                   7179: 	    $name_to_ip{$name} = $ip;
                   7180: 	} else {
                   7181: 	    $ip = $name_to_ip{$name};
1.598     albertel 7182: 	}
                   7183: 	push(@{$iphost{$ip}},$id);
                   7184:     }
                   7185:     return %iphost;
                   7186: }
                   7187: 
1.1       albertel 7188: # ------------------------------------------------------ Read spare server file
                   7189: {
1.448     albertel 7190:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7191: 
                   7192:     while (my $configline=<$config>) {
                   7193:        chomp($configline);
1.284     matthew  7194:        if ($configline) {
1.1       albertel 7195:           $spareid{$configline}=1;
                   7196:        }
                   7197:     }
1.448     albertel 7198:     close($config);
1.1       albertel 7199: }
1.11      www      7200: # ------------------------------------------------------------ Read permissions
                   7201: {
1.448     albertel 7202:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7203: 
                   7204:     while (my $configline=<$config>) {
1.448     albertel 7205: 	chomp($configline);
                   7206: 	if ($configline) {
                   7207: 	    my ($role,$perm)=split(/ /,$configline);
                   7208: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7209: 	}
1.11      www      7210:     }
1.448     albertel 7211:     close($config);
1.11      www      7212: }
                   7213: 
                   7214: # -------------------------------------------- Read plain texts for permissions
                   7215: {
1.448     albertel 7216:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7217: 
                   7218:     while (my $configline=<$config>) {
1.448     albertel 7219: 	chomp($configline);
                   7220: 	if ($configline) {
1.742     raeburn  7221: 	    my ($short,@plain)=split(/:/,$configline);
                   7222:             %{$prp{$short}} = ();
                   7223: 	    if (@plain > 0) {
                   7224:                 $prp{$short}{'std'} = $plain[0];
                   7225:                 for (my $i=1; $i<@plain; $i++) {
                   7226:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7227:                 }
                   7228:             }
1.448     albertel 7229: 	}
1.135     www      7230:     }
1.448     albertel 7231:     close($config);
1.135     www      7232: }
                   7233: 
                   7234: # ---------------------------------------------------------- Read package table
                   7235: {
1.448     albertel 7236:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7237: 
                   7238:     while (my $configline=<$config>) {
1.483     albertel 7239: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7240: 	chomp($configline);
                   7241: 	my ($short,$plain)=split(/:/,$configline);
                   7242: 	my ($pack,$name)=split(/\&/,$short);
                   7243: 	if ($plain ne '') {
                   7244: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7245: 	    $packagetab{$short}=$plain; 
                   7246: 	}
1.11      www      7247:     }
1.448     albertel 7248:     close($config);
1.329     matthew  7249: }
                   7250: 
                   7251: # ------------- set up temporary directory
                   7252: {
                   7253:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7254: 
1.11      www      7255: }
                   7256: 
1.599     albertel 7257: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7258: 
1.281     www      7259: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7260: $dumpcount=0;
1.22      www      7261: 
1.163     harris41 7262: &logtouch();
1.672     albertel 7263: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7264: $readit=1;
1.564     albertel 7265:     {
                   7266: 	use integer;
                   7267: 	my $test=(2**32)+1;
1.568     albertel 7268: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7269: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7270:     }
1.195     www      7271: }
1.1       albertel 7272: }
1.179     www      7273: 
1.1       albertel 7274: 1;
1.191     harris41 7275: __END__
                   7276: 
1.243     albertel 7277: =pod
                   7278: 
1.191     harris41 7279: =head1 NAME
                   7280: 
1.243     albertel 7281: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7282: 
                   7283: =head1 SYNOPSIS
                   7284: 
1.243     albertel 7285: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7286: 
                   7287:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7288: 
1.243     albertel 7289: Common parameters:
                   7290: 
                   7291: =over 4
                   7292: 
                   7293: =item *
                   7294: 
                   7295: $uname : an internal username (if $cname expecting a course Id specifically)
                   7296: 
                   7297: =item *
                   7298: 
                   7299: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7300: 
                   7301: =item *
                   7302: 
                   7303: $symb : a resource instance identifier
                   7304: 
                   7305: =item *
                   7306: 
                   7307: $namespace : the name of a .db file that contains the data needed or
                   7308: being set.
                   7309: 
                   7310: =back
                   7311: 
1.394     bowersj2 7312: =head1 OVERVIEW
1.191     harris41 7313: 
1.394     bowersj2 7314: lonnet provides subroutines which interact with the
                   7315: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7316: about classes, users, and resources.
1.243     albertel 7317: 
                   7318: For many of these objects you can also use this to store data about
                   7319: them or modify them in various ways.
1.191     harris41 7320: 
1.394     bowersj2 7321: =head2 Symbs
1.191     harris41 7322: 
1.394     bowersj2 7323: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7324: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7325: map, the resource number of the resource in the map, and the URL of
                   7326: the resource itself. The latter is somewhat redundant, but might help
                   7327: if maps change.
                   7328: 
                   7329: An example is
                   7330: 
                   7331:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7332: 
                   7333: The respective map entry is
                   7334: 
                   7335:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7336:   title="Problem 2">
                   7337:  </resource>
                   7338: 
                   7339: Symbs are used by the random number generator, as well as to store and
                   7340: restore data specific to a certain instance of for example a problem.
                   7341: 
                   7342: =head2 Storing And Retrieving Data
                   7343: 
                   7344: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7345: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7346: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7347: is is the non-critical message twin of cstore. These functions are for
                   7348: handlers to store a perl hash to a user's permanent data space in an
                   7349: easy manner, and to retrieve it again on another call. It is expected
                   7350: that a handler would use this once at the beginning to retrieve data,
                   7351: and then again once at the end to send only the new data back.
                   7352: 
                   7353: The data is stored in the user's data directory on the user's
                   7354: homeserver under the ID of the course.
                   7355: 
                   7356: The hash that is returned by restore will have all of the previous
                   7357: value for all of the elements of the hash.
                   7358: 
                   7359: Example:
                   7360: 
                   7361:  #creating a hash
                   7362:  my %hash;
                   7363:  $hash{'foo'}='bar';
                   7364: 
                   7365:  #storing it
                   7366:  &Apache::lonnet::cstore(\%hash);
                   7367: 
                   7368:  #changing a value
                   7369:  $hash{'foo'}='notbar';
                   7370: 
                   7371:  #adding a new value
                   7372:  $hash{'bar'}='foo';
                   7373:  &Apache::lonnet::cstore(\%hash);
                   7374: 
                   7375:  #retrieving the hash
                   7376:  my %history=&Apache::lonnet::restore();
                   7377: 
                   7378:  #print the hash
                   7379:  foreach my $key (sort(keys(%history))) {
                   7380:    print("\%history{$key} = $history{$key}");
                   7381:  }
                   7382: 
                   7383: Will print out:
1.191     harris41 7384: 
1.394     bowersj2 7385:  %history{1:foo} = bar
                   7386:  %history{1:keys} = foo:timestamp
                   7387:  %history{1:timestamp} = 990455579
                   7388:  %history{2:bar} = foo
                   7389:  %history{2:foo} = notbar
                   7390:  %history{2:keys} = foo:bar:timestamp
                   7391:  %history{2:timestamp} = 990455580
                   7392:  %history{bar} = foo
                   7393:  %history{foo} = notbar
                   7394:  %history{timestamp} = 990455580
                   7395:  %history{version} = 2
                   7396: 
                   7397: Note that the special hash entries C<keys>, C<version> and
                   7398: C<timestamp> were added to the hash. C<version> will be equal to the
                   7399: total number of versions of the data that have been stored. The
                   7400: C<timestamp> attribute will be the UNIX time the hash was
                   7401: stored. C<keys> is available in every historical section to list which
                   7402: keys were added or changed at a specific historical revision of a
                   7403: hash.
                   7404: 
                   7405: B<Warning>: do not store the hash that restore returns directly. This
                   7406: will cause a mess since it will restore the historical keys as if the
                   7407: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7408: 
1.394     bowersj2 7409: Calling convention:
1.191     harris41 7410: 
1.394     bowersj2 7411:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7412:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7413: 
1.394     bowersj2 7414: For more detailed information, see lonnet specific documentation.
1.191     harris41 7415: 
1.394     bowersj2 7416: =head1 RETURN MESSAGES
1.191     harris41 7417: 
1.394     bowersj2 7418: =over 4
1.191     harris41 7419: 
1.394     bowersj2 7420: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7421: 
1.394     bowersj2 7422: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7423: when the connection is brought back up
1.191     harris41 7424: 
1.394     bowersj2 7425: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7426: for later delivery
1.191     harris41 7427: 
1.394     bowersj2 7428: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7429: 
1.394     bowersj2 7430: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7431: that was requested
1.191     harris41 7432: 
1.243     albertel 7433: =back
1.191     harris41 7434: 
1.243     albertel 7435: =head1 PUBLIC SUBROUTINES
1.191     harris41 7436: 
1.243     albertel 7437: =head2 Session Environment Functions
1.191     harris41 7438: 
1.243     albertel 7439: =over 4
1.191     harris41 7440: 
1.394     bowersj2 7441: =item * 
                   7442: X<appenv()>
                   7443: B<appenv(%hash)>: the value of %hash is written to
                   7444: the user envirnoment file, and will be restored for each access this
1.620     albertel 7445: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7446: process
1.191     harris41 7447: 
                   7448: =item *
1.394     bowersj2 7449: X<delenv()>
                   7450: B<delenv($regexp)>: removes all items from the session
                   7451: environment file that matches the regular expression in $regexp. The
1.620     albertel 7452: values are also delted from the current processes %env.
1.191     harris41 7453: 
1.243     albertel 7454: =back
                   7455: 
                   7456: =head2 User Information
1.191     harris41 7457: 
1.243     albertel 7458: =over 4
1.191     harris41 7459: 
                   7460: =item *
1.394     bowersj2 7461: X<queryauthenticate()>
                   7462: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7463: authentication scheme
                   7464: 
                   7465: =item *
1.394     bowersj2 7466: X<authenticate()>
                   7467: B<authenticate($uname,$upass,$udom)>: try to
                   7468: authenticate user from domain's lib servers (first use the current
                   7469: one). C<$upass> should be the users password.
1.191     harris41 7470: 
                   7471: =item *
1.394     bowersj2 7472: X<homeserver()>
                   7473: B<homeserver($uname,$udom)>: find the server which has
                   7474: the user's directory and files (there must be only one), this caches
                   7475: the answer, and also caches if there is a borken connection.
1.191     harris41 7476: 
                   7477: =item *
1.394     bowersj2 7478: X<idget()>
                   7479: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7480: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7481: username, and only 1 username per ID in a specific domain) (returns
                   7482: hash: id=>name,id=>name)
1.191     harris41 7483: 
                   7484: =item *
1.394     bowersj2 7485: X<idrget()>
                   7486: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7487: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7488: 
                   7489: =item *
1.394     bowersj2 7490: X<idput()>
                   7491: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7492: 
                   7493: =item *
1.394     bowersj2 7494: X<rolesinit()>
                   7495: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7496: 
                   7497: =item *
1.551     albertel 7498: X<getsection()>
                   7499: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7500: course $cname, return section name/number or '' for "not in course"
                   7501: and '-1' for "no section"
                   7502: 
                   7503: =item *
1.394     bowersj2 7504: X<userenvironment()>
                   7505: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7506: passed in @what from the requested user's environment, returns a hash
                   7507: 
                   7508: =back
                   7509: 
                   7510: =head2 User Roles
                   7511: 
                   7512: =over 4
                   7513: 
                   7514: =item *
                   7515: 
                   7516: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7517: actions
                   7518:  F: full access
                   7519:  U,I,K: authentication modes (cxx only)
                   7520:  '': forbidden
                   7521:  1: user needs to choose course
                   7522:  2: browse allowed
1.766     albertel 7523:  A: passphrase authentication needed
1.243     albertel 7524: 
                   7525: =item *
                   7526: 
                   7527: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7528: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7529: and course level
                   7530: 
                   7531: =item *
                   7532: 
                   7533: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7534: explanation of a user role term
                   7535: 
                   7536: =back
                   7537: 
                   7538: =head2 User Modification
                   7539: 
                   7540: =over 4
                   7541: 
                   7542: =item *
                   7543: 
                   7544: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7545: user for the level given by URL.  Optional start and end dates (leave empty
                   7546: string or zero for "no date")
1.191     harris41 7547: 
                   7548: =item *
                   7549: 
1.243     albertel 7550: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7551: change a users, password, possible return values are: ok,
                   7552: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7553: refused
1.191     harris41 7554: 
                   7555: =item *
                   7556: 
1.243     albertel 7557: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7558: 
                   7559: =item *
                   7560: 
1.243     albertel 7561: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7562: modify user
1.191     harris41 7563: 
                   7564: =item *
                   7565: 
1.286     matthew  7566: modifystudent
                   7567: 
                   7568: modify a students enrollment and identification information.
                   7569: The course id is resolved based on the current users environment.  
                   7570: This means the envoking user must be a course coordinator or otherwise
                   7571: associated with a course.
                   7572: 
1.297     matthew  7573: This call is essentially a wrapper for lonnet::modifyuser and
                   7574: lonnet::modify_student_enrollment
1.286     matthew  7575: 
                   7576: Inputs: 
                   7577: 
                   7578: =over 4
                   7579: 
                   7580: =item B<$udom> Students loncapa domain
                   7581: 
                   7582: =item B<$uname> Students loncapa login name
                   7583: 
                   7584: =item B<$uid> Students id/student number
                   7585: 
                   7586: =item B<$umode> Students authentication mode
                   7587: 
                   7588: =item B<$upass> Students password
                   7589: 
                   7590: =item B<$first> Students first name
                   7591: 
                   7592: =item B<$middle> Students middle name
                   7593: 
                   7594: =item B<$last> Students last name
                   7595: 
                   7596: =item B<$gene> Students generation
                   7597: 
                   7598: =item B<$usec> Students section in course
                   7599: 
                   7600: =item B<$end> Unix time of the roles expiration
                   7601: 
                   7602: =item B<$start> Unix time of the roles start date
                   7603: 
                   7604: =item B<$forceid> If defined, allow $uid to be changed
                   7605: 
                   7606: =item B<$desiredhome> server to use as home server for student
                   7607: 
                   7608: =back
1.297     matthew  7609: 
                   7610: =item *
                   7611: 
                   7612: modify_student_enrollment
                   7613: 
                   7614: Change a students enrollment status in a class.  The environment variable
                   7615: 'role.request.course' must be defined for this function to proceed.
                   7616: 
                   7617: Inputs:
                   7618: 
                   7619: =over 4
                   7620: 
                   7621: =item $udom, students domain
                   7622: 
                   7623: =item $uname, students name
                   7624: 
                   7625: =item $uid, students user id
                   7626: 
                   7627: =item $first, students first name
                   7628: 
                   7629: =item $middle
                   7630: 
                   7631: =item $last
                   7632: 
                   7633: =item $gene
                   7634: 
                   7635: =item $usec
                   7636: 
                   7637: =item $end
                   7638: 
                   7639: =item $start
                   7640: 
                   7641: =back
                   7642: 
1.191     harris41 7643: 
                   7644: =item *
                   7645: 
1.243     albertel 7646: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7647: custom role; give a custom role to a user for the level given by URL.  Specify
                   7648: name and domain of role author, and role name
1.191     harris41 7649: 
                   7650: =item *
                   7651: 
1.243     albertel 7652: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7653: 
                   7654: =item *
                   7655: 
1.243     albertel 7656: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7657: 
                   7658: =back
                   7659: 
                   7660: =head2 Course Infomation
                   7661: 
                   7662: =over 4
1.191     harris41 7663: 
                   7664: =item *
                   7665: 
1.631     albertel 7666: coursedescription($courseid) : returns a hash of information about the
                   7667: specified course id, including all environment settings for the
                   7668: course, the description of the course will be in the hash under the
                   7669: key 'description'
1.191     harris41 7670: 
                   7671: =item *
                   7672: 
1.624     albertel 7673: resdata($name,$domain,$type,@which) : request for current parameter
                   7674: setting for a specific $type, where $type is either 'course' or 'user',
                   7675: @what should be a list of parameters to ask about. This routine caches
                   7676: answers for 5 minutes.
1.243     albertel 7677: 
                   7678: =back
                   7679: 
                   7680: =head2 Course Modification
                   7681: 
                   7682: =over 4
1.191     harris41 7683: 
                   7684: =item *
                   7685: 
1.243     albertel 7686: writecoursepref($courseid,%prefs) : write preferences (environment
                   7687: database) for a course
1.191     harris41 7688: 
                   7689: =item *
                   7690: 
1.243     albertel 7691: createcourse($udom,$description,$url) : make/modify course
                   7692: 
                   7693: =back
                   7694: 
                   7695: =head2 Resource Subroutines
                   7696: 
                   7697: =over 4
1.191     harris41 7698: 
                   7699: =item *
                   7700: 
1.243     albertel 7701: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7702: 
                   7703: =item *
                   7704: 
1.243     albertel 7705: repcopy($filename) : subscribes to the requested file, and attempts to
                   7706: replicate from the owning library server, Might return
1.607     raeburn  7707: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7708: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7709: resource. Expects the local filesystem pathname
                   7710: (/home/httpd/html/res/....)
                   7711: 
                   7712: =back
                   7713: 
                   7714: =head2 Resource Information
                   7715: 
                   7716: =over 4
1.191     harris41 7717: 
                   7718: =item *
                   7719: 
1.243     albertel 7720: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7721: a vairety of different possible values, $varname should be a request
                   7722: string, and the other parameters can be used to specify who and what
                   7723: one is asking about.
                   7724: 
                   7725: Possible values for $varname are environment.lastname (or other item
                   7726: from the envirnment hash), user.name (or someother aspect about the
                   7727: user), resource.0.maxtries (or some other part and parameter of a
                   7728: resource)
1.204     albertel 7729: 
                   7730: =item *
                   7731: 
1.243     albertel 7732: directcondval($number) : get current value of a condition; reads from a state
                   7733: string
1.204     albertel 7734: 
                   7735: =item *
                   7736: 
1.243     albertel 7737: condval($condidx) : value of condition index based on state
1.204     albertel 7738: 
                   7739: =item *
                   7740: 
1.243     albertel 7741: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7742: resource's metadata, $what should be either a specific key, or either
                   7743: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7744: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7745: 
                   7746: this function automatically caches all requests
1.191     harris41 7747: 
                   7748: =item *
                   7749: 
1.243     albertel 7750: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7751: network of library servers; returns file handle of where SQL and regex results
                   7752: will be stored for query
1.191     harris41 7753: 
                   7754: =item *
                   7755: 
1.243     albertel 7756: symbread($filename) : return symbolic list entry (filename argument optional);
                   7757: returns the data handle
1.191     harris41 7758: 
                   7759: =item *
                   7760: 
1.243     albertel 7761: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7762: a possible symb for the URL in $thisfn, and if is an encryypted
                   7763: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7764: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7765: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7766: 
1.191     harris41 7767: 
                   7768: =item *
                   7769: 
1.243     albertel 7770: symbclean($symb) : removes versions numbers from a symb, returns the
                   7771: cleaned symb
1.191     harris41 7772: 
                   7773: =item *
                   7774: 
1.243     albertel 7775: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7776: course map, user must be in a course for it to work.
1.191     harris41 7777: 
                   7778: =item *
                   7779: 
1.243     albertel 7780: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7781: 
                   7782: =item *
                   7783: 
1.243     albertel 7784: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7785: a random seed, all arguments are optional, if they aren't sent it uses the
                   7786: environment to derive them. Note: if symb isn't sent and it can't get one
                   7787: from &symbread it will use the current time as its return value
1.191     harris41 7788: 
                   7789: =item *
                   7790: 
1.243     albertel 7791: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7792: unfakeable, receipt
1.191     harris41 7793: 
                   7794: =item *
                   7795: 
1.620     albertel 7796: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7797: 
                   7798: =item *
                   7799: 
1.243     albertel 7800: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7801: 
                   7802: =item *
                   7803: 
1.243     albertel 7804: 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 7805: 
                   7806: =item *
                   7807: 
1.243     albertel 7808: 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 7809: 
                   7810: =item *
                   7811: 
1.243     albertel 7812: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7813: 
                   7814: =item *
                   7815: 
1.243     albertel 7816: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7817: forcing spreadsheet to reevaluate the resource scores next time.
                   7818: 
                   7819: =back
                   7820: 
                   7821: =head2 Storing/Retreiving Data
                   7822: 
                   7823: =over 4
1.191     harris41 7824: 
                   7825: =item *
                   7826: 
1.243     albertel 7827: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7828: for this url; hashref needs to be given and should be a \%hashname; the
                   7829: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7830: be derived from the env
1.191     harris41 7831: 
                   7832: =item *
                   7833: 
1.243     albertel 7834: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7835: uses critical subroutine
1.191     harris41 7836: 
                   7837: =item *
                   7838: 
1.243     albertel 7839: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7840: all args are optional
1.191     harris41 7841: 
                   7842: =item *
                   7843: 
1.717     albertel 7844: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7845: dumps the complete (or key matching regexp) namespace into a hash
                   7846: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7847: normally &store()ed into
                   7848: 
                   7849: $range should be either an integer '100' (give me the first 100
                   7850:                                            matching records)
                   7851:               or be  two integers sperated by a - with no spaces
                   7852:                  '30-50' (give me the 30th through the 50th matching
                   7853:                           records)
                   7854: 
                   7855: 
                   7856: =item *
                   7857: 
                   7858: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7859: replaces a &store() version of data with a replacement set of data
                   7860: for a particular resource in a namespace passed in the $storehash hash 
                   7861: reference
                   7862: 
                   7863: =item *
                   7864: 
1.243     albertel 7865: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7866: works very similar to store/cstore, but all data is stored in a
                   7867: temporary location and can be reset using tmpreset, $storehash should
                   7868: be a hash reference, returns nothing on success
1.191     harris41 7869: 
                   7870: =item *
                   7871: 
1.243     albertel 7872: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7873: similar to restore, but all data is stored in a temporary location and
                   7874: can be reset using tmpreset. Returns a hash of values on success,
                   7875: error string otherwise.
1.191     harris41 7876: 
                   7877: =item *
                   7878: 
1.243     albertel 7879: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7880: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7881: 
                   7882: =item *
                   7883: 
1.243     albertel 7884: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7885: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7886: 
                   7887: =item *
                   7888: 
1.243     albertel 7889: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7890: namesp ($udom and $uname are optional)
1.191     harris41 7891: 
                   7892: =item *
                   7893: 
1.702     albertel 7894: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7895: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7896: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7897: 
1.702     albertel 7898: $range should be either an integer '100' (give me the first 100
                   7899:                                            matching records)
                   7900:               or be  two integers sperated by a - with no spaces
                   7901:                  '30-50' (give me the 30th through the 50th matching
                   7902:                           records)
1.449     matthew  7903: =item *
                   7904: 
                   7905: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7906: $store can be a scalar, an array reference, or if the amount to be 
                   7907: incremented is > 1, a hash reference.
                   7908: 
                   7909: ($udom and $uname are optional)
1.191     harris41 7910: 
                   7911: =item *
                   7912: 
1.243     albertel 7913: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7914: ($udom and $uname are optional)
1.191     harris41 7915: 
                   7916: =item *
                   7917: 
1.243     albertel 7918: cput($namespace,$storehash,$udom,$uname) : critical put
                   7919: ($udom and $uname are optional)
1.191     harris41 7920: 
                   7921: =item *
                   7922: 
1.748     albertel 7923: newput($namespace,$storehash,$udom,$uname) :
                   7924: 
                   7925: Attempts to store the items in the $storehash, but only if they don't
                   7926: currently exist, if this succeeds you can be certain that you have 
                   7927: successfully created a new key value pair in the $namespace db.
                   7928: 
                   7929: 
                   7930: Args:
                   7931:  $namespace: name of database to store values to
                   7932:  $storehash: hashref to store to the db
                   7933:  $udom: (optional) domain of user containing the db
                   7934:  $uname: (optional) name of user caontaining the db
                   7935: 
                   7936: Returns:
                   7937:  'ok' -> succeeded in storing all keys of $storehash
                   7938:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7939:                         least <key> already existed in the db (other
                   7940:                         requested keys may also already exist)
                   7941:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7942:  'con_lost' -> unable to contact request server
                   7943:  'refused' -> action was not allowed by remote machine
                   7944: 
                   7945: 
                   7946: =item *
                   7947: 
1.243     albertel 7948: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7949: reference filled in from namesp (encrypts the return communication)
                   7950: ($udom and $uname are optional)
1.191     harris41 7951: 
                   7952: =item *
                   7953: 
1.243     albertel 7954: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7955: critical subroutine
                   7956: 
                   7957: =back
                   7958: 
                   7959: =head2 Network Status Functions
                   7960: 
                   7961: =over 4
1.191     harris41 7962: 
                   7963: =item *
                   7964: 
                   7965: dirlist($uri) : return directory list based on URI
                   7966: 
                   7967: =item *
                   7968: 
1.243     albertel 7969: spareserver() : find server with least workload from spare.tab
                   7970: 
                   7971: =back
                   7972: 
                   7973: =head2 Apache Request
                   7974: 
                   7975: =over 4
1.191     harris41 7976: 
                   7977: =item *
                   7978: 
1.243     albertel 7979: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7980: localhost, posts hash
                   7981: 
                   7982: =back
                   7983: 
                   7984: =head2 Data to String to Data
                   7985: 
                   7986: =over 4
1.191     harris41 7987: 
                   7988: =item *
                   7989: 
1.243     albertel 7990: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7991: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7992: 
                   7993: =item *
                   7994: 
1.243     albertel 7995: hashref2str($hashref) : convert a hashref into a string complete with
                   7996: escaping and '=' and '&' separators, supports elements that are
                   7997: arrayrefs and hashrefs
1.191     harris41 7998: 
                   7999: =item *
                   8000: 
1.243     albertel 8001: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8002: with escaping and '&' separators, supports elements that are arrayrefs
                   8003: and hashrefs
1.191     harris41 8004: 
                   8005: =item *
                   8006: 
1.243     albertel 8007: str2hash($string) : convert string to hash using unescaping and
                   8008: splitting on '=' and '&', supports elements that are arrayrefs and
                   8009: hashrefs
1.191     harris41 8010: 
                   8011: =item *
                   8012: 
1.243     albertel 8013: str2array($string) : convert string to hash using unescaping and
                   8014: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8015: 
                   8016: =back
                   8017: 
                   8018: =head2 Logging Routines
                   8019: 
                   8020: =over 4
                   8021: 
                   8022: These routines allow one to make log messages in the lonnet.log and
                   8023: lonnet.perm logfiles.
1.191     harris41 8024: 
                   8025: =item *
                   8026: 
1.243     albertel 8027: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8028: 
                   8029: =item *
                   8030: 
1.243     albertel 8031: logthis() : append message to the normal lonnet.log file, it gets
                   8032: preiodically rolled over and deleted.
1.191     harris41 8033: 
                   8034: =item *
                   8035: 
1.243     albertel 8036: logperm() : append a permanent message to lonnet.perm.log, this log
                   8037: file never gets deleted by any automated portion of the system, only
                   8038: messages of critical importance should go in here.
                   8039: 
                   8040: =back
                   8041: 
                   8042: =head2 General File Helper Routines
                   8043: 
                   8044: =over 4
1.191     harris41 8045: 
                   8046: =item *
                   8047: 
1.481     raeburn  8048: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8049: (a) files in /uploaded
                   8050:   (i) If a local copy of the file exists - 
                   8051:       compares modification date of local copy with last-modified date for 
                   8052:       definitive version stored on home server for course. If local copy is 
                   8053:       stale, requests a new version from the home server and stores it. 
                   8054:       If the original has been removed from the home server, then local copy 
                   8055:       is unlinked.
                   8056:   (ii) If local copy does not exist -
                   8057:       requests the file from the home server and stores it. 
                   8058:   
                   8059:   If $caller is 'uploadrep':  
                   8060:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8061:     for request for files originally uploaded via DOCS. 
                   8062:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8063:   
                   8064:   Otherwise:
                   8065:      This indicates a call from the content generation phase of the request.
                   8066:      -  returns the entire contents of the file or -1.
                   8067:      
                   8068: (b) files in /res
                   8069:    - returns the entire contents of a file or -1; 
                   8070:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8071: 
1.712     albertel 8072: 
                   8073: =item *
                   8074: 
                   8075: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8076:                   reference
                   8077: 
                   8078: returns either a stat() list of data about the file or an empty list
                   8079: if the file doesn't exist or couldn't find out about it (connection
                   8080: problems or user unknown)
                   8081: 
1.191     harris41 8082: =item *
                   8083: 
1.243     albertel 8084: filelocation($dir,$file) : returns file system location of a file
                   8085: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8086: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8087: and a file of ../bob will become /a/bob)
1.191     harris41 8088: 
                   8089: =item *
                   8090: 
                   8091: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8092: filelocation except for hrefs
                   8093: 
                   8094: =item *
                   8095: 
                   8096: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8097: 
1.243     albertel 8098: =back
                   8099: 
1.608     albertel 8100: =head2 Usererfile file routines (/uploaded*)
                   8101: 
                   8102: =over 4
                   8103: 
                   8104: =item *
                   8105: 
                   8106: userfileupload(): main rotine for putting a file in a user or course's
                   8107:                   filespace, arguments are,
                   8108: 
1.620     albertel 8109:  formname - required - this is the name of the element in $env where the
1.608     albertel 8110:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8111:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8112:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8113:  coursedoc - if true, store the file in the course of the active role
                   8114:              of the current user
                   8115:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8116:          if undefined, it will be placed in "unknown"
                   8117: 
                   8118:  (This routine calls clean_filename() to remove any dangerous
                   8119:  characters from the filename, and then calls finuserfileupload() to
                   8120:  complete the transaction)
                   8121: 
                   8122:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8123:  and /adm/notfound.html if unsuccessful
                   8124: 
                   8125: =item *
                   8126: 
                   8127: clean_filename(): routine for cleaing a filename up for storage in
                   8128:                  userfile space, argument is:
                   8129: 
                   8130:  filename - proposed filename
                   8131: 
                   8132: returns: the new clean filename
                   8133: 
                   8134: =item *
                   8135: 
                   8136: finishuserfileupload(): routine that creaes and sends the file to
                   8137: userspace, probably shouldn't be called directly
                   8138: 
                   8139:   docuname: username or courseid of destination for the file
                   8140:   docudom: domain of user/course of destination for the file
                   8141:   formname: same as for userfileupload()
                   8142:   fname: filename (inculding subdirectories) for the file
                   8143: 
                   8144:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8145:  and /adm/notfound.html if unsuccessful
                   8146: 
                   8147: =item *
                   8148: 
                   8149: renameuserfile(): renames an existing userfile to a new name
                   8150: 
                   8151:   Args:
                   8152:    docuname: username or courseid of destination for the file
                   8153:    docudom: domain of user/course of destination for the file
                   8154:    old: current file name (including any subdirs under userfiles)
                   8155:    new: desired file name (including any subdirs under userfiles)
                   8156: 
                   8157: =item *
                   8158: 
                   8159: mkdiruserfile(): creates a directory is a userfiles dir
                   8160: 
                   8161:   Args:
                   8162:    docuname: username or courseid of destination for the file
                   8163:    docudom: domain of user/course of destination for the file
                   8164:    dir: dir to create (including any subdirs under userfiles)
                   8165: 
                   8166: =item *
                   8167: 
                   8168: removeuserfile(): removes a file that exists in userfiles
                   8169: 
                   8170:   Args:
                   8171:    docuname: username or courseid of destination for the file
                   8172:    docudom: domain of user/course of destination for the file
                   8173:    fname: filname to delete (including any subdirs under userfiles)
                   8174: 
                   8175: =item *
                   8176: 
                   8177: removeuploadedurl(): convience function for removeuserfile()
                   8178: 
                   8179:   Args:
                   8180:    url:  a full /uploaded/... url to delete
                   8181: 
1.747     albertel 8182: =item * 
                   8183: 
                   8184: get_portfile_permissions():
                   8185:   Args:
                   8186:     domain: domain of user or course contain the portfolio files
                   8187:     user: name of user or num of course contain the portfolio files
                   8188:   Returns:
                   8189:     hashref of a dump of the proper file_permissions.db
                   8190:    
                   8191: 
                   8192: =item * 
                   8193: 
                   8194: get_access_controls():
                   8195: 
                   8196: Args:
                   8197:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8198:   group: (optional) the group you want the files associated with
                   8199:   file: (optional) the file you want access info on
                   8200: 
                   8201: Returns:
1.749     raeburn  8202:     a hash (keys are file names) of hashes containing
                   8203:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8204:         values are XML containing access control settings (see below) 
1.747     albertel 8205: 
                   8206: Internal notes:
                   8207: 
1.749     raeburn  8208:  access controls are stored in file_permissions.db as key=value pairs.
                   8209:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8210:         where scope -> public,guest,course,group,domains or users.
                   8211:               end -> UNIX time for end of access (0 -> no end date)
                   8212:               start -> UNIX time for start of access
                   8213: 
                   8214:     value -> XML description of access control
                   8215:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8216:             <start></start>
                   8217:             <end></end>
                   8218: 
                   8219:             <password></password>  for scope type = guest
                   8220: 
                   8221:             <domain></domain>     for scope type = course or group
                   8222:             <number></number>
                   8223:             <roles id="">
                   8224:              <role></role>
                   8225:              <access></access>
                   8226:              <section></section>
                   8227:              <group></group>
                   8228:             </roles>
                   8229: 
                   8230:             <dom></dom>         for scope type = domains
                   8231: 
                   8232:             <users>             for scope type = users
                   8233:              <user>
                   8234:               <uname></uname>
                   8235:               <udom></udom>
                   8236:              </user>
                   8237:             </users>
                   8238:            </scope> 
                   8239:               
                   8240:  Access data is also aggregated for each file in an additional key=value pair:
                   8241:  key -> path to file/file_name\0accesscontrol 
                   8242:  value -> reference to hash
                   8243:           hash contains key = value pairs
                   8244:           where key = uniqueID:scope_end_start
                   8245:                 value = UNIX time record was last updated
                   8246: 
                   8247:           Used to improve speed of look-ups of access controls for each file.  
                   8248:  
                   8249:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8250: 
                   8251: modify_access_controls():
                   8252: 
                   8253: Modifies access controls for a portfolio file
                   8254: Args
                   8255: 1. file name
                   8256: 2. reference to hash of required changes,
                   8257: 3. domain
                   8258: 4. username
                   8259:   where domain,username are the domain of the portfolio owner 
                   8260:   (either a user or a course) 
                   8261: 
                   8262: Returns:
                   8263: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8264: 2. result of deletions ('ok' or 'error', with error message).
                   8265: 3. reference to hash of any new or updated access controls.
                   8266: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8267:    key = integer (inbound ID)
                   8268:    value = uniqueID  
1.747     albertel 8269: 
1.608     albertel 8270: =back
                   8271: 
1.243     albertel 8272: =head2 HTTP Helper Routines
                   8273: 
                   8274: =over 4
                   8275: 
1.191     harris41 8276: =item *
                   8277: 
                   8278: escape() : unpack non-word characters into CGI-compatible hex codes
                   8279: 
                   8280: =item *
                   8281: 
                   8282: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8283: 
1.243     albertel 8284: =back
                   8285: 
                   8286: =head1 PRIVATE SUBROUTINES
                   8287: 
                   8288: =head2 Underlying communication routines (Shouldn't call)
                   8289: 
                   8290: =over 4
                   8291: 
                   8292: =item *
                   8293: 
                   8294: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8295: 
                   8296: =item *
                   8297: 
                   8298: reply() : uses subreply to send a message to remote machine, logs all failures
                   8299: 
                   8300: =item *
                   8301: 
                   8302: critical() : passes a critical message to another server; if cannot
                   8303: get through then place message in connection buffer directory and
                   8304: returns con_delayed, if incapable of saving message, returns
                   8305: con_failed
                   8306: 
                   8307: =item *
                   8308: 
                   8309: reconlonc() : tries to reconnect lonc client processes.
                   8310: 
                   8311: =back
                   8312: 
                   8313: =head2 Resource Access Logging
                   8314: 
                   8315: =over 4
                   8316: 
                   8317: =item *
                   8318: 
                   8319: flushcourselogs() : flush (save) buffer logs and access logs
                   8320: 
                   8321: =item *
                   8322: 
                   8323: courselog($what) : save message for course in hash
                   8324: 
                   8325: =item *
                   8326: 
                   8327: courseacclog($what) : save message for course using &courselog().  Perform
                   8328: special processing for specific resource types (problems, exams, quizzes, etc).
                   8329: 
1.191     harris41 8330: =item *
                   8331: 
                   8332: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8333: as a PerlChildExitHandler
1.243     albertel 8334: 
                   8335: =back
                   8336: 
                   8337: =head2 Other
                   8338: 
                   8339: =over 4
                   8340: 
                   8341: =item *
                   8342: 
                   8343: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8344: 
                   8345: =back
                   8346: 
                   8347: =cut

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