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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.782   ! albertel    4: # $Id: lonnet.pm,v 1.781 2006/09/15 20:49:29 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.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
1.780     albertel  296: my $env_loaded;
                    297: sub transfer_profile_to_env {
                    298:     if ($env_loaded) { return; } 
1.374     www       299: 
                    300:     my ($lonidsdir,$handle)=@_;
1.720     albertel  301:     if (!defined($lonidsdir)) {
                    302: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    303:     }
                    304:     if (!defined($handle)) {
                    305:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    306:     }
                    307: 
1.374     www       308:     my @profile;
                    309:     {
1.448     albertel  310: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       311: 	flock($idf,LOCK_SH);
                    312: 	@profile=<$idf>;
1.448     albertel  313: 	close($idf);
1.374     www       314:     }
                    315:     my $envi;
1.433     matthew   316:     my %Remove;
1.374     www       317:     for ($envi=0;$envi<=$#profile;$envi++) {
                    318: 	chomp($profile[$envi]);
1.690     albertel  319: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
1.726     albertel  320: 	$envname=&unescape($envname);
                    321: 	$envvalue=&unescape($envvalue);
1.619     albertel  322: 	$env{$envname} = $envvalue;
1.433     matthew   323:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    324:             if ($time < time-300) {
                    325:                 $Remove{$key}++;
                    326:             }
                    327:         }
                    328:     }
1.619     albertel  329:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  330:     $env_loaded=1;
1.433     matthew   331:     foreach my $expired_key (keys(%Remove)) {
                    332:         &delenv($expired_key);
1.374     www       333:     }
1.1       albertel  334: }
                    335: 
1.5       www       336: # ---------------------------------------------------------- Append Environment
                    337: 
                    338: sub appenv {
1.6       www       339:     my %newenv=@_;
1.692     albertel  340:     foreach my $key (keys(%newenv)) {
                    341: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  342:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  343:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       344:                 .'</font>');
1.692     albertel  345: 	    delete($newenv{$key});
1.35      www       346:         } else {
1.692     albertel  347:             $env{$key}=$newenv{$key};
1.35      www       348:         }
1.191     harris41  349:     }
1.779     albertel  350:     foreach my $key (keys(%newenv)) {
                    351: 	my $value = &escape($newenv{$key});
                    352: 	delete($newenv{$key});
                    353: 	$newenv{&escape($key)}=$value;
                    354:     }
1.95      www       355: 
                    356:     my $lockfh;
1.620     albertel  357:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  358: 	return 'error: '.$!;
1.95      www       359:     }
                    360:     unless (flock($lockfh,LOCK_EX)) {
1.672     albertel  361:          &logthis("<font color=\"blue\">WARNING: ".
1.95      www       362:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  363:          close($lockfh);
1.95      www       364:          return 'error: '.$!;
                    365:     }
                    366: 
1.6       www       367:     my @oldenv;
                    368:     {
1.448     albertel  369: 	my $fh;
1.620     albertel  370: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  371: 	    return 'error: '.$!;
                    372: 	}
                    373: 	@oldenv=<$fh>;
                    374: 	close($fh);
1.6       www       375:     }
                    376:     for (my $i=0; $i<=$#oldenv; $i++) {
                    377:         chomp($oldenv[$i]);
1.9       www       378:         if ($oldenv[$i] ne '') {
1.690     albertel  379: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
1.448     albertel  380: 	    unless (defined($newenv{$name})) {
                    381: 		$newenv{$name}=$value;
                    382: 	    }
1.9       www       383:         }
1.6       www       384:     }
                    385:     {
1.448     albertel  386: 	my $fh;
1.620     albertel  387: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  388: 	    return 'error';
                    389: 	}
                    390: 	my $newname;
                    391: 	foreach $newname (keys %newenv) {
1.779     albertel  392: 	    print $fh $newname.'='.$newenv{$newname}."\n";
1.448     albertel  393: 	}
                    394: 	close($fh);
1.56      www       395:     }
1.448     albertel  396: 	
                    397:     close($lockfh);
1.56      www       398:     return 'ok';
                    399: }
                    400: # ----------------------------------------------------- Delete from Environment
                    401: 
                    402: sub delenv {
                    403:     my $delthis=shift;
                    404:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  405:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       406:                 "Attempt to delete from environment ".$delthis);
                    407:         return 'error';
                    408:     }
                    409:     my @oldenv;
                    410:     {
1.448     albertel  411: 	my $fh;
1.620     albertel  412: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  413: 	    return 'error';
                    414: 	}
                    415: 	unless (flock($fh,LOCK_SH)) {
1.672     albertel  416: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  417: 		     'Could not obtain shared lock in delenv: '.$!);
                    418: 	    close($fh);
                    419: 	    return 'error: '.$!;
                    420: 	}
                    421: 	@oldenv=<$fh>;
                    422: 	close($fh);
1.56      www       423:     }
                    424:     {
1.448     albertel  425: 	my $fh;
1.620     albertel  426: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  427: 	    return 'error';
                    428: 	}
                    429: 	unless (flock($fh,LOCK_EX)) {
1.672     albertel  430: 	    &logthis("<font color=\"blue\">WARNING: ".
1.448     albertel  431: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    432: 	    close($fh);
                    433: 	    return 'error: '.$!;
                    434: 	}
1.692     albertel  435: 	foreach my $cur_key (@oldenv) {
1.726     albertel  436: 	    my $unescaped_cur_key = &unescape($cur_key);
                    437: 	    if ($unescaped_cur_key=~/^$delthis/) { 
                    438:                 my ($key) = split('=',$cur_key,2);
                    439: 		$key = &unescape($key);
1.619     albertel  440:                 delete($env{$key});
1.473     matthew   441:             } else {
1.692     albertel  442:                 print $fh $cur_key; 
1.473     matthew   443:             }
1.448     albertel  444: 	}
                    445: 	close($fh);
1.5       www       446:     }
                    447:     return 'ok';
1.369     albertel  448: }
                    449: 
                    450: # ------------------------------------------ Find out current server userload
                    451: # there is a copy in lond
                    452: sub userload {
                    453:     my $numusers=0;
                    454:     {
                    455: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    456: 	my $filename;
                    457: 	my $curtime=time;
                    458: 	while ($filename=readdir(LONIDS)) {
                    459: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  460: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  461: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  462: 	}
                    463: 	closedir(LONIDS);
                    464:     }
                    465:     my $userloadpercent=0;
                    466:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    467:     if ($maxuserload) {
1.371     albertel  468: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  469:     }
1.372     albertel  470:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  471:     return $userloadpercent;
1.283     www       472: }
                    473: 
                    474: # ------------------------------------------ Fight off request when overloaded
                    475: 
                    476: sub overloaderror {
                    477:     my ($r,$checkserver)=@_;
                    478:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    479:     my $loadavg;
                    480:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  481:        open(my $loadfile,'/proc/loadavg');
1.283     www       482:        $loadavg=<$loadfile>;
                    483:        $loadavg =~ s/\s.*//g;
1.285     matthew   484:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  485:        close($loadfile);
1.283     www       486:     } else {
                    487:        $loadavg=&reply('load',$checkserver);
                    488:     }
1.285     matthew   489:     my $overload=$loadavg-100;
1.283     www       490:     if ($overload>0) {
1.285     matthew   491: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       492:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       493:         return 413;
1.283     www       494:     }    
                    495:     return '';
1.5       www       496: }
1.1       albertel  497: 
                    498: # ------------------------------ Find server with least workload from spare.tab
1.11      www       499: 
1.1       albertel  500: sub spareserver {
1.670     albertel  501:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  502:     my $tryserver;
                    503:     my $spareserver='';
1.370     albertel  504:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    505:     my $lowestserver=$loadpercent > $userloadpercent?
                    506: 	             $loadpercent :  $userloadpercent;
1.670     albertel  507:     foreach $tryserver (keys(%spareid)) {
                    508: 	my $loadans=&reply('load',$tryserver);
                    509: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  510: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    511: 	    next; #didn't get a number from the server
                    512: 	}
                    513: 	my $answer;
                    514: 	if ($loadans =~ /\d/) {
                    515: 	    if ($userloadans =~ /\d/) {
                    516: 		#both are numbers, pick the bigger one
                    517: 		$answer=$loadans > $userloadans?
                    518: 		    $loadans :  $userloadans;
                    519: 	    } else {
                    520: 		$answer = $loadans;
                    521: 	    }
                    522: 	} else {
                    523: 	    $answer = $userloadans;
                    524: 	}
                    525: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  526: 	    if ($want_server_name) {
                    527: 		$spareserver=$tryserver;
                    528: 	    } else {
                    529: 		$spareserver="http://$hostname{$tryserver}";
                    530: 	    }
1.411     albertel  531: 	    $lowestserver=$answer;
                    532: 	}
1.370     albertel  533:     }
1.1       albertel  534:     return $spareserver;
1.202     matthew   535: }
                    536: 
                    537: # --------------------------------------------- Try to change a user's password
                    538: 
                    539: sub changepass {
                    540:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    541:     $currentpass = &escape($currentpass);
                    542:     $newpass     = &escape($newpass);
                    543:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    544: 		       $server);
                    545:     if (! $answer) {
                    546: 	&logthis("No reply on password change request to $server ".
                    547: 		 "by $uname in domain $udom.");
                    548:     } elsif ($answer =~ "^ok") {
                    549:         &logthis("$uname in $udom successfully changed their password ".
                    550: 		 "on $server.");
                    551:     } elsif ($answer =~ "^pwchange_failure") {
                    552: 	&logthis("$uname in $udom was unable to change their password ".
                    553: 		 "on $server.  The action was blocked by either lcpasswd ".
                    554: 		 "or pwchange");
                    555:     } elsif ($answer =~ "^non_authorized") {
                    556:         &logthis("$uname in $udom did not get their password correct when ".
                    557: 		 "attempting to change it on $server.");
                    558:     } elsif ($answer =~ "^auth_mode_error") {
                    559:         &logthis("$uname in $udom attempted to change their password despite ".
                    560: 		 "not being locally or internally authenticated on $server.");
                    561:     } elsif ($answer =~ "^unknown_user") {
                    562:         &logthis("$uname in $udom attempted to change their password ".
                    563: 		 "on $server but were unable to because $server is not ".
                    564: 		 "their home server.");
                    565:     } elsif ($answer =~ "^refused") {
                    566: 	&logthis("$server refused to change $uname in $udom password because ".
                    567: 		 "it was sent an unencrypted request to change the password.");
                    568:     }
                    569:     return $answer;
1.1       albertel  570: }
                    571: 
1.169     harris41  572: # ----------------------- Try to determine user's current authentication scheme
                    573: 
                    574: sub queryauthenticate {
                    575:     my ($uname,$udom)=@_;
1.456     albertel  576:     my $uhome=&homeserver($uname,$udom);
                    577:     if (!$uhome) {
                    578: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    579: 	return 'no_host';
                    580:     }
                    581:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    582:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    583: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  584:     }
1.456     albertel  585:     return $answer;
1.169     harris41  586: }
                    587: 
1.1       albertel  588: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       589: 
1.1       albertel  590: sub authenticate {
                    591:     my ($uname,$upass,$udom)=@_;
1.12      www       592:     $upass=escape($upass);
1.199     www       593:     $uname=~s/\W//g;
1.471     albertel  594:     my $uhome=&homeserver($uname,$udom);
                    595:     if (!$uhome) {
                    596: 	&logthis("User $uname at $udom is unknown in authenticate");
                    597: 	return 'no_host';
1.1       albertel  598:     }
1.471     albertel  599:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    600:     if ($answer eq 'authorized') {
                    601: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    602: 	return $uhome; 
                    603:     }
                    604:     if ($answer eq 'non_authorized') {
                    605: 	&logthis("User $uname at $udom rejected by $uhome");
                    606: 	return 'no_host'; 
1.9       www       607:     }
1.471     albertel  608:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  609:     return 'no_host';
                    610: }
                    611: 
                    612: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       613: 
1.599     albertel  614: my %homecache;
1.1       albertel  615: sub homeserver {
1.230     stredwic  616:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  617:     my $index="$uname:$udom";
1.426     albertel  618: 
1.599     albertel  619:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  620:     my $tryserver;
                    621:     foreach $tryserver (keys %libserv) {
1.230     stredwic  622:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  623: 		 exists($badServerCache{$tryserver}));
1.1       albertel  624: 	if ($hostdom{$tryserver} eq $udom) {
                    625:            my $answer=reply("home:$udom:$uname",$tryserver);
                    626:            if ($answer eq 'found') { 
1.599     albertel  627: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  628:            } elsif ($answer eq 'no_host') {
                    629: 	       $badServerCache{$tryserver}=1;
1.221     matthew   630:            }
1.1       albertel  631:        }
                    632:     }    
                    633:     return 'no_host';
1.70      www       634: }
                    635: 
                    636: # ------------------------------------- Find the usernames behind a list of IDs
                    637: 
                    638: sub idget {
                    639:     my ($udom,@ids)=@_;
                    640:     my %returnhash=();
                    641:     
                    642:     my $tryserver;
                    643:     foreach $tryserver (keys %libserv) {
                    644:        if ($hostdom{$tryserver} eq $udom) {
                    645: 	  my $idlist=join('&',@ids);
                    646:           $idlist=~tr/A-Z/a-z/; 
                    647: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    648:           my @answer=();
1.76      www       649:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       650: 	      @answer=split(/\&/,$reply);
                    651:           }                    ;
                    652:           my $i;
                    653:           for ($i=0;$i<=$#ids;$i++) {
                    654:               if ($answer[$i]) {
                    655: 		  $returnhash{$ids[$i]}=$answer[$i];
                    656:               } 
                    657:           }
                    658:        }
                    659:     }    
                    660:     return %returnhash;
                    661: }
                    662: 
                    663: # ------------------------------------- Find the IDs behind a list of usernames
                    664: 
                    665: sub idrget {
                    666:     my ($udom,@unames)=@_;
                    667:     my %returnhash=();
1.191     harris41  668:     foreach (@unames) {
1.70      www       669:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  670:     }
1.70      www       671:     return %returnhash;
                    672: }
                    673: 
                    674: # ------------------------------- Store away a list of names and associated IDs
                    675: 
                    676: sub idput {
                    677:     my ($udom,%ids)=@_;
                    678:     my %servers=();
1.191     harris41  679:     foreach (keys %ids) {
1.487     albertel  680: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       681:         my $uhom=&homeserver($_,$udom);
                    682:         if ($uhom ne 'no_host') {
                    683:             my $id=&escape($ids{$_});
                    684:             $id=~tr/A-Z/a-z/;
                    685:             my $unam=&escape($_);
                    686: 	    if ($servers{$uhom}) {
                    687: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    688:             } else {
                    689:                 $servers{$uhom}=$id.'='.$unam;
                    690:             }
                    691:         }
1.191     harris41  692:     }
                    693:     foreach (keys %servers) {
1.70      www       694:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  695:     }
1.344     www       696: }
                    697: 
                    698: # --------------------------------------------------- Assign a key to a student
                    699: 
                    700: sub assign_access_key {
1.364     www       701: #
                    702: # a valid key looks like uname:udom#comments
                    703: # comments are being appended
                    704: #
1.498     www       705:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    706:     $kdom=
1.620     albertel  707:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       708:     $knum=
1.620     albertel  709:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       710:     $cdom=
1.620     albertel  711:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       712:     $cnum=
1.620     albertel  713:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    714:     $udom=$env{'user.name'} unless (defined($udom));
                    715:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       716:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       717:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  718:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       719:                                                   # assigned to this person
                    720:                                                   # - this should not happen,
1.345     www       721:                                                   # unless something went wrong
                    722:                                                   # the first time around
                    723: # ready to assign
1.364     www       724:         $logentry=$1.'; '.$logentry;
1.496     www       725:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       726:                                                  $kdom,$knum) eq 'ok') {
1.345     www       727: # key now belongs to user
1.346     www       728: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       729:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    730:                 &appenv('environment.'.$envkey => $ckey);
                    731:                 return 'ok';
                    732:             } else {
                    733:                 return 
                    734:   'error: Count not permanently assign key, will need to be re-entered later.';
                    735: 	    }
                    736:         } else {
                    737:             return 'error: Could not assign key, try again later.';
                    738:         }
1.364     www       739:     } elsif (!$existing{$ckey}) {
1.345     www       740: # the key does not exist
                    741: 	return 'error: The key does not exist';
                    742:     } else {
                    743: # the key is somebody else's
                    744: 	return 'error: The key is already in use';
                    745:     }
1.344     www       746: }
                    747: 
1.364     www       748: # ------------------------------------------ put an additional comment on a key
                    749: 
                    750: sub comment_access_key {
                    751: #
                    752: # a valid key looks like uname:udom#comments
                    753: # comments are being appended
                    754: #
                    755:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    756:     $cdom=
1.620     albertel  757:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       758:     $cnum=
1.620     albertel  759:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       760:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    761:     if ($existing{$ckey}) {
                    762:         $existing{$ckey}.='; '.$logentry;
                    763: # ready to assign
1.367     www       764:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       765:                                                  $cdom,$cnum) eq 'ok') {
                    766: 	    return 'ok';
                    767:         } else {
                    768: 	    return 'error: Count not store comment.';
                    769:         }
                    770:     } else {
                    771: # the key does not exist
                    772: 	return 'error: The key does not exist';
                    773:     }
                    774: }
                    775: 
1.344     www       776: # ------------------------------------------------------ Generate a set of keys
                    777: 
                    778: sub generate_access_keys {
1.364     www       779:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       780:     $cdom=
1.620     albertel  781:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       782:     $cnum=
1.620     albertel  783:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       784:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       785:     unless (($cdom) && ($cnum)) { return 0; }
                    786:     if ($number>10000) { return 0; }
                    787:     sleep(2); # make sure don't get same seed twice
                    788:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    789:     my $total=0;
                    790:     for (my $i=1;$i<=$number;$i++) {
                    791:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    792:                   sprintf("%lx",int(100000*rand)).'-'.
                    793:                   sprintf("%lx",int(100000*rand));
                    794:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    795:        $newkey=~s/0/h/g; # and also 0 and O
                    796:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    797:        if ($existing{$newkey}) {
                    798:            $i--;
                    799:        } else {
1.364     www       800: 	  if (&put('accesskeys',
                    801:               { $newkey => '# generated '.localtime().
1.620     albertel  802:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       803:                            '; '.$logentry },
                    804: 		   $cdom,$cnum) eq 'ok') {
1.344     www       805:               $total++;
                    806: 	  }
                    807:        }
                    808:     }
1.620     albertel  809:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       810:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    811:     return $total;
                    812: }
                    813: 
                    814: # ------------------------------------------------------- Validate an accesskey
                    815: 
                    816: sub validate_access_key {
                    817:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    818:     $cdom=
1.620     albertel  819:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       820:     $cnum=
1.620     albertel  821:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    822:     $udom=$env{'user.domain'} unless (defined($udom));
                    823:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       824:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  825:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       826: }
                    827: 
                    828: # ------------------------------------- Find the section of student in a course
1.652     albertel  829: sub devalidate_getsection_cache {
                    830:     my ($udom,$unam,$courseid)=@_;
                    831:     $courseid=~s/\_/\//g;
                    832:     $courseid=~s/^(\w)/\/$1/;
                    833:     my $hashid="$udom:$unam:$courseid";
                    834:     &devalidate_cache_new('getsection',$hashid);
                    835: }
1.298     matthew   836: 
                    837: sub getsection {
                    838:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  839:     my $cachetime=1800;
1.298     matthew   840:     $courseid=~s/\_/\//g;
                    841:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  842: 
                    843:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  844:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  845:     if (defined($cached)) { return $result; }
                    846: 
1.298     matthew   847:     my %Pending; 
                    848:     my %Expired;
                    849:     #
                    850:     # Each role can either have not started yet (pending), be active, 
                    851:     #    or have expired.
                    852:     #
                    853:     # If there is an active role, we are done.
                    854:     #
                    855:     # If there is more than one role which has not started yet, 
                    856:     #     choose the one which will start sooner
                    857:     # If there is one role which has not started yet, return it.
                    858:     #
                    859:     # If there is more than one expired role, choose the one which ended last.
                    860:     # If there is a role which has expired, return it.
                    861:     #
                    862:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    863:                         &homeserver($unam,$udom)))) {
                    864:         my ($key,$value)=split(/\=/,$_);
                    865:         $key=&unescape($key);
1.479     albertel  866:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   867:         my $section=$1;
                    868:         if ($key eq $courseid.'_st') { $section=''; }
                    869:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    870:         my $now=time;
1.548     albertel  871:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   872:             $Expired{$end}=$section;
                    873:             next;
                    874:         }
1.548     albertel  875:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   876:             $Pending{$start}=$section;
                    877:             next;
                    878:         }
1.599     albertel  879:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   880:     }
                    881:     #
                    882:     # Presumedly there will be few matching roles from the above
                    883:     # loop and the sorting time will be negligible.
                    884:     if (scalar(keys(%Pending))) {
                    885:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  886:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   887:     } 
                    888:     if (scalar(keys(%Expired))) {
                    889:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    890:         my $time = pop(@sorted);
1.599     albertel  891:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   892:     }
1.599     albertel  893:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   894: }
1.70      www       895: 
1.599     albertel  896: sub save_cache {
                    897:     &purge_remembered();
1.722     albertel  898:     #&Apache::loncommon::validate_page();
1.620     albertel  899:     undef(%env);
1.780     albertel  900:     undef($env_loaded);
1.599     albertel  901: }
1.452     albertel  902: 
1.599     albertel  903: my $to_remember=-1;
                    904: my %remembered;
                    905: my %accessed;
                    906: my $kicks=0;
                    907: my $hits=0;
                    908: sub devalidate_cache_new {
                    909:     my ($name,$id,$debug) = @_;
                    910:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    911:     $id=&escape($name.':'.$id);
                    912:     $memcache->delete($id);
                    913:     delete($remembered{$id});
                    914:     delete($accessed{$id});
                    915: }
                    916: 
                    917: sub is_cached_new {
                    918:     my ($name,$id,$debug) = @_;
                    919:     $id=&escape($name.':'.$id);
                    920:     if (exists($remembered{$id})) {
                    921: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    922: 	$accessed{$id}=[&gettimeofday()];
                    923: 	$hits++;
                    924: 	return ($remembered{$id},1);
                    925:     }
                    926:     my $value = $memcache->get($id);
                    927:     if (!(defined($value))) {
                    928: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  929: 	return (undef,undef);
1.416     albertel  930:     }
1.599     albertel  931:     if ($value eq '__undef__') {
                    932: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    933: 	$value=undef;
                    934:     }
                    935:     &make_room($id,$value,$debug);
                    936:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    937:     return ($value,1);
                    938: }
                    939: 
                    940: sub do_cache_new {
                    941:     my ($name,$id,$value,$time,$debug) = @_;
                    942:     $id=&escape($name.':'.$id);
                    943:     my $setvalue=$value;
                    944:     if (!defined($setvalue)) {
                    945: 	$setvalue='__undef__';
                    946:     }
1.623     albertel  947:     if (!defined($time) ) {
                    948: 	$time=600;
                    949:     }
1.599     albertel  950:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  951:     $memcache->set($id,$setvalue,$time);
                    952:     # need to make a copy of $value
                    953:     #&make_room($id,$value,$debug);
1.599     albertel  954:     return $value;
                    955: }
                    956: 
                    957: sub make_room {
                    958:     my ($id,$value,$debug)=@_;
                    959:     $remembered{$id}=$value;
                    960:     if ($to_remember<0) { return; }
                    961:     $accessed{$id}=[&gettimeofday()];
                    962:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    963:     my $to_kick;
                    964:     my $max_time=0;
                    965:     foreach my $other (keys(%accessed)) {
                    966: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    967: 	    $to_kick=$other;
                    968: 	    $max_time=&tv_interval($accessed{$other});
                    969: 	}
                    970:     }
                    971:     delete($remembered{$to_kick});
                    972:     delete($accessed{$to_kick});
                    973:     $kicks++;
                    974:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  975:     return;
                    976: }
                    977: 
1.599     albertel  978: sub purge_remembered {
1.604     albertel  979:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    980:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  981:     undef(%remembered);
                    982:     undef(%accessed);
1.428     albertel  983: }
1.70      www       984: # ------------------------------------- Read an entry from a user's environment
                    985: 
                    986: sub userenvironment {
                    987:     my ($udom,$unam,@what)=@_;
                    988:     my %returnhash=();
                    989:     my @answer=split(/\&/,
                    990:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    991:                       &homeserver($unam,$udom)));
                    992:     my $i;
                    993:     for ($i=0;$i<=$#what;$i++) {
                    994: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    995:     }
                    996:     return %returnhash;
1.1       albertel  997: }
                    998: 
1.617     albertel  999: # ---------------------------------------------------------- Get a studentphoto
                   1000: sub studentphoto {
                   1001:     my ($udom,$unam,$ext) = @_;
                   1002:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1003:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1004:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1005:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1006:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1007:             } else {
                   1008:                 my ($result,$perm_reqd)=
1.707     albertel 1009: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1010:                 if ($result eq 'ok') {
                   1011:                     if (!($perm_reqd eq 'yes')) {
                   1012:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1013:                     }
                   1014:                 }
                   1015:             }
                   1016:         }
                   1017:     } else {
                   1018:         my ($result,$perm_reqd) = 
1.707     albertel 1019: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1020:         if ($result eq 'ok') {
                   1021:             if (!($perm_reqd eq 'yes')) {
                   1022:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1023:             }
                   1024:         }
                   1025:     }
                   1026:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1027: }
                   1028: 
                   1029: sub retrievestudentphoto {
                   1030:     my ($udom,$unam,$ext,$type) = @_;
                   1031:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1032:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1033:     if ($ret eq 'ok') {
                   1034:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1035:         if ($type eq 'thumbnail') {
                   1036:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1037:         }
                   1038:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1039:         return $tokenurl;
                   1040:     } else {
                   1041:         if ($type eq 'thumbnail') {
                   1042:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1043:         } else { 
                   1044:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1045:         }
1.617     albertel 1046:     }
                   1047: }
                   1048: 
1.263     www      1049: # -------------------------------------------------------------------- New chat
                   1050: 
                   1051: sub chatsend {
1.724     raeburn  1052:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1053:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1054:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1055:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1056:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1057: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1058: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1059: }
                   1060: 
                   1061: # ------------------------------------------ Find current version of a resource
                   1062: 
                   1063: sub getversion {
                   1064:     my $fname=&clutter(shift);
                   1065:     unless ($fname=~/^\/res\//) { return -1; }
                   1066:     return &currentversion(&filelocation('',$fname));
                   1067: }
                   1068: 
                   1069: sub currentversion {
                   1070:     my $fname=shift;
1.599     albertel 1071:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1072:     if (defined($cached)) { return $result; }
1.292     www      1073:     my $author=$fname;
                   1074:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1075:     my ($udom,$uname)=split(/\//,$author);
                   1076:     my $home=homeserver($uname,$udom);
                   1077:     if ($home eq 'no_host') { 
                   1078:         return -1; 
                   1079:     }
                   1080:     my $answer=reply("currentversion:$fname",$home);
                   1081:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1082: 	return -1;
                   1083:     }
1.599     albertel 1084:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1085: }
                   1086: 
1.1       albertel 1087: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1088: 
1.1       albertel 1089: sub subscribe {
                   1090:     my $fname=shift;
1.761     raeburn  1091:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1092:     $fname=~s/[\n\r]//g;
1.1       albertel 1093:     my $author=$fname;
                   1094:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1095:     my ($udom,$uname)=split(/\//,$author);
                   1096:     my $home=homeserver($uname,$udom);
1.335     albertel 1097:     if ($home eq 'no_host') {
                   1098:         return 'not_found';
1.1       albertel 1099:     }
                   1100:     my $answer=reply("sub:$fname",$home);
1.64      www      1101:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1102: 	$answer.=' by '.$home;
                   1103:     }
1.1       albertel 1104:     return $answer;
                   1105: }
                   1106:     
1.8       www      1107: # -------------------------------------------------------------- Replicate file
                   1108: 
                   1109: sub repcopy {
                   1110:     my $filename=shift;
1.23      www      1111:     $filename=~s/\/+/\//g;
1.607     raeburn  1112:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1113:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1114:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1115: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1116: 	return &repcopy_userfile($filename);
                   1117:     }
1.532     albertel 1118:     $filename=~s/[\n\r]//g;
1.8       www      1119:     my $transname="$filename.in.transfer";
1.607     raeburn  1120:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1121:     my $remoteurl=subscribe($filename);
1.64      www      1122:     if ($remoteurl =~ /^con_lost by/) {
                   1123: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1124:            return 'unavailable';
1.8       www      1125:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1126: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1127: 	   return 'not_found';
1.64      www      1128:     } elsif ($remoteurl =~ /^rejected by/) {
                   1129: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1130:            return 'forbidden';
1.20      www      1131:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1132:            return 'ok';
1.8       www      1133:     } else {
1.290     www      1134:         my $author=$filename;
                   1135:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1136:         my ($udom,$uname)=split(/\//,$author);
                   1137:         my $home=homeserver($uname,$udom);
                   1138:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1139:            my @parts=split(/\//,$filename);
                   1140:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1141:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1142:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1143: 	       return 'bad_request';
1.8       www      1144:            }
                   1145:            my $count;
                   1146:            for ($count=5;$count<$#parts;$count++) {
                   1147:                $path.="/$parts[$count]";
                   1148:                if ((-e $path)!=1) {
                   1149: 		   mkdir($path,0777);
                   1150:                }
                   1151:            }
                   1152:            my $ua=new LWP::UserAgent;
                   1153:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1154:            my $response=$ua->request($request,$transname);
                   1155:            if ($response->is_error()) {
                   1156: 	       unlink($transname);
                   1157:                my $message=$response->status_line;
1.672     albertel 1158:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1159:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1160:                return 'unavailable';
1.8       www      1161:            } else {
1.16      www      1162: 	       if ($remoteurl!~/\.meta$/) {
                   1163:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1164:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1165:                   if ($mresponse->is_error()) {
                   1166: 		      unlink($filename.'.meta');
                   1167:                       &logthis(
1.672     albertel 1168:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1169:                   }
                   1170: 	       }
1.8       www      1171:                rename($transname,$filename);
1.607     raeburn  1172:                return 'ok';
1.8       www      1173:            }
1.290     www      1174:        }
1.8       www      1175:     }
1.330     www      1176: }
                   1177: 
                   1178: # ------------------------------------------------ Get server side include body
                   1179: sub ssi_body {
1.381     albertel 1180:     my ($filelink,%form)=@_;
1.606     matthew  1181:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1182:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1183:     }
1.330     www      1184:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1185:                                      &ssi($filelink,%form));
1.778     albertel 1186:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1187:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1188:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1189:     return $output;
1.8       www      1190: }
                   1191: 
1.15      www      1192: # --------------------------------------------------------- Server Side Include
                   1193: 
1.782   ! albertel 1194: sub absolute_url {
        !          1195:     my ($host_name) = @_;
        !          1196:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
        !          1197:     if ($host_name eq '') {
        !          1198: 	$host_name = $ENV{'SERVER_NAME'};
        !          1199:     }
        !          1200:     return $protocol.$host_name;
        !          1201: }
        !          1202: 
1.15      www      1203: sub ssi {
                   1204: 
1.23      www      1205:     my ($fn,%form)=@_;
1.15      www      1206: 
                   1207:     my $ua=new LWP::UserAgent;
1.23      www      1208:     
                   1209:     my $request;
1.711     albertel 1210: 
                   1211:     $form{'no_update_last_known'}=1;
                   1212: 
1.23      www      1213:     if (%form) {
1.782   ! albertel 1214:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1215:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1216:     } else {
1.782   ! albertel 1217:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1218:     }
                   1219: 
1.15      www      1220:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1221:     my $response=$ua->request($request);
                   1222: 
1.324     www      1223:     return $response->content;
                   1224: }
                   1225: 
                   1226: sub externalssi {
                   1227:     my ($url)=@_;
                   1228:     my $ua=new LWP::UserAgent;
                   1229:     my $request=new HTTP::Request('GET',$url);
                   1230:     my $response=$ua->request($request);
1.15      www      1231:     return $response->content;
                   1232: }
1.254     www      1233: 
1.492     albertel 1234: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1235: 
                   1236: sub allowuploaded {
                   1237:     my ($srcurl,$url)=@_;
                   1238:     $url=&clutter(&declutter($url));
                   1239:     my $dir=$url;
                   1240:     $dir=~s/\/[^\/]+$//;
                   1241:     my %httpref=();
                   1242:     my $httpurl=&hreflocation('',$url);
                   1243:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1244:     &Apache::lonnet::appenv(%httpref);
1.254     www      1245: }
1.477     raeburn  1246: 
1.478     albertel 1247: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1248: # input: action, courseID, current domain, intended
1.637     raeburn  1249: #        path to file, source of file, instruction to parse file for objects,
                   1250: #        ref to hash for embedded objects,
                   1251: #        ref to hash for codebase of java objects.
                   1252: #
1.485     raeburn  1253: # output: url to file (if action was uploaddoc), 
                   1254: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1255: #
1.478     albertel 1256: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1257: # course.
1.477     raeburn  1258: #
1.478     albertel 1259: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1260: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1261: #          course's home server.
1.477     raeburn  1262: #
1.478     albertel 1263: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1264: #          be copied from $source (current location) to 
                   1265: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1266: #         and will then be copied to
                   1267: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1268: #         course's home server.
1.485     raeburn  1269: #
1.481     raeburn  1270: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1271: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1272: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1273: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1274: #         in course's home server.
1.637     raeburn  1275: #
1.477     raeburn  1276: 
                   1277: sub process_coursefile {
1.638     albertel 1278:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1279:     my $fetchresult;
1.638     albertel 1280:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1281:     if ($action eq 'propagate') {
1.638     albertel 1282:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1283: 			     $home);
1.481     raeburn  1284:     } else {
1.477     raeburn  1285:         my $fpath = '';
                   1286:         my $fname = $file;
1.478     albertel 1287:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1288:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1289:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1290:         if ($action eq 'copy') {
                   1291:             if ($source eq '') {
                   1292:                 $fetchresult = 'no source file';
                   1293:                 return $fetchresult;
                   1294:             } else {
                   1295:                 my $destination = $filepath.'/'.$fname;
                   1296:                 rename($source,$destination);
                   1297:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1298:                                  $home);
1.481     raeburn  1299:             }
                   1300:         } elsif ($action eq 'uploaddoc') {
                   1301:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1302:             print $fh $env{'form.'.$source};
1.481     raeburn  1303:             close($fh);
1.637     raeburn  1304:             if ($parser eq 'parse') {
                   1305:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1306:                 unless ($parse_result eq 'ok') {
                   1307:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1308:                 }
                   1309:             }
1.477     raeburn  1310:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1311:                                  $home);
1.481     raeburn  1312:             if ($fetchresult eq 'ok') {
                   1313:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1314:             } else {
                   1315:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1316:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1317:                 return '/adm/notfound.html';
                   1318:             }
1.477     raeburn  1319:         }
                   1320:     }
1.485     raeburn  1321:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1322:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1323:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1324:     }
                   1325:     return $fetchresult;
                   1326: }
                   1327: 
1.637     raeburn  1328: sub build_filepath {
                   1329:     my ($fpath) = @_;
                   1330:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1331:     unless ($fpath eq '') {
                   1332:         my @parts=split('/',$fpath);
                   1333:         foreach my $part (@parts) {
                   1334:             $filepath.= '/'.$part;
                   1335:             if ((-e $filepath)!=1) {
                   1336:                 mkdir($filepath,0777);
                   1337:             }
                   1338:         }
                   1339:     }
                   1340:     return $filepath;
                   1341: }
                   1342: 
                   1343: sub store_edited_file {
1.638     albertel 1344:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1345:     my $file = $primary_url;
                   1346:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1347:     my $fpath = '';
                   1348:     my $fname = $file;
                   1349:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1350:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1351:     my $filepath = &build_filepath($fpath);
                   1352:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1353:     print $fh $content;
                   1354:     close($fh);
1.638     albertel 1355:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1356:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1357: 			  $home);
1.637     raeburn  1358:     if ($$fetchresult eq 'ok') {
                   1359:         return '/uploaded/'.$fpath.'/'.$fname;
                   1360:     } else {
1.638     albertel 1361:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1362: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1363:         return '/adm/notfound.html';
                   1364:     }
                   1365: }
                   1366: 
1.531     albertel 1367: sub clean_filename {
                   1368:     my ($fname)=@_;
1.315     www      1369: # Replace Windows backslashes by forward slashes
1.257     www      1370:     $fname=~s/\\/\//g;
1.315     www      1371: # Get rid of everything but the actual filename
1.257     www      1372:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1373: # Replace spaces by underscores
                   1374:     $fname=~s/\s+/\_/g;
                   1375: # Replace all other weird characters by nothing
1.317     www      1376:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1377: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1378: # numbers
                   1379:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1380:     return $fname;
                   1381: }
                   1382: 
1.608     albertel 1383: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1384: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1385: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1386: #        $coursedoc - if true up to the current course
                   1387: #                     if false
                   1388: #        $subdir - directory in userfile to store the file into
                   1389: #        $parser, $allfiles, $codebase - unknown
                   1390: #
                   1391: # output: url of file in userspace, or error: <message> 
                   1392: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1393: 
                   1394: 
1.531     albertel 1395: sub userfileupload {
1.719     banghart 1396:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1397:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1398:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1399:     $fname=&clean_filename($fname);
1.315     www      1400: # See if there is anything left
1.257     www      1401:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1402:     chop($env{'form.'.$formname});
1.523     raeburn  1403:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1404:         my $now = time;
                   1405:         my $filepath = 'tmp/helprequests/'.$now;
                   1406:         my @parts=split(/\//,$filepath);
                   1407:         my $fullpath = $perlvar{'lonDaemons'};
                   1408:         for (my $i=0;$i<@parts;$i++) {
                   1409:             $fullpath .= '/'.$parts[$i];
                   1410:             if ((-e $fullpath)!=1) {
                   1411:                 mkdir($fullpath,0777);
                   1412:             }
                   1413:         }
                   1414:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1415:         print $fh $env{'form.'.$formname};
1.523     raeburn  1416:         close($fh);
1.741     raeburn  1417:         return $fullpath.'/'.$fname;
                   1418:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1419:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1420:                        '_'.$env{'user.domain'}.'/pending';
                   1421:         my @parts=split(/\//,$filepath);
                   1422:         my $fullpath = $perlvar{'lonDaemons'};
                   1423:         for (my $i=0;$i<@parts;$i++) {
                   1424:             $fullpath .= '/'.$parts[$i];
                   1425:             if ((-e $fullpath)!=1) {
                   1426:                 mkdir($fullpath,0777);
                   1427:             }
                   1428:         }
                   1429:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1430:         print $fh $env{'form.'.$formname};
                   1431:         close($fh);
                   1432:         return $fullpath.'/'.$fname;
1.523     raeburn  1433:     }
1.719     banghart 1434:     
1.258     www      1435: # Create the directory if not present
1.493     albertel 1436:     $fname="$subdir/$fname";
1.259     www      1437:     if ($coursedoc) {
1.638     albertel 1438: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1439: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1440:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1441:             return &finishuserfileupload($docuname,$docudom,
                   1442: 					 $formname,$fname,$parser,$allfiles,
                   1443: 					 $codebase);
1.481     raeburn  1444:         } else {
1.620     albertel 1445:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1446:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1447: 				       $fname,$formname,$parser,
                   1448: 				       $allfiles,$codebase);
1.481     raeburn  1449:         }
1.719     banghart 1450:     } elsif (defined($destuname)) {
                   1451:         my $docuname=$destuname;
                   1452:         my $docudom=$destudom;
                   1453: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1454: 				     $fname,$parser,$allfiles,$codebase);
                   1455:         
1.259     www      1456:     } else {
1.638     albertel 1457:         my $docuname=$env{'user.name'};
                   1458:         my $docudom=$env{'user.domain'};
1.714     raeburn  1459:         if (exists($env{'form.group'})) {
                   1460:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1461:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1462:         }
1.638     albertel 1463: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1464: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1465:     }
1.271     www      1466: }
                   1467: 
                   1468: sub finishuserfileupload {
1.638     albertel 1469:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1470:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1471:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1472:     my ($fnamepath,$file);
                   1473:     $file=$fname;
                   1474:     if ($fname=~m|/|) {
                   1475:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1476: 	$path.=$fnamepath.'/';
                   1477:     }
1.259     www      1478:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1479:     my $count;
                   1480:     for ($count=4;$count<=$#parts;$count++) {
                   1481:         $filepath.="/$parts[$count]";
                   1482:         if ((-e $filepath)!=1) {
                   1483: 	    mkdir($filepath,0777);
                   1484:         }
                   1485:     }
                   1486: # Save the file
                   1487:     {
1.701     albertel 1488: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1489: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1490: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1491: 	    return '/adm/notfound.html';
                   1492: 	}
                   1493: 	if (!print FH ($env{'form.'.$formname})) {
                   1494: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1495: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1496: 	    return '/adm/notfound.html';
                   1497: 	}
1.570     albertel 1498: 	close(FH);
1.258     www      1499:     }
1.637     raeburn  1500:     if ($parser eq 'parse') {
1.638     albertel 1501:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1502: 						   $codebase);
1.637     raeburn  1503:         unless ($parse_result eq 'ok') {
1.638     albertel 1504:             &logthis('Failed to parse '.$filepath.$file.
                   1505: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1506:         }
                   1507:     }
1.259     www      1508: # Notify homeserver to grep it
                   1509: #
1.638     albertel 1510:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1511:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1512:     if ($fetchresult eq 'ok') {
1.259     www      1513: #
1.258     www      1514: # Return the URL to it
1.494     albertel 1515:         return '/uploaded/'.$path.$file;
1.263     www      1516:     } else {
1.494     albertel 1517:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1518: 		 ': '.$fetchresult);
1.263     www      1519:         return '/adm/notfound.html';
                   1520:     }    
1.493     albertel 1521: }
                   1522: 
1.637     raeburn  1523: sub extract_embedded_items {
1.648     raeburn  1524:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1525:     my @state = ();
                   1526:     my %javafiles = (
                   1527:                       codebase => '',
                   1528:                       code => '',
                   1529:                       archive => ''
                   1530:                     );
                   1531:     my %mediafiles = (
                   1532:                       src => '',
                   1533:                       movie => '',
                   1534:                      );
1.648     raeburn  1535:     my $p;
                   1536:     if ($content) {
                   1537:         $p = HTML::LCParser->new($content);
                   1538:     } else {
                   1539:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1540:     }
1.641     albertel 1541:     while (my $t=$p->get_token()) {
1.640     albertel 1542: 	if ($t->[0] eq 'S') {
                   1543: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1544: 	    push (@state, $tagname);
1.648     raeburn  1545:             if (lc($tagname) eq 'allow') {
                   1546:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1547:             }
1.640     albertel 1548: 	    if (lc($tagname) eq 'img') {
                   1549: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1550: 	    }
1.645     raeburn  1551:             if (lc($tagname) eq 'script') {
                   1552:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1553:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1554:                 } else {
                   1555:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1556:                 }
                   1557:             }
                   1558:             if (lc($tagname) eq 'link') {
                   1559:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1560:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1561:                 }
                   1562:             }
1.640     albertel 1563: 	    if (lc($tagname) eq 'object' ||
                   1564: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1565: 		foreach my $item (keys(%javafiles)) {
                   1566: 		    $javafiles{$item} = '';
                   1567: 		}
                   1568: 	    }
                   1569: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1570: 		my $name = lc($attr->{'name'});
                   1571: 		foreach my $item (keys(%javafiles)) {
                   1572: 		    if ($name eq $item) {
                   1573: 			$javafiles{$item} = $attr->{'value'};
                   1574: 			last;
                   1575: 		    }
                   1576: 		}
                   1577: 		foreach my $item (keys(%mediafiles)) {
                   1578: 		    if ($name eq $item) {
                   1579: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1580: 			last;
                   1581: 		    }
                   1582: 		}
                   1583: 	    }
                   1584: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1585: 		foreach my $item (keys(%javafiles)) {
                   1586: 		    if ($attr->{$item}) {
                   1587: 			$javafiles{$item} = $attr->{$item};
                   1588: 			last;
                   1589: 		    }
                   1590: 		}
                   1591: 		foreach my $item (keys(%mediafiles)) {
                   1592: 		    if ($attr->{$item}) {
                   1593: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1594: 			last;
                   1595: 		    }
                   1596: 		}
                   1597: 	    }
                   1598: 	} elsif ($t->[0] eq 'E') {
                   1599: 	    my ($tagname) = ($t->[1]);
                   1600: 	    if ($javafiles{'codebase'} ne '') {
                   1601: 		$javafiles{'codebase'} .= '/';
                   1602: 	    }  
                   1603: 	    if (lc($tagname) eq 'applet' ||
                   1604: 		lc($tagname) eq 'object' ||
                   1605: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1606: 		) {
                   1607: 		foreach my $item (keys(%javafiles)) {
                   1608: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1609: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1610: 			&add_filetype($allfiles,$file,$item);
                   1611: 		    }
                   1612: 		}
                   1613: 	    } 
                   1614: 	    pop @state;
                   1615: 	}
                   1616:     }
1.637     raeburn  1617:     return 'ok';
                   1618: }
                   1619: 
1.639     albertel 1620: sub add_filetype {
                   1621:     my ($allfiles,$file,$type)=@_;
                   1622:     if (exists($allfiles->{$file})) {
                   1623: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1624: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1625: 	}
                   1626:     } else {
                   1627: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1628:     }
                   1629: }
                   1630: 
1.493     albertel 1631: sub removeuploadedurl {
                   1632:     my ($url)=@_;
                   1633:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1634:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1635: }
                   1636: 
                   1637: sub removeuserfile {
                   1638:     my ($docuname,$docudom,$fname)=@_;
                   1639:     my $home=&homeserver($docuname,$docudom);
                   1640:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1641: }
1.15      www      1642: 
1.530     albertel 1643: sub mkdiruserfile {
                   1644:     my ($docuname,$docudom,$dir)=@_;
                   1645:     my $home=&homeserver($docuname,$docudom);
                   1646:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1647: }
                   1648: 
1.531     albertel 1649: sub renameuserfile {
                   1650:     my ($docuname,$docudom,$old,$new)=@_;
                   1651:     my $home=&homeserver($docuname,$docudom);
                   1652:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1653: 		  &escape("$new"),$home);
                   1654: }
                   1655: 
1.14      www      1656: # ------------------------------------------------------------------------- Log
                   1657: 
                   1658: sub log {
                   1659:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1660:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1661: }
                   1662: 
                   1663: # ------------------------------------------------------------------ Course Log
1.352     www      1664: #
                   1665: # This routine flushes several buffers of non-mission-critical nature
                   1666: #
1.157     www      1667: 
                   1668: sub flushcourselogs {
1.352     www      1669:     &logthis('Flushing log buffers');
                   1670: #
                   1671: # course logs
                   1672: # This is a log of all transactions in a course, which can be used
                   1673: # for data mining purposes
                   1674: #
                   1675: # It also collects the courseid database, which lists last transaction
                   1676: # times and course titles for all courseids
                   1677: #
                   1678:     my %courseidbuffer=();
1.191     harris41 1679:     foreach (keys %courselogs) {
1.157     www      1680:         my $crsid=$_;
1.352     www      1681:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1682: 		          &escape($courselogs{$crsid}),
                   1683: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1684: 	    delete $courselogs{$crsid};
                   1685:         } else {
                   1686:             &logthis('Failed to flush log buffer for '.$crsid);
                   1687:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1688:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1689:                         " exceeded maximum size, deleting.</font>");
                   1690:                delete $courselogs{$crsid};
                   1691:             }
1.352     www      1692:         }
                   1693:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1694:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1695: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1696:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1697:         } else {
                   1698:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1699: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1700:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1701:         }
1.191     harris41 1702:     }
1.352     www      1703: #
                   1704: # Write course id database (reverse lookup) to homeserver of courses 
                   1705: # Is used in pickcourse
                   1706: #
                   1707:     foreach (keys %courseidbuffer) {
1.353     www      1708:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1709:     }
                   1710: #
                   1711: # File accesses
                   1712: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1713: #
1.449     matthew  1714:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1715:         if ($entry =~ /___count$/) {
                   1716:             my ($dom,$name);
                   1717:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1718:             if (! defined($dom) || $dom eq '' || 
                   1719:                 ! defined($name) || $name eq '') {
1.620     albertel 1720:                 my $cid = $env{'request.course.id'};
                   1721:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1722:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1723:             }
1.450     matthew  1724:             my $value = $accesshash{$entry};
                   1725:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1726:             my %temphash=($url => $value);
1.449     matthew  1727:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1728:             if ($result eq 'ok') {
                   1729:                 delete $accesshash{$entry};
                   1730:             } elsif ($result eq 'unknown_cmd') {
                   1731:                 # Target server has old code running on it.
1.450     matthew  1732:                 my %temphash=($entry => $value);
1.449     matthew  1733:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1734:                     delete $accesshash{$entry};
                   1735:                 }
                   1736:             }
                   1737:         } else {
1.458     matthew  1738:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1739:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1740:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1741:                 delete $accesshash{$entry};
                   1742:             }
1.185     www      1743:         }
1.191     harris41 1744:     }
1.352     www      1745: #
                   1746: # Roles
                   1747: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1748: #
1.349     www      1749:     foreach (keys %userrolehash) {
                   1750:         my $entry=$_;
1.351     www      1751:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1752: 	    split(/\:/,$entry);
                   1753:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1754:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1755:                 $rudom,$runame) eq 'ok') {
                   1756: 	    delete $userrolehash{$entry};
                   1757:         }
                   1758:     }
1.662     raeburn  1759: #
                   1760: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1761: #
                   1762:     my %domrolebuffer = ();
                   1763:     foreach my $entry (keys %domainrolehash) {
                   1764:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1765:         if ($domrolebuffer{$rudom}) {
                   1766:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1767:                       '='.&escape($domainrolehash{$entry});
                   1768:         } else {
                   1769:             $domrolebuffer{$rudom}.=&escape($entry).
                   1770:                       '='.&escape($domainrolehash{$entry});
                   1771:         }
                   1772:         delete $domainrolehash{$entry};
                   1773:     }
                   1774:     foreach my $dom (keys(%domrolebuffer)) {
                   1775:         foreach my $tryserver (keys %libserv) {
                   1776:             if ($hostdom{$tryserver} eq $dom) {
                   1777:                 unless (&reply('domroleput:'.$dom.':'.
                   1778:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1779:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1780:                 }
                   1781:             }
                   1782:         }
                   1783:     }
1.186     www      1784:     $dumpcount++;
1.157     www      1785: }
                   1786: 
                   1787: sub courselog {
                   1788:     my $what=shift;
1.158     www      1789:     $what=time.':'.$what;
1.620     albertel 1790:     unless ($env{'request.course.id'}) { return ''; }
                   1791:     $coursedombuf{$env{'request.course.id'}}=
                   1792:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1793:     $coursenumbuf{$env{'request.course.id'}}=
                   1794:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1795:     $coursehombuf{$env{'request.course.id'}}=
                   1796:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1797:     $coursedescrbuf{$env{'request.course.id'}}=
                   1798:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1799:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1800:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1801:     $courseownerbuf{$env{'request.course.id'}}=
                   1802:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1803:     $coursetypebuf{$env{'request.course.id'}}=
                   1804:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1805:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1806: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1807:     } else {
1.620     albertel 1808: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1809:     }
1.620     albertel 1810:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1811: 	&flushcourselogs();
                   1812:     }
1.158     www      1813: }
                   1814: 
                   1815: sub courseacclog {
                   1816:     my $fnsymb=shift;
1.620     albertel 1817:     unless ($env{'request.course.id'}) { return ''; }
                   1818:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1819:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1820:         $what.=':POST';
1.583     matthew  1821:         # FIXME: Probably ought to escape things....
1.620     albertel 1822: 	foreach (keys %env) {
1.158     www      1823:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1824: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1825:             }
1.191     harris41 1826:         }
1.583     matthew  1827:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1828:         # FIXME: We should not be depending on a form parameter that someone
                   1829:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1830:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1831:             $what.= ':POST';
                   1832:             # FIXME: Probably ought to escape things....
                   1833:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1834:                                  'crsdiscuss') {
1.620     albertel 1835:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1836:             }
                   1837:         }
1.158     www      1838:     }
                   1839:     &courselog($what);
1.149     www      1840: }
                   1841: 
1.185     www      1842: sub countacc {
                   1843:     my $url=&declutter(shift);
1.458     matthew  1844:     return if (! defined($url) || $url eq '');
1.620     albertel 1845:     unless ($env{'request.course.id'}) { return ''; }
                   1846:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1847:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1848:     $accesshash{$key}++;
1.185     www      1849: }
1.349     www      1850: 
1.361     www      1851: sub linklog {
                   1852:     my ($from,$to)=@_;
                   1853:     $from=&declutter($from);
                   1854:     $to=&declutter($to);
                   1855:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1856:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1857: }
                   1858:   
1.349     www      1859: sub userrolelog {
                   1860:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1861:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1862:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1863:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1864:         ($trole=~/^ta/)) {
1.350     www      1865:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1866:        $userrolehash
                   1867:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1868:                     =$tend.':'.$tstart;
1.662     raeburn  1869:     }
                   1870:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1871:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1872:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1873:         ($trole=~/^sc/)) {
                   1874:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1875:        $domainrolehash
                   1876:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1877:                     = $tend.':'.$tstart;
                   1878:     }
1.351     www      1879: }
                   1880: 
                   1881: sub get_course_adv_roles {
                   1882:     my $cid=shift;
1.620     albertel 1883:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1884:     my %coursehash=&coursedescription($cid);
1.470     www      1885:     my %nothide=();
                   1886:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1887: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1888:     }
1.351     www      1889:     my %returnhash=();
                   1890:     my %dumphash=
                   1891:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1892:     my $now=time;
                   1893:     foreach (keys %dumphash) {
                   1894: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1895:         if (($tstart) && ($tstart<0)) { next; }
                   1896:         if (($tend) && ($tend<$now)) { next; }
                   1897:         if (($tstart) && ($now<$tstart)) { next; }
                   1898:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1899: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1900: 	if ((&privileged($username,$domain)) && 
                   1901: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1902: 	if ($role eq 'cr') { next; }
1.351     www      1903:         my $key=&plaintext($role);
                   1904:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1905:         if ($returnhash{$key}) {
                   1906: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1907:         } else {
                   1908:             $returnhash{$key}=$username.':'.$domain;
                   1909:         }
1.400     www      1910:      }
                   1911:     return %returnhash;
                   1912: }
                   1913: 
                   1914: sub get_my_roles {
                   1915:     my ($uname,$udom)=@_;
1.620     albertel 1916:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1917:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1918:     my %dumphash=
                   1919:             &dump('nohist_userroles',$udom,$uname);
                   1920:     my %returnhash=();
                   1921:     my $now=time;
                   1922:     foreach (keys %dumphash) {
                   1923: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1924:         if (($tstart) && ($tstart<0)) { next; }
                   1925:         if (($tend) && ($tend<$now)) { next; }
                   1926:         if (($tstart) && ($now<$tstart)) { next; }
                   1927:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1928: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1929:      }
                   1930:     return %returnhash;
1.399     www      1931: }
                   1932: 
                   1933: # ----------------------------------------------------- Frontpage Announcements
                   1934: #
                   1935: #
                   1936: 
                   1937: sub postannounce {
                   1938:     my ($server,$text)=@_;
                   1939:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1940:     unless ($text=~/\w/) { $text=''; }
                   1941:     return &reply('setannounce:'.&escape($text),$server);
                   1942: }
                   1943: 
                   1944: sub getannounce {
1.448     albertel 1945: 
                   1946:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1947: 	my $announcement='';
                   1948: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1949: 	close($fh);
1.399     www      1950: 	if ($announcement=~/\w/) { 
                   1951: 	    return 
                   1952:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1953:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1954: 	} else {
                   1955: 	    return '';
                   1956: 	}
                   1957:     } else {
                   1958: 	return '';
                   1959:     }
1.351     www      1960: }
1.353     www      1961: 
                   1962: # ---------------------------------------------------------- Course ID routines
                   1963: # Deal with domain's nohist_courseid.db files
                   1964: #
                   1965: 
                   1966: sub courseidput {
                   1967:     my ($domain,$what,$coursehome)=@_;
                   1968:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1969: }
                   1970: 
                   1971: sub courseiddump {
1.741     raeburn  1972:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1973:     my %returnhash=();
1.355     www      1974:     unless ($domfilter) { $domfilter=''; }
1.353     www      1975:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1976:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1977: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1978: 	        foreach (
                   1979:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1980: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1981:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1982:                                $tryserver))) {
1.506     raeburn  1983: 		    my ($key,$value)=split(/\=/,$_);
                   1984:                     if (($key) && ($value)) {
1.516     raeburn  1985: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1986:                     }
1.353     www      1987:                 }
                   1988:             }
                   1989:         }
                   1990:     }
                   1991:     return %returnhash;
                   1992: }
                   1993: 
1.658     raeburn  1994: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1995: 
                   1996: sub dcmailput {
1.685     raeburn  1997:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1998:     my $status = &Apache::lonnet::critical(
1.740     www      1999:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2000:        &escape($message),$server);
1.662     raeburn  2001:     return $status;
                   2002: }
                   2003: 
1.658     raeburn  2004: sub dcmaildump {
                   2005:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2006:     my %returnhash=();
                   2007:     if (exists($domain_primary{$dom})) {
                   2008:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2009:                                                          &escape($enddate).':';
                   2010: 	my @esc_senders=map { &escape($_)} @$senders;
                   2011: 	$cmd.=&escape(join('&',@esc_senders));
                   2012: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2013:             my ($key,$value) = split(/\=/,$_);
                   2014:             if (($key) && ($value)) {
                   2015:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2016:             }
                   2017:         }
                   2018:     }
                   2019:     return %returnhash;
                   2020: }
1.662     raeburn  2021: # ---------------------------------------------------------- Domain roles
                   2022: 
                   2023: sub get_domain_roles {
                   2024:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2025:     if (undef($startdate) || $startdate eq '') {
                   2026:         $startdate = '.';
                   2027:     }
                   2028:     if (undef($enddate) || $enddate eq '') {
                   2029:         $enddate = '.';
                   2030:     }
                   2031:     my $rolelist = join(':',@{$roles});
                   2032:     my %personnel = ();
                   2033:     foreach my $tryserver (keys(%libserv)) {
                   2034:         if ($hostdom{$tryserver} eq $dom) {
                   2035:             %{$personnel{$tryserver}}=();
                   2036:             foreach (
                   2037:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2038:                    &escape($startdate).':'.&escape($enddate).':'.
                   2039:                    &escape($rolelist), $tryserver))) {
                   2040:                 my($key,$value) = split(/\=/,$_);
                   2041:                 if (($key) && ($value)) {
                   2042:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2043:                 }
                   2044:             }
                   2045:         }
                   2046:     }
                   2047:     return %personnel;
                   2048: }
1.658     raeburn  2049: 
1.149     www      2050: # ----------------------------------------------------------- Check out an item
                   2051: 
1.504     albertel 2052: sub get_first_access {
                   2053:     my ($type,$argsymb)=@_;
                   2054:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2055:     if ($argsymb) { $symb=$argsymb; }
                   2056:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2057:     if ($type eq 'map') {
                   2058: 	$res=&symbread($map);
                   2059:     } else {
                   2060: 	$res=$symb;
                   2061:     }
                   2062:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2063:     return $times{"$courseid\0$res"};
1.504     albertel 2064: }
                   2065: 
                   2066: sub set_first_access {
                   2067:     my ($type)=@_;
                   2068:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2069:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2070:     if ($type eq 'map') {
                   2071: 	$res=&symbread($map);
                   2072:     } else {
                   2073: 	$res=$symb;
                   2074:     }
                   2075:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2076:     if (!$firstaccess) {
1.588     albertel 2077: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2078:     }
                   2079:     return 'already_set';
1.504     albertel 2080: }
                   2081: 
1.149     www      2082: sub checkout {
                   2083:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2084:     my $now=time;
                   2085:     my $lonhost=$perlvar{'lonHostID'};
                   2086:     my $infostr=&escape(
1.234     www      2087:                  'CHECKOUTTOKEN&'.
1.149     www      2088:                  $tuname.'&'.
                   2089:                  $tudom.'&'.
                   2090:                  $tcrsid.'&'.
                   2091:                  $symb.'&'.
                   2092: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2093:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2094:     if ($token=~/^error\:/) { 
1.672     albertel 2095:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2096:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2097:                  "</font>");
                   2098:         return ''; 
                   2099:     }
                   2100: 
1.149     www      2101:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2102:     $token=~tr/a-z/A-Z/;
                   2103: 
1.153     www      2104:     my %infohash=('resource.0.outtoken' => $token,
                   2105:                   'resource.0.checkouttime' => $now,
                   2106:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2107: 
                   2108:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2109:        return '';
1.151     www      2110:     } else {
1.672     albertel 2111:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2112:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2113:                  "</font>");
1.149     www      2114:     }    
                   2115: 
                   2116:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2117:                          &escape('Checkout '.$infostr.' - '.
                   2118:                                                  $token)) ne 'ok') {
                   2119: 	return '';
1.151     www      2120:     } else {
1.672     albertel 2121:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2122:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2123:                  "</font>");
1.149     www      2124:     }
1.151     www      2125:     return $token;
1.149     www      2126: }
                   2127: 
                   2128: # ------------------------------------------------------------ Check in an item
                   2129: 
                   2130: sub checkin {
                   2131:     my $token=shift;
1.150     www      2132:     my $now=time;
                   2133:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2134:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2135:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2136:     $dtoken=~s/\W/\_/g;
1.234     www      2137:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2138:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2139: 
1.154     www      2140:     unless (($tuname) && ($tudom)) {
                   2141:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2142:         return '';
                   2143:     }
                   2144:     
                   2145:     unless (&allowed('mgr',$tcrsid)) {
                   2146:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2147:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2148:         return '';
                   2149:     }
                   2150: 
1.153     www      2151:     my %infohash=('resource.0.intoken' => $token,
                   2152:                   'resource.0.checkintime' => $now,
                   2153:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2154: 
                   2155:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2156:        return '';
                   2157:     }    
                   2158: 
                   2159:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2160:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2161: 	return '';
                   2162:     }
                   2163: 
                   2164:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2165: }
                   2166: 
                   2167: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2168: 
                   2169: sub expirespread {
                   2170:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2171:     my $cid=$env{'request.course.id'}; 
1.110     www      2172:     if ($cid) {
                   2173:        my $now=time;
                   2174:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2175:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2176:                             $env{'course.'.$cid.'.num'}.
1.110     www      2177: 	        	    ':nohist_expirationdates:'.
                   2178:                             &escape($key).'='.$now,
1.620     albertel 2179:                             $env{'course.'.$cid.'.home'})
1.110     www      2180:     }
                   2181:     return 'ok';
1.14      www      2182: }
                   2183: 
1.109     www      2184: # ----------------------------------------------------- Devalidate Spreadsheets
                   2185: 
                   2186: sub devalidate {
1.325     www      2187:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2188:     my $cid=$env{'request.course.id'}; 
1.109     www      2189:     if ($cid) {
1.391     matthew  2190:         # delete the stored spreadsheets for
                   2191:         # - the student level sheet of this user in course's homespace
                   2192:         # - the assessment level sheet for this resource 
                   2193:         #   for this user in user's homespace
1.553     albertel 2194: 	# - current conditional state info
1.325     www      2195: 	my $key=$uname.':'.$udom.':';
1.109     www      2196:         my $status=
1.299     matthew  2197: 	    &del('nohist_calculatedsheets',
1.391     matthew  2198: 		 [$key.'studentcalc:'],
1.620     albertel 2199: 		 $env{'course.'.$cid.'.domain'},
                   2200: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2201: 		.' '.
                   2202: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2203: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2204:         unless ($status eq 'ok ok') {
                   2205:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2206:                     $uname.' at '.$udom.' for '.
1.109     www      2207: 		    $symb.': '.$status);
1.133     albertel 2208:         }
1.553     albertel 2209: 	&delenv('user.state.'.$cid);
1.109     www      2210:     }
                   2211: }
                   2212: 
1.265     albertel 2213: sub get_scalar {
                   2214:     my ($string,$end) = @_;
                   2215:     my $value;
                   2216:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2217: 	$value = $1;
                   2218:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2219: 	$value = $1;
                   2220:     }
                   2221:     return &unescape($value);
                   2222: }
                   2223: 
                   2224: sub array2str {
                   2225:   my (@array) = @_;
                   2226:   my $result=&arrayref2str(\@array);
                   2227:   $result=~s/^__ARRAY_REF__//;
                   2228:   $result=~s/__END_ARRAY_REF__$//;
                   2229:   return $result;
                   2230: }
                   2231: 
1.204     albertel 2232: sub arrayref2str {
                   2233:   my ($arrayref) = @_;
1.265     albertel 2234:   my $result='__ARRAY_REF__';
1.204     albertel 2235:   foreach my $elem (@$arrayref) {
1.265     albertel 2236:     if(ref($elem) eq 'ARRAY') {
                   2237:       $result.=&arrayref2str($elem).'&';
                   2238:     } elsif(ref($elem) eq 'HASH') {
                   2239:       $result.=&hashref2str($elem).'&';
                   2240:     } elsif(ref($elem)) {
                   2241:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2242:     } else {
                   2243:       $result.=&escape($elem).'&';
                   2244:     }
                   2245:   }
                   2246:   $result=~s/\&$//;
1.265     albertel 2247:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2248:   return $result;
                   2249: }
                   2250: 
1.168     albertel 2251: sub hash2str {
1.204     albertel 2252:   my (%hash) = @_;
                   2253:   my $result=&hashref2str(\%hash);
1.265     albertel 2254:   $result=~s/^__HASH_REF__//;
                   2255:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2256:   return $result;
                   2257: }
                   2258: 
                   2259: sub hashref2str {
                   2260:   my ($hashref)=@_;
1.265     albertel 2261:   my $result='__HASH_REF__';
1.495     albertel 2262:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2263:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2264:       $result.=&arrayref2str($_).'=';
1.204     albertel 2265:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2266:       $result.=&hashref2str($_).'=';
1.204     albertel 2267:     } elsif (ref($_)) {
1.265     albertel 2268:       $result.='=';
                   2269:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2270:     } else {
1.265     albertel 2271: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2272:     }
                   2273: 
1.265     albertel 2274:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2275:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2276:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2277:       $result.=&hashref2str($hashref->{$_}).'&';
                   2278:     } elsif(ref($hashref->{$_})) {
                   2279:        $result.='&';
                   2280:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2281:     } else {
1.265     albertel 2282:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2283:     }
                   2284:   }
1.168     albertel 2285:   $result=~s/\&$//;
1.265     albertel 2286:   $result .= '__END_HASH_REF__';
1.168     albertel 2287:   return $result;
                   2288: }
                   2289: 
                   2290: sub str2hash {
1.265     albertel 2291:     my ($string)=@_;
                   2292:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2293:     return %$hash;
                   2294: }
                   2295: 
                   2296: sub str2hashref {
1.168     albertel 2297:   my ($string) = @_;
1.265     albertel 2298: 
                   2299:   my %hash;
                   2300: 
                   2301:   if($string !~ /^__HASH_REF__/) {
                   2302:       if (! ($string eq '' || !defined($string))) {
                   2303: 	  $hash{'error'}='Not hash reference';
                   2304:       }
                   2305:       return (\%hash, $string);
                   2306:   }
                   2307: 
                   2308:   $string =~ s/^__HASH_REF__//;
                   2309: 
                   2310:   while($string !~ /^__END_HASH_REF__/) {
                   2311:       #key
                   2312:       my $key='';
                   2313:       if($string =~ /^__HASH_REF__/) {
                   2314:           ($key, $string)=&str2hashref($string);
                   2315:           if(defined($key->{'error'})) {
                   2316:               $hash{'error'}='Bad data';
                   2317:               return (\%hash, $string);
                   2318:           }
                   2319:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2320:           ($key, $string)=&str2arrayref($string);
                   2321:           if($key->[0] eq 'Array reference error') {
                   2322:               $hash{'error'}='Bad data';
                   2323:               return (\%hash, $string);
                   2324:           }
                   2325:       } else {
                   2326:           $string =~ s/^(.*?)=//;
1.267     albertel 2327: 	  $key=&unescape($1);
1.265     albertel 2328:       }
                   2329:       $string =~ s/^=//;
                   2330: 
                   2331:       #value
                   2332:       my $value='';
                   2333:       if($string =~ /^__HASH_REF__/) {
                   2334:           ($value, $string)=&str2hashref($string);
                   2335:           if(defined($value->{'error'})) {
                   2336:               $hash{'error'}='Bad data';
                   2337:               return (\%hash, $string);
                   2338:           }
                   2339:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2340:           ($value, $string)=&str2arrayref($string);
                   2341:           if($value->[0] eq 'Array reference error') {
                   2342:               $hash{'error'}='Bad data';
                   2343:               return (\%hash, $string);
                   2344:           }
                   2345:       } else {
                   2346: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2347:       }
                   2348:       $string =~ s/^&//;
                   2349: 
                   2350:       $hash{$key}=$value;
1.204     albertel 2351:   }
1.265     albertel 2352: 
                   2353:   $string =~ s/^__END_HASH_REF__//;
                   2354: 
                   2355:   return (\%hash, $string);
1.204     albertel 2356: }
                   2357: 
                   2358: sub str2array {
1.265     albertel 2359:     my ($string)=@_;
                   2360:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2361:     return @$array;
                   2362: }
                   2363: 
                   2364: sub str2arrayref {
1.204     albertel 2365:   my ($string) = @_;
1.265     albertel 2366:   my @array;
                   2367: 
                   2368:   if($string !~ /^__ARRAY_REF__/) {
                   2369:       if (! ($string eq '' || !defined($string))) {
                   2370: 	  $array[0]='Array reference error';
                   2371:       }
                   2372:       return (\@array, $string);
                   2373:   }
                   2374: 
                   2375:   $string =~ s/^__ARRAY_REF__//;
                   2376: 
                   2377:   while($string !~ /^__END_ARRAY_REF__/) {
                   2378:       my $value='';
                   2379:       if($string =~ /^__HASH_REF__/) {
                   2380:           ($value, $string)=&str2hashref($string);
                   2381:           if(defined($value->{'error'})) {
                   2382:               $array[0] ='Array reference error';
                   2383:               return (\@array, $string);
                   2384:           }
                   2385:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2386:           ($value, $string)=&str2arrayref($string);
                   2387:           if($value->[0] eq 'Array reference error') {
                   2388:               $array[0] ='Array reference error';
                   2389:               return (\@array, $string);
                   2390:           }
                   2391:       } else {
                   2392: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2393:       }
                   2394:       $string =~ s/^&//;
                   2395: 
                   2396:       push(@array, $value);
1.191     harris41 2397:   }
1.265     albertel 2398: 
                   2399:   $string =~ s/^__END_ARRAY_REF__//;
                   2400: 
                   2401:   return (\@array, $string);
1.168     albertel 2402: }
                   2403: 
1.167     albertel 2404: # -------------------------------------------------------------------Temp Store
                   2405: 
1.168     albertel 2406: sub tmpreset {
                   2407:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2408:   if (!$symb) {
                   2409:     $symb=&symbread();
1.620     albertel 2410:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2411:   }
                   2412:   $symb=escape($symb);
                   2413: 
1.620     albertel 2414:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2415:   $namespace=~s/\//\_/g;
                   2416:   $namespace=~s/\W//g;
                   2417: 
1.620     albertel 2418:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2419:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2420:   if ($domain eq 'public' && $stuname eq 'public') {
                   2421:       $stuname=$ENV{'REMOTE_ADDR'};
                   2422:   }
1.168     albertel 2423:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2424:   my %hash;
                   2425:   if (tie(%hash,'GDBM_File',
                   2426: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2427: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2428:     foreach my $key (keys %hash) {
1.180     albertel 2429:       if ($key=~ /:$symb/) {
1.168     albertel 2430: 	delete($hash{$key});
                   2431:       }
                   2432:     }
                   2433:   }
                   2434: }
                   2435: 
1.167     albertel 2436: sub tmpstore {
1.168     albertel 2437:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2438: 
                   2439:   if (!$symb) {
                   2440:     $symb=&symbread();
1.620     albertel 2441:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2442:   }
                   2443:   $symb=escape($symb);
                   2444: 
                   2445:   if (!$namespace) {
                   2446:     # I don't think we would ever want to store this for a course.
                   2447:     # it seems this will only be used if we don't have a course.
1.620     albertel 2448:     #$namespace=$env{'request.course.id'};
1.168     albertel 2449:     #if (!$namespace) {
1.620     albertel 2450:       $namespace=$env{'request.state'};
1.168     albertel 2451:     #}
                   2452:   }
                   2453:   $namespace=~s/\//\_/g;
                   2454:   $namespace=~s/\W//g;
1.620     albertel 2455:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2456:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2457:   if ($domain eq 'public' && $stuname eq 'public') {
                   2458:       $stuname=$ENV{'REMOTE_ADDR'};
                   2459:   }
1.168     albertel 2460:   my $now=time;
                   2461:   my %hash;
                   2462:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2463:   if (tie(%hash,'GDBM_File',
                   2464: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2465: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2466:     $hash{"version:$symb"}++;
                   2467:     my $version=$hash{"version:$symb"};
                   2468:     my $allkeys=''; 
                   2469:     foreach my $key (keys(%$storehash)) {
                   2470:       $allkeys.=$key.':';
1.591     albertel 2471:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2472:     }
                   2473:     $hash{"$version:$symb:timestamp"}=$now;
                   2474:     $allkeys.='timestamp';
                   2475:     $hash{"$version:keys:$symb"}=$allkeys;
                   2476:     if (untie(%hash)) {
                   2477:       return 'ok';
                   2478:     } else {
                   2479:       return "error:$!";
                   2480:     }
                   2481:   } else {
                   2482:     return "error:$!";
                   2483:   }
                   2484: }
1.167     albertel 2485: 
1.168     albertel 2486: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2487: 
1.168     albertel 2488: sub tmprestore {
                   2489:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2490: 
1.168     albertel 2491:   if (!$symb) {
                   2492:     $symb=&symbread();
1.620     albertel 2493:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2494:   }
                   2495:   $symb=escape($symb);
                   2496: 
1.620     albertel 2497:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2498: 
1.620     albertel 2499:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2500:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2501:   if ($domain eq 'public' && $stuname eq 'public') {
                   2502:       $stuname=$ENV{'REMOTE_ADDR'};
                   2503:   }
1.168     albertel 2504:   my %returnhash;
                   2505:   $namespace=~s/\//\_/g;
                   2506:   $namespace=~s/\W//g;
                   2507:   my %hash;
                   2508:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2509:   if (tie(%hash,'GDBM_File',
                   2510: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2511: 	  &GDBM_READER(),0640)) {
1.168     albertel 2512:     my $version=$hash{"version:$symb"};
                   2513:     $returnhash{'version'}=$version;
                   2514:     my $scope;
                   2515:     for ($scope=1;$scope<=$version;$scope++) {
                   2516:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2517:       my @keys=split(/:/,$vkeys);
                   2518:       my $key;
                   2519:       $returnhash{"$scope:keys"}=$vkeys;
                   2520:       foreach $key (@keys) {
1.591     albertel 2521: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2522: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2523:       }
                   2524:     }
1.168     albertel 2525:     if (!(untie(%hash))) {
                   2526:       return "error:$!";
                   2527:     }
                   2528:   } else {
                   2529:     return "error:$!";
                   2530:   }
                   2531:   return %returnhash;
1.167     albertel 2532: }
                   2533: 
1.9       www      2534: # ----------------------------------------------------------------------- Store
                   2535: 
                   2536: sub store {
1.124     www      2537:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2538:     my $home='';
                   2539: 
1.168     albertel 2540:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2541: 
1.213     www      2542:     $symb=&symbclean($symb);
1.122     albertel 2543:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2544: 
1.620     albertel 2545:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2546:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2547: 
                   2548:     &devalidate($symb,$stuname,$domain);
1.109     www      2549: 
                   2550:     $symb=escape($symb);
1.187     www      2551:     if (!$namespace) { 
1.620     albertel 2552:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2553:           return ''; 
                   2554:        } 
                   2555:     }
1.620     albertel 2556:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2557: 
                   2558:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2559:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2560: 
1.12      www      2561:     my $namevalue='';
1.191     harris41 2562:     foreach (keys %$storehash) {
1.591     albertel 2563:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2564:     }
1.12      www      2565:     $namevalue=~s/\&$//;
1.187     www      2566:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2567:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2568: }
                   2569: 
1.47      www      2570: # -------------------------------------------------------------- Critical Store
                   2571: 
                   2572: sub cstore {
1.124     www      2573:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2574:     my $home='';
                   2575: 
1.168     albertel 2576:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2577: 
1.213     www      2578:     $symb=&symbclean($symb);
1.122     albertel 2579:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2580: 
1.620     albertel 2581:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2582:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2583: 
                   2584:     &devalidate($symb,$stuname,$domain);
1.109     www      2585: 
                   2586:     $symb=escape($symb);
1.187     www      2587:     if (!$namespace) { 
1.620     albertel 2588:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2589:           return ''; 
                   2590:        } 
                   2591:     }
1.620     albertel 2592:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2593: 
                   2594:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2595:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2596: 
1.47      www      2597:     my $namevalue='';
1.191     harris41 2598:     foreach (keys %$storehash) {
1.591     albertel 2599:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2600:     }
1.47      www      2601:     $namevalue=~s/\&$//;
1.187     www      2602:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2603:     return critical
                   2604:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2605: }
                   2606: 
1.9       www      2607: # --------------------------------------------------------------------- Restore
                   2608: 
                   2609: sub restore {
1.124     www      2610:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2611:     my $home='';
                   2612: 
1.168     albertel 2613:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2614: 
1.122     albertel 2615:     if (!$symb) {
                   2616:       unless ($symb=escape(&symbread())) { return ''; }
                   2617:     } else {
1.213     www      2618:       $symb=&escape(&symbclean($symb));
1.122     albertel 2619:     }
1.188     www      2620:     if (!$namespace) { 
1.620     albertel 2621:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2622:           return ''; 
                   2623:        } 
                   2624:     }
1.620     albertel 2625:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2626:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2627:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2628:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2629: 
1.12      www      2630:     my %returnhash=();
1.191     harris41 2631:     foreach (split(/\&/,$answer)) {
1.12      www      2632: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2633:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2634:     }
1.75      www      2635:     my $version;
                   2636:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2637:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2638:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2639:        }
1.75      www      2640:     }
1.13      www      2641:     return %returnhash;
1.34      www      2642: }
                   2643: 
                   2644: # ---------------------------------------------------------- Course Description
                   2645: 
                   2646: sub coursedescription {
1.731     albertel 2647:     my ($courseid,$args)=@_;
1.34      www      2648:     $courseid=~s/^\///;
1.49      www      2649:     $courseid=~s/\_/\//g;
1.34      www      2650:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2651:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2652:     my $normalid=$cdomain.'_'.$cnum;
                   2653:     # need to always cache even if we get errors otherwise we keep 
                   2654:     # trying and trying and trying to get the course description.
                   2655:     my %envhash=();
                   2656:     my %returnhash=();
1.731     albertel 2657:     
                   2658:     my $expiretime=600;
                   2659:     if ($env{'request.course.id'} eq $normalid) {
                   2660: 	$expiretime=120;
                   2661:     }
                   2662: 
                   2663:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2664:     if (!$args->{'freshen_cache'}
                   2665: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2666: 	foreach my $key (keys(%env)) {
                   2667: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2668: 	    my ($setting) = $1;
                   2669: 	    $returnhash{$setting} = $env{$key};
                   2670: 	}
                   2671: 	return %returnhash;
                   2672:     }
                   2673: 
                   2674:     # get the data agin
                   2675:     if (!$args->{'one_time'}) {
                   2676: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2677:     }
1.34      www      2678:     if ($chome ne 'no_host') {
1.302     albertel 2679:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2680:        if (!exists($returnhash{'con_lost'})) {
                   2681:            $returnhash{'home'}= $chome;
                   2682: 	   $returnhash{'domain'} = $cdomain;
                   2683: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2684:            if (!defined($returnhash{'type'})) {
                   2685:                $returnhash{'type'} = 'Course';
                   2686:            }
1.130     albertel 2687:            while (my ($name,$value) = each %returnhash) {
1.53      www      2688:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2689:            }
1.270     www      2690:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2691:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2692: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2693:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2694:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2695:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2696:        }
                   2697:     }
1.731     albertel 2698:     if (!$args->{'one_time'}) {
                   2699: 	&appenv(%envhash);
                   2700:     }
1.302     albertel 2701:     return %returnhash;
1.461     www      2702: }
                   2703: 
                   2704: # -------------------------------------------------See if a user is privileged
                   2705: 
                   2706: sub privileged {
                   2707:     my ($username,$domain)=@_;
                   2708:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2709: 			&homeserver($username,$domain));
                   2710:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2711:     my $now=time;
                   2712:     if ($rolesdump ne '') {
                   2713:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2714: 	    if ($_!~/^rolesdef_/) {
1.461     www      2715: 		my ($area,$role)=split(/=/,$_);
                   2716: 		$area=~s/\_\w\w$//;
                   2717: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2718: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2719: 		    my $active=1;
                   2720: 		    if ($tend) {
                   2721: 			if ($tend<$now) { $active=0; }
                   2722: 		    }
                   2723: 		    if ($tstart) {
                   2724: 			if ($tstart>$now) { $active=0; }
                   2725: 		    }
                   2726: 		    if ($active) { return 1; }
                   2727: 		}
                   2728: 	    }
                   2729: 	}
                   2730:     }
                   2731:     return 0;
1.9       www      2732: }
1.1       albertel 2733: 
1.103     harris41 2734: # -------------------------------------------------------- Get user privileges
1.11      www      2735: 
                   2736: sub rolesinit {
                   2737:     my ($domain,$username,$authhost)=@_;
                   2738:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2739:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2740:     my %allroles=();
1.678     raeburn  2741:     my %allgroups=();   
1.11      www      2742:     my $now=time;
1.743     albertel 2743:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2744:     my $group_privs;
1.11      www      2745: 
                   2746:     if ($rolesdump ne '') {
1.191     harris41 2747:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2748: 	  if ($_!~/^rolesdef_/) {
1.11      www      2749:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2750: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2751:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2752: 	    if ($role=~/^cr/) { 
1.655     albertel 2753: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2754: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2755: 		    ($tend,$tstart)=split('_',$trest);
                   2756: 		} else {
                   2757: 		    $trole=$role;
                   2758: 		}
1.678     raeburn  2759:             } elsif ($role =~ m|^gr/|) {
                   2760:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2761:                 ($trole,$group_privs) = split(/\//,$trole);
                   2762:                 $group_privs = &unescape($group_privs);
1.587     albertel 2763: 	    } else {
                   2764: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2765: 	    }
1.743     albertel 2766: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2767: 					 $username);
                   2768: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2769:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2770:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2771:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2772: 		my $spec=$trole.'.'.$area;
                   2773: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2774: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2775:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2776:                 } elsif ($trole eq 'gr') {
                   2777:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2778: 		} else {
1.567     raeburn  2779:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2780: 		}
1.12      www      2781:             }
1.662     raeburn  2782:           }
1.191     harris41 2783:         }
1.743     albertel 2784:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2785:         $userroles{'user.adv'}    = $adv;
                   2786: 	$userroles{'user.author'} = $author;
1.620     albertel 2787:         $env{'user.adv'}=$adv;
1.11      www      2788:     }
1.743     albertel 2789:     return \%userroles;  
1.11      www      2790: }
                   2791: 
1.567     raeburn  2792: sub set_arearole {
                   2793:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2794: # log the associated role with the area
                   2795:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2796:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2797: }
                   2798: 
                   2799: sub custom_roleprivs {
                   2800:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2801:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2802:     my $homsvr=homeserver($rauthor,$rdomain);
                   2803:     if ($hostname{$homsvr} ne '') {
                   2804:         my ($rdummy,$roledef)=
                   2805:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2806:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2807:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2808:             if (defined($syspriv)) {
                   2809:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2810:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2811:             }
                   2812:             if ($tdomain ne '') {
                   2813:                 if (defined($dompriv)) {
                   2814:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2815:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2816:                 }
                   2817:                 if (($trest ne '') && (defined($coursepriv))) {
                   2818:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2819:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2820:                 }
                   2821:             }
                   2822:         }
                   2823:     }
                   2824: }
                   2825: 
1.678     raeburn  2826: sub group_roleprivs {
                   2827:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2828:     my $access = 1;
                   2829:     my $now = time;
                   2830:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2831:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2832:     if ($access) {
                   2833:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2834:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2835:     }
                   2836: }
1.567     raeburn  2837: 
                   2838: sub standard_roleprivs {
                   2839:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2840:     if (defined($pr{$trole.':s'})) {
                   2841:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2842:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2843:     }
                   2844:     if ($tdomain ne '') {
                   2845:         if (defined($pr{$trole.':d'})) {
                   2846:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2847:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2848:         }
                   2849:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2850:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2851:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2852:         }
                   2853:     }
                   2854: }
                   2855: 
                   2856: sub set_userprivs {
1.678     raeburn  2857:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2858:     my $author=0;
                   2859:     my $adv=0;
1.678     raeburn  2860:     my %grouproles = ();
                   2861:     if (keys(%{$allgroups}) > 0) {
                   2862:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2863:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2864:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2865:                 $trole = $1;
                   2866:                 $area = $2;
1.681     raeburn  2867:                 $sec = $3;
                   2868:                 $extendedarea = $area.$sec;
                   2869:                 if (exists($$allgroups{$area})) {
                   2870:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2871:                         my $spec = $trole.'.'.$extendedarea;
                   2872:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2873:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2874:                     }
                   2875:                 }
                   2876:             }
                   2877:         }
                   2878:     }
                   2879:     foreach (keys(%grouproles)) {
                   2880:         $$allroles{$_} = $grouproles{$_};
                   2881:     }
1.567     raeburn  2882:     foreach (keys %{$allroles}) {
                   2883:         my %thesepriv=();
                   2884:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2885:         foreach (split(/:/,$$allroles{$_})) {
                   2886:             if ($_ ne '') {
                   2887:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2888:                 if ($restrictions eq '') {
                   2889:                     $thesepriv{$privilege}='F';
                   2890:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2891:                     $thesepriv{$privilege}.=$restrictions;
                   2892:                 }
                   2893:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2894:             }
                   2895:         }
                   2896:         my $thesestr='';
                   2897:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2898:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2899:     }
                   2900:     return ($author,$adv);
                   2901: }
                   2902: 
1.12      www      2903: # --------------------------------------------------------------- get interface
                   2904: 
                   2905: sub get {
1.131     albertel 2906:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2907:    my $items='';
1.191     harris41 2908:    foreach (@$storearr) {
1.12      www      2909:        $items.=escape($_).'&';
1.191     harris41 2910:    }
1.12      www      2911:    $items=~s/\&$//;
1.620     albertel 2912:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2913:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2914:    my $uhome=&homeserver($uname,$udomain);
                   2915: 
1.133     albertel 2916:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2917:    my @pairs=split(/\&/,$rep);
1.273     albertel 2918:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2919:      return @pairs;
                   2920:    }
1.15      www      2921:    my %returnhash=();
1.42      www      2922:    my $i=0;
1.191     harris41 2923:    foreach (@$storearr) {
1.557     albertel 2924:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2925:       $i++;
1.191     harris41 2926:    }
1.15      www      2927:    return %returnhash;
1.27      www      2928: }
                   2929: 
                   2930: # --------------------------------------------------------------- del interface
                   2931: 
                   2932: sub del {
1.133     albertel 2933:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2934:    my $items='';
1.191     harris41 2935:    foreach (@$storearr) {
1.27      www      2936:        $items.=escape($_).'&';
1.191     harris41 2937:    }
1.27      www      2938:    $items=~s/\&$//;
1.620     albertel 2939:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2940:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2941:    my $uhome=&homeserver($uname,$udomain);
                   2942: 
                   2943:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2944: }
                   2945: 
                   2946: # -------------------------------------------------------------- dump interface
                   2947: 
                   2948: sub dump {
1.755     albertel 2949:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2950:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2951:     if (!$uname) { $uname=$env{'user.name'}; }
                   2952:     my $uhome=&homeserver($uname,$udomain);
                   2953:     if ($regexp) {
                   2954: 	$regexp=&escape($regexp);
                   2955:     } else {
                   2956: 	$regexp='.';
                   2957:     }
                   2958:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2959:     my @pairs=split(/\&/,$rep);
                   2960:     my %returnhash=();
                   2961:     foreach my $item (@pairs) {
                   2962: 	my ($key,$value)=split(/=/,$item,2);
                   2963: 	$key = &unescape($key);
                   2964: 	next if ($key =~ /^error: 2 /);
                   2965: 	$returnhash{$key}=&thaw_unescape($value);
                   2966:     }
                   2967:     return %returnhash;
1.407     www      2968: }
                   2969: 
1.717     albertel 2970: # --------------------------------------------------------- dumpstore interface
                   2971: 
                   2972: sub dumpstore {
                   2973:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2974:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2975: }
                   2976: 
1.407     www      2977: # -------------------------------------------------------------- keys interface
                   2978: 
                   2979: sub getkeys {
                   2980:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2981:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2982:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2983:    my $uhome=&homeserver($uname,$udomain);
                   2984:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2985:    my @keyarray=();
                   2986:    foreach (split(/\&/,$rep)) {
                   2987:       push (@keyarray,&unescape($_));
                   2988:    }
                   2989:    return @keyarray;
1.318     matthew  2990: }
                   2991: 
1.319     matthew  2992: # --------------------------------------------------------------- currentdump
                   2993: sub currentdump {
1.328     matthew  2994:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2995:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2996:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2997:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2998:    my $uhome = &homeserver($sname,$sdom);
                   2999:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3000:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3001:    #
1.318     matthew  3002:    my %returnhash=();
1.319     matthew  3003:    #
                   3004:    if ($rep eq "unknown_cmd") { 
                   3005:        # an old lond will not know currentdump
                   3006:        # Do a dump and make it look like a currentdump
1.326     matthew  3007:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3008:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3009:        my %hash = @tmp;
                   3010:        @tmp=();
1.424     matthew  3011:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3012:    } else {
                   3013:        my @pairs=split(/\&/,$rep);
                   3014:        foreach (@pairs) {
                   3015:            my ($key,$value)=split(/=/,$_);
                   3016:            my ($symb,$param) = split(/:/,$key);
                   3017:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3018:                                                         &thaw_unescape($value);
1.319     matthew  3019:        }
1.191     harris41 3020:    }
1.12      www      3021:    return %returnhash;
1.424     matthew  3022: }
                   3023: 
                   3024: sub convert_dump_to_currentdump{
                   3025:     my %hash = %{shift()};
                   3026:     my %returnhash;
                   3027:     # Code ripped from lond, essentially.  The only difference
                   3028:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3029:     # we might run in to problems with parameter names =~ /^v\./
                   3030:     while (my ($key,$value) = each(%hash)) {
                   3031:         my ($v,$symb,$param) = split(/:/,$key);
                   3032:         next if ($v eq 'version' || $symb eq 'keys');
                   3033:         next if (exists($returnhash{$symb}) &&
                   3034:                  exists($returnhash{$symb}->{$param}) &&
                   3035:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3036:         $returnhash{$symb}->{$param}=$value;
                   3037:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3038:     }
                   3039:     #
                   3040:     # Remove all of the keys in the hashes which keep track of
                   3041:     # the version of the parameter.
                   3042:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3043:         # use a foreach because we are going to delete from the hash.
                   3044:         foreach my $key (keys(%$param_hash)) {
                   3045:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3046:         }
                   3047:     }
                   3048:     return \%returnhash;
1.12      www      3049: }
                   3050: 
1.627     albertel 3051: # ------------------------------------------------------ critical inc interface
                   3052: 
                   3053: sub cinc {
                   3054:     return &inc(@_,'critical');
                   3055: }
                   3056: 
1.449     matthew  3057: # --------------------------------------------------------------- inc interface
                   3058: 
                   3059: sub inc {
1.627     albertel 3060:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3061:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3062:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3063:     my $uhome=&homeserver($uname,$udomain);
                   3064:     my $items='';
                   3065:     if (! ref($store)) {
                   3066:         # got a single value, so use that instead
                   3067:         $items = &escape($store).'=&';
                   3068:     } elsif (ref($store) eq 'SCALAR') {
                   3069:         $items = &escape($$store).'=&';        
                   3070:     } elsif (ref($store) eq 'ARRAY') {
                   3071:         $items = join('=&',map {&escape($_);} @{$store});
                   3072:     } elsif (ref($store) eq 'HASH') {
                   3073:         while (my($key,$value) = each(%{$store})) {
                   3074:             $items.= &escape($key).'='.&escape($value).'&';
                   3075:         }
                   3076:     }
                   3077:     $items=~s/\&$//;
1.627     albertel 3078:     if ($critical) {
                   3079: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3080:     } else {
                   3081: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3082:     }
1.449     matthew  3083: }
                   3084: 
1.12      www      3085: # --------------------------------------------------------------- put interface
                   3086: 
                   3087: sub put {
1.134     albertel 3088:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3089:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3090:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3091:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3092:    my $items='';
1.191     harris41 3093:    foreach (keys %$storehash) {
1.557     albertel 3094:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3095:    }
1.12      www      3096:    $items=~s/\&$//;
1.134     albertel 3097:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3098: }
                   3099: 
1.631     albertel 3100: # ------------------------------------------------------------ newput interface
                   3101: 
                   3102: sub newput {
                   3103:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3104:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3105:    if (!$uname) { $uname=$env{'user.name'}; }
                   3106:    my $uhome=&homeserver($uname,$udomain);
                   3107:    my $items='';
                   3108:    foreach my $key (keys(%$storehash)) {
                   3109:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3110:    }
                   3111:    $items=~s/\&$//;
                   3112:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3113: }
                   3114: 
                   3115: # ---------------------------------------------------------  putstore interface
                   3116: 
1.524     raeburn  3117: sub putstore {
1.715     albertel 3118:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3119:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3120:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3121:    my $uhome=&homeserver($uname,$udomain);
                   3122:    my $items='';
1.715     albertel 3123:    foreach my $key (keys(%$storehash)) {
                   3124:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3125:    }
1.715     albertel 3126:    $items=~s/\&$//;
1.716     albertel 3127:    my $esc_symb=&escape($symb);
                   3128:    my $esc_v=&escape($version);
1.715     albertel 3129:    my $reply =
1.716     albertel 3130:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3131: 	      $uhome);
                   3132:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3133:        # gfall back to way things use to be done
1.715     albertel 3134:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3135: 			    $uname);
1.524     raeburn  3136:    }
1.715     albertel 3137:    return $reply;
                   3138: }
                   3139: 
                   3140: sub old_putstore {
1.716     albertel 3141:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3142:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3143:     if (!$uname) { $uname=$env{'user.name'}; }
                   3144:     my $uhome=&homeserver($uname,$udomain);
                   3145:     my %newstorehash;
                   3146:     foreach (keys %$storehash) {
                   3147: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3148: 	$newstorehash{$key} = $storehash->{$_};
                   3149:     }
                   3150:     my $items='';
                   3151:     my %allitems = ();
                   3152:     foreach (keys %newstorehash) {
                   3153: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3154: 	    my $key = $1.':keys:'.$2;
                   3155: 	    $allitems{$key} .= $3.':';
                   3156: 	}
                   3157: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3158:     }
                   3159:     foreach (keys %allitems) {
                   3160: 	$allitems{$_} =~ s/\:$//;
                   3161: 	$items.= $_.'='.$allitems{$_}.'&';
                   3162:     }
                   3163:     $items=~s/\&$//;
                   3164:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3165: }
                   3166: 
1.47      www      3167: # ------------------------------------------------------ critical put interface
                   3168: 
                   3169: sub cput {
1.134     albertel 3170:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3171:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3172:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3173:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3174:    my $items='';
1.191     harris41 3175:    foreach (keys %$storehash) {
1.715     albertel 3176:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3177:    }
1.47      www      3178:    $items=~s/\&$//;
1.134     albertel 3179:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3180: }
                   3181: 
                   3182: # -------------------------------------------------------------- eget interface
                   3183: 
                   3184: sub eget {
1.133     albertel 3185:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3186:    my $items='';
1.191     harris41 3187:    foreach (@$storearr) {
1.12      www      3188:        $items.=escape($_).'&';
1.191     harris41 3189:    }
1.12      www      3190:    $items=~s/\&$//;
1.620     albertel 3191:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3192:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3193:    my $uhome=&homeserver($uname,$udomain);
                   3194:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3195:    my @pairs=split(/\&/,$rep);
                   3196:    my %returnhash=();
1.42      www      3197:    my $i=0;
1.191     harris41 3198:    foreach (@$storearr) {
1.557     albertel 3199:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3200:       $i++;
1.191     harris41 3201:    }
1.12      www      3202:    return %returnhash;
                   3203: }
                   3204: 
1.667     albertel 3205: # ------------------------------------------------------------ tmpput interface
                   3206: sub tmpput {
                   3207:     my ($storehash,$server)=@_;
                   3208:     my $items='';
                   3209:     foreach (keys(%$storehash)) {
                   3210: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3211:     }
                   3212:     $items=~s/\&$//;
                   3213:     return &reply("tmpput:$items",$server);
                   3214: }
                   3215: 
                   3216: # ------------------------------------------------------------ tmpget interface
                   3217: sub tmpget {
1.688     albertel 3218:     my ($token,$server)=@_;
                   3219:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3220:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3221:     my %returnhash;
                   3222:     foreach my $item (split(/\&/,$rep)) {
                   3223: 	my ($key,$value)=split(/=/,$item);
                   3224: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3225:     }
                   3226:     return %returnhash;
                   3227: }
                   3228: 
1.688     albertel 3229: # ------------------------------------------------------------ tmpget interface
                   3230: sub tmpdel {
                   3231:     my ($token,$server)=@_;
                   3232:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3233:     return &reply("tmpdel:$token",$server);
                   3234: }
                   3235: 
1.765     albertel 3236: # -------------------------------------------------- portfolio access checking
                   3237: 
                   3238: sub portfolio_access {
1.766     albertel 3239:     my ($requrl) = @_;
1.765     albertel 3240:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3241:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3242:     if ($result eq 'ok') {
1.766     albertel 3243:        return 'F';
1.765     albertel 3244:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3245:        return 'A';
1.765     albertel 3246:     }
1.766     albertel 3247:     return '';
1.765     albertel 3248: }
                   3249: 
                   3250: sub get_portfolio_access {
1.767     albertel 3251:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3252: 
                   3253:     if (!ref($access_hash)) {
                   3254: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3255: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3256: 						   $file_name);
                   3257: 	$access_hash = $access_controls{$file_name};
                   3258:     }
                   3259: 
1.765     albertel 3260:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3261:     my $now = time;
                   3262:     if (ref($access_hash) eq 'HASH') {
                   3263:         foreach my $key (keys(%{$access_hash})) {
                   3264:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3265:             if ($start > $now) {
                   3266:                 next;
                   3267:             }
                   3268:             if ($end && $end<$now) {
                   3269:                 next;
                   3270:             }
                   3271:             if ($scope eq 'public') {
                   3272:                 $public = $key;
                   3273:                 last;
                   3274:             } elsif ($scope eq 'guest') {
                   3275:                 $guest = $key;
                   3276:             } elsif ($scope eq 'domains') {
                   3277:                 push(@domains,$key);
                   3278:             } elsif ($scope eq 'users') {
                   3279:                 push(@users,$key);
                   3280:             } elsif ($scope eq 'course') {
                   3281:                 push(@courses,$key);
                   3282:             } elsif ($scope eq 'group') {
                   3283:                 push(@groups,$key);
                   3284:             }
                   3285:         }
                   3286:         if ($public) {
                   3287:             return 'ok';
                   3288:         }
                   3289:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3290:             if ($guest) {
                   3291:                 return $guest;
                   3292:             }
                   3293:         } else {
                   3294:             if (@domains > 0) {
                   3295:                 foreach my $domkey (@domains) {
                   3296:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3297:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3298:                             return 'ok';
                   3299:                         }
                   3300:                     }
                   3301:                 }
                   3302:             }
                   3303:             if (@users > 0) {
                   3304:                 foreach my $userkey (@users) {
                   3305:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3306:                         return 'ok';
                   3307:                     }
                   3308:                 }
                   3309:             }
                   3310:             my %roleshash;
                   3311:             my @courses_and_groups = @courses;
                   3312:             push(@courses_and_groups,@groups); 
                   3313:             if (@courses_and_groups > 0) {
                   3314:                 my (%allgroups,%allroles); 
                   3315:                 my ($start,$end,$role,$sec,$group);
                   3316:                 foreach my $envkey (%env) {
                   3317:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3318:                         my $cid = $2.'_'.$3; 
                   3319:                         if ($1 eq 'gr') {
                   3320:                             $group = $4;
                   3321:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3322:                         } else {
                   3323:                             if ($4 eq '') {
                   3324:                                 $sec = 'none';
                   3325:                             } else {
                   3326:                                 $sec = $4;
                   3327:                             }
                   3328:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3329:                         }
                   3330:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3331:                         my $cid = $2.'_'.$3;
                   3332:                         if ($4 eq '') {
                   3333:                             $sec = 'none';
                   3334:                         } else {
                   3335:                             $sec = $4;
                   3336:                         }
                   3337:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3338:                     }
                   3339:                 }
                   3340:                 if (keys(%allroles) == 0) {
                   3341:                     return;
                   3342:                 }
                   3343:                 foreach my $key (@courses_and_groups) {
                   3344:                     my %content = %{$$access_hash{$key}};
                   3345:                     my $cnum = $content{'number'};
                   3346:                     my $cdom = $content{'domain'};
                   3347:                     my $cid = $cdom.'_'.$cnum;
                   3348:                     if (!exists($allroles{$cid})) {
                   3349:                         next;
                   3350:                     }    
                   3351:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3352:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3353:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3354:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3355:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3356:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3357:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3358:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3359:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3360:                                         if (grep/^all$/,@sections) {
                   3361:                                             return 'ok';
                   3362:                                         } else {
                   3363:                                             if (grep/^$sec$/,@sections) {
                   3364:                                                 return 'ok';
                   3365:                                             }
                   3366:                                         }
                   3367:                                     }
                   3368:                                 }
                   3369:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3370:                                     if (grep/^none$/,@groups) {
                   3371:                                         return 'ok';
                   3372:                                     }
                   3373:                                 } else {
                   3374:                                     if (grep/^all$/,@groups) {
                   3375:                                         return 'ok';
                   3376:                                     } 
                   3377:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3378:                                         if (grep/^$group$/,@groups) {
                   3379:                                             return 'ok';
                   3380:                                         }
                   3381:                                     }
                   3382:                                 } 
                   3383:                             }
                   3384:                         }
                   3385:                     }
                   3386:                 }
                   3387:             }
                   3388:             if ($guest) {
                   3389:                 return $guest;
                   3390:             }
                   3391:         }
                   3392:     }
                   3393:     return;
                   3394: }
                   3395: 
                   3396: sub course_group_datechecker {
                   3397:     my ($dates,$now,$status) = @_;
                   3398:     my ($start,$end) = split(/\./,$dates);
                   3399:     if (!$start && !$end) {
                   3400:         return 'ok';
                   3401:     }
                   3402:     if (grep/^active$/,@{$status}) {
                   3403:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3404:             return 'ok';
                   3405:         }
                   3406:     }
                   3407:     if (grep/^previous$/,@{$status}) {
                   3408:         if ($end > $now ) {
                   3409:             return 'ok';
                   3410:         }
                   3411:     }
                   3412:     if (grep/^future$/,@{$status}) {
                   3413:         if ($start > $now) {
                   3414:             return 'ok';
                   3415:         }
                   3416:     }
                   3417:     return; 
                   3418: }
                   3419: 
                   3420: sub parse_portfolio_url {
                   3421:     my ($url) = @_;
                   3422: 
                   3423:     my ($type,$udom,$unum,$group,$file_name);
                   3424:     
                   3425:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3426: 	$type = 1;
                   3427:         $udom = $1;
                   3428:         $unum = $2;
                   3429:         $file_name = $3;
                   3430:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3431: 	$type = 2;
                   3432:         $udom = $1;
                   3433:         $unum = $2;
                   3434:         $group = $3;
                   3435:         $file_name = $3.'/'.$4;
                   3436:     }
                   3437:     if (wantarray) {
                   3438: 	return ($type,$udom,$unum,$file_name,$group);
                   3439:     }
                   3440:     return $type;
                   3441: }
                   3442: 
                   3443: sub is_portfolio_url {
                   3444:     my ($url) = @_;
                   3445:     return scalar(&parse_portfolio_url($url));
                   3446: }
                   3447: 
1.341     www      3448: # ---------------------------------------------- Custom access rule evaluation
                   3449: 
                   3450: sub customaccess {
                   3451:     my ($priv,$uri)=@_;
1.620     albertel 3452:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3453:     $urealm=~s/^\W//;
                   3454:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3455:     my $access=0;
                   3456:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3457: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3458:         if ($role) {
                   3459: 	   if ($role ne $urole) { next; }
                   3460:         }
                   3461:         foreach (split(/\s*\,\s*/,$realm)) {
                   3462:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3463:             if ($tdom) {
                   3464: 		if ($tdom ne $udom) { next; }
                   3465:             }
                   3466:             if ($tcrs) {
                   3467: 		if ($tcrs ne $ucrs) { next; }
                   3468:             }
                   3469:             if ($tsec) {
                   3470: 		if ($tsec ne $usec) { next; }
                   3471:             }
                   3472:             $access=($effect eq 'allow');
                   3473:             last;
1.342     www      3474:         }
1.402     bowersj2 3475: 	if ($realm eq '' && $role eq '') {
                   3476:             $access=($effect eq 'allow');
                   3477: 	}
1.341     www      3478:     }
                   3479:     return $access;
                   3480: }
                   3481: 
1.103     harris41 3482: # ------------------------------------------------- Check for a user privilege
1.12      www      3483: 
                   3484: sub allowed {
1.579     albertel 3485:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3486:     my $ver_orguri=$uri;
1.439     www      3487:     $uri=&deversion($uri);
1.152     www      3488:     my $orguri=$uri;
1.52      www      3489:     $uri=&declutter($uri);
1.545     banghart 3490:     
1.620     albertel 3491:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3492: # Free bre access to adm and meta resources
1.775     albertel 3493:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3494: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3495: 	&& ($priv eq 'bre')) {
1.14      www      3496: 	return 'F';
1.159     www      3497:     }
                   3498: 
1.545     banghart 3499: # Free bre access to user's own portfolio contents
1.714     raeburn  3500:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3501:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3502: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3503:         return 'F';
                   3504:     }
                   3505: 
1.762     raeburn  3506: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3507:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3508:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3509:         if (exists($env{'request.course.id'})) {
                   3510:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3511:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3512:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3513:                 my $courseprivid=$env{'request.course.id'};
                   3514:                 $courseprivid=~s/\_/\//;
                   3515:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3516:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3517:                     return $1; 
1.762     raeburn  3518:                 } else {
                   3519:                     if ($env{'request.course.sec'}) {
                   3520:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3521:                     }
                   3522:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3523:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3524:                         return $2;
                   3525:                     }
1.714     raeburn  3526:                 }
                   3527:             }
                   3528:         }
                   3529:     }
                   3530: 
1.159     www      3531: # Free bre to public access
                   3532: 
                   3533:     if ($priv eq 'bre') {
1.238     www      3534:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3535: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3536:            return 'F'; 
                   3537:         }
1.238     www      3538:         if ($copyright eq 'priv') {
                   3539:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3540: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3541: 		return '';
                   3542:             }
                   3543:         }
                   3544:         if ($copyright eq 'domain') {
                   3545:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3546: 	    unless (($env{'user.domain'} eq $1) ||
                   3547:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3548: 		return '';
                   3549:             }
1.262     matthew  3550:         }
1.620     albertel 3551:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3552:             # Library role, so allow browsing of resources in this domain.
                   3553:             return 'F';
1.238     www      3554:         }
1.341     www      3555:         if ($copyright eq 'custom') {
                   3556: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3557:         }
1.14      www      3558:     }
1.264     matthew  3559:     # Domain coordinator is trying to create a course
1.620     albertel 3560:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3561:         # uri is the requested domain in this case.
                   3562:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3563:         # a role of dc for the domain in question.
1.620     albertel 3564:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3565:     }
1.29      www      3566: 
1.52      www      3567:     my $thisallowed='';
                   3568:     my $statecond=0;
                   3569:     my $courseprivid='';
                   3570: 
                   3571: # Course
                   3572: 
1.620     albertel 3573:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3574:        $thisallowed.=$1;
                   3575:     }
1.29      www      3576: 
1.52      www      3577: # Domain
                   3578: 
1.620     albertel 3579:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3580:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3581:        $thisallowed.=$1;
                   3582:     }
1.52      www      3583: 
                   3584: # Course: uri itself is a course
1.66      www      3585:     my $courseuri=$uri;
                   3586:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3587:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3588: 
1.620     albertel 3589:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3590:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3591:        $thisallowed.=$1;
                   3592:     }
1.29      www      3593: 
1.665     albertel 3594: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3595: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3596:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3597: 	$thisallowed='';
1.671     raeburn  3598:         my ($match)=&is_on_map($uri);
                   3599:         if ($match) {
                   3600:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3601:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3602:                 $thisallowed.=$1;
                   3603:             }
                   3604:         } else {
1.705     albertel 3605:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3606:             if ($refuri) {
                   3607:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3608:                     $thisallowed='F';
1.671     raeburn  3609:                 } else {
                   3610:                     $refuri=&declutter($refuri);
                   3611:                     my ($match) = &is_on_map($refuri);
                   3612:                     if ($match) {
                   3613:                         $thisallowed='F';
                   3614:                     }
1.669     raeburn  3615:                 }
1.671     raeburn  3616:             }
                   3617:         }
1.314     www      3618:     }
1.492     albertel 3619: 
1.766     albertel 3620:     if ($priv eq 'bre'
                   3621: 	&& $thisallowed ne 'F' 
                   3622: 	&& $thisallowed ne '2'
                   3623: 	&& &is_portfolio_url($uri)) {
                   3624: 	$thisallowed = &portfolio_access($uri);
                   3625:     }
                   3626:     
1.52      www      3627: # Full access at system, domain or course-wide level? Exit.
1.29      www      3628: 
                   3629:     if ($thisallowed=~/F/) {
                   3630: 	return 'F';
                   3631:     }
                   3632: 
1.52      www      3633: # If this is generating or modifying users, exit with special codes
1.29      www      3634: 
1.643     www      3635:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3636: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3637: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3638: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3639: 	    unless ($auname) { return $thisallowed; }
                   3640: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3641: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3642: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3643: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3644: 	}
1.52      www      3645: 	return $thisallowed;
                   3646:     }
                   3647: #
1.103     harris41 3648: # Gathered so far: system, domain and course wide privileges
1.52      www      3649: #
                   3650: # Course: See if uri or referer is an individual resource that is part of 
                   3651: # the course
                   3652: 
1.620     albertel 3653:     if ($env{'request.course.id'}) {
1.232     www      3654: 
1.620     albertel 3655:        $courseprivid=$env{'request.course.id'};
                   3656:        if ($env{'request.course.sec'}) {
                   3657:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3658:        }
                   3659:        $courseprivid=~s/\_/\//;
                   3660:        my $checkreferer=1;
1.232     www      3661:        my ($match,$cond)=&is_on_map($uri);
                   3662:        if ($match) {
                   3663:            $statecond=$cond;
1.620     albertel 3664:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3665:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3666:                $thisallowed.=$1;
                   3667:                $checkreferer=0;
                   3668:            }
1.29      www      3669:        }
1.83      www      3670:        
1.148     www      3671:        if ($checkreferer) {
1.620     albertel 3672: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3673:             unless ($refuri) {
1.620     albertel 3674:                 foreach (keys %env) {
1.148     www      3675: 		    if ($_=~/^httpref\..*\*/) {
                   3676: 			my $pattern=$_;
1.156     www      3677:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3678:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3679:                         $pattern=~s/\//\\\//g;
1.152     www      3680:                         if ($orguri=~/$pattern/) {
1.620     albertel 3681: 			    $refuri=$env{$_};
1.148     www      3682:                         }
                   3683:                     }
1.191     harris41 3684:                 }
1.148     www      3685:             }
1.232     www      3686: 
1.148     www      3687:          if ($refuri) { 
1.152     www      3688: 	  $refuri=&declutter($refuri);
1.232     www      3689:           my ($match,$cond)=&is_on_map($refuri);
                   3690:             if ($match) {
                   3691:               my $refstatecond=$cond;
1.620     albertel 3692:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3693:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3694:                   $thisallowed.=$1;
1.53      www      3695:                   $uri=$refuri;
                   3696:                   $statecond=$refstatecond;
1.52      www      3697:               }
                   3698:           }
1.148     www      3699:         }
1.29      www      3700:        }
1.52      www      3701:    }
1.29      www      3702: 
1.52      www      3703: #
1.103     harris41 3704: # Gathered now: all privileges that could apply, and condition number
1.52      www      3705: # 
                   3706: #
                   3707: # Full or no access?
                   3708: #
1.29      www      3709: 
1.52      www      3710:     if ($thisallowed=~/F/) {
                   3711: 	return 'F';
                   3712:     }
1.29      www      3713: 
1.52      www      3714:     unless ($thisallowed) {
                   3715:         return '';
                   3716:     }
1.29      www      3717: 
1.52      www      3718: # Restrictions exist, deal with them
                   3719: #
                   3720: #   C:according to course preferences
                   3721: #   R:according to resource settings
                   3722: #   L:unless locked
                   3723: #   X:according to user session state
                   3724: #
                   3725: 
                   3726: # Possibly locked functionality, check all courses
1.54      www      3727: # Locks might take effect only after 10 minutes cache expiration for other
                   3728: # courses, and 2 minutes for current course
1.52      www      3729: 
                   3730:     my $envkey;
                   3731:     if ($thisallowed=~/L/) {
1.620     albertel 3732:         foreach $envkey (keys %env) {
1.54      www      3733:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3734:                my $courseid=$2;
                   3735:                my $roleid=$1.'.'.$2;
1.92      www      3736:                $courseid=~s/^\///;
1.54      www      3737:                my $expiretime=600;
1.620     albertel 3738:                if ($env{'request.role'} eq $roleid) {
1.54      www      3739: 		  $expiretime=120;
                   3740:                }
                   3741: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3742:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3743:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3744: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3745:                }
1.620     albertel 3746:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3747:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3748: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3749:                        &log($env{'user.domain'},$env{'user.name'},
                   3750:                             $env{'user.home'},
1.57      www      3751:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3752:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3753:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3754: 		       return '';
                   3755:                    }
                   3756:                }
1.620     albertel 3757:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3758:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3759: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3760:                        &log($env{'user.domain'},$env{'user.name'},
                   3761:                             $env{'user.home'},
1.57      www      3762:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3763:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3764:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3765: 		       return '';
                   3766:                    }
                   3767:                }
                   3768: 	   }
1.29      www      3769:        }
1.52      www      3770:     }
                   3771:    
                   3772: #
                   3773: # Rest of the restrictions depend on selected course
                   3774: #
                   3775: 
1.620     albertel 3776:     unless ($env{'request.course.id'}) {
1.766     albertel 3777: 	if ($thisallowed eq 'A') {
                   3778: 	    return 'A';
                   3779: 	} else {
                   3780: 	    return '1';
                   3781: 	}
1.52      www      3782:     }
1.29      www      3783: 
1.52      www      3784: #
                   3785: # Now user is definitely in a course
                   3786: #
1.53      www      3787: 
                   3788: 
                   3789: # Course preferences
                   3790: 
                   3791:    if ($thisallowed=~/C/) {
1.620     albertel 3792:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3793:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3794:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3795: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3796: 	   if ($priv ne 'pch') { 
                   3797: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3798: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3799: 			$env{'request.course.id'});
                   3800: 	   }
1.237     www      3801:            return '';
                   3802:        }
                   3803: 
1.620     albertel 3804:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3805: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3806: 	   if ($priv ne 'pch') { 
                   3807: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3808: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3809: 			$env{'request.course.id'});
                   3810: 	   }
1.54      www      3811:            return '';
                   3812:        }
1.53      www      3813:    }
                   3814: 
                   3815: # Resource preferences
                   3816: 
                   3817:    if ($thisallowed=~/R/) {
1.620     albertel 3818:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3819:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3820: 	   if ($priv ne 'pch') { 
                   3821: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3822: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3823: 	   }
                   3824: 	   return '';
1.54      www      3825:        }
1.53      www      3826:    }
1.30      www      3827: 
1.246     www      3828: # Restricted by state or randomout?
1.30      www      3829: 
1.52      www      3830:    if ($thisallowed=~/X/) {
1.620     albertel 3831:       if ($env{'acc.randomout'}) {
1.579     albertel 3832: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3833:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3834:             return ''; 
                   3835:          }
1.247     www      3836:       }
                   3837:       if (&condval($statecond)) {
1.52      www      3838: 	 return '2';
                   3839:       } else {
                   3840:          return '';
                   3841:       }
                   3842:    }
1.30      www      3843: 
1.766     albertel 3844:     if ($thisallowed eq 'A') {
                   3845: 	return 'A';
                   3846:     }
1.52      www      3847:    return 'F';
1.232     www      3848: }
                   3849: 
1.710     albertel 3850: sub split_uri_for_cond {
                   3851:     my $uri=&deversion(&declutter(shift));
                   3852:     my @uriparts=split(/\//,$uri);
                   3853:     my $filename=pop(@uriparts);
                   3854:     my $pathname=join('/',@uriparts);
                   3855:     return ($pathname,$filename);
                   3856: }
1.232     www      3857: # --------------------------------------------------- Is a resource on the map?
                   3858: 
                   3859: sub is_on_map {
1.710     albertel 3860:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3861:     #Trying to find the conditional for the file
1.620     albertel 3862:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3863: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3864:     if ($match) {
1.289     bowersj2 3865: 	return (1,$1);
                   3866:     } else {
1.434     www      3867: 	return (0,0);
1.289     bowersj2 3868:     }
1.12      www      3869: }
                   3870: 
1.427     www      3871: # --------------------------------------------------------- Get symb from alias
                   3872: 
                   3873: sub get_symb_from_alias {
                   3874:     my $symb=shift;
                   3875:     my ($map,$resid,$url)=&decode_symb($symb);
                   3876: # Already is a symb
                   3877:     if ($url) { return $symb; }
                   3878: # Must be an alias
                   3879:     my $aliassymb='';
                   3880:     my %bighash;
1.620     albertel 3881:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3882:                             &GDBM_READER(),0640)) {
                   3883:         my $rid=$bighash{'mapalias_'.$symb};
                   3884: 	if ($rid) {
                   3885: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3886: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3887: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3888: 	}
                   3889:         untie %bighash;
                   3890:     }
                   3891:     return $aliassymb;
                   3892: }
                   3893: 
1.12      www      3894: # ----------------------------------------------------------------- Define Role
                   3895: 
                   3896: sub definerole {
                   3897:   if (allowed('mcr','/')) {
                   3898:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3899:     foreach (split(':',$sysrole)) {
1.21      www      3900: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3901:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3902:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3903: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3904:                return "refused:s:$crole&$cqual"; 
                   3905:             }
                   3906:         }
1.191     harris41 3907:     }
1.392     www      3908:     foreach (split(':',$domrole)) {
1.21      www      3909: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3910:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3911:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3912: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3913:                return "refused:d:$crole&$cqual"; 
                   3914:             }
                   3915:         }
1.191     harris41 3916:     }
1.392     www      3917:     foreach (split(':',$courole)) {
1.21      www      3918: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3919:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3920:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3921: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3922:                return "refused:c:$crole&$cqual"; 
                   3923:             }
                   3924:         }
1.191     harris41 3925:     }
1.620     albertel 3926:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3927:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3928: 	        "rolesdef_$rolename=".
                   3929:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3930:     return reply($command,$env{'user.home'});
1.12      www      3931:   } else {
                   3932:     return 'refused';
                   3933:   }
1.105     harris41 3934: }
                   3935: 
                   3936: # ---------------- Make a metadata query against the network of library servers
                   3937: 
                   3938: sub metadata_query {
1.244     matthew  3939:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3940:     my %rhash;
1.244     matthew  3941:     my @server_list = (defined($server_array) ? @$server_array
                   3942:                                               : keys(%libserv) );
                   3943:     for my $server (@server_list) {
1.118     harris41 3944: 	unless ($custom or $customshow) {
                   3945: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3946: 	    $rhash{$server}=$reply;
                   3947: 	}
                   3948: 	else {
                   3949: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3950: 			     &escape($custom).':'.&escape($customshow),
                   3951: 			     $server);
                   3952: 	    $rhash{$server}=$reply;
                   3953: 	}
1.112     harris41 3954:     }
1.118     harris41 3955:     return \%rhash;
1.240     www      3956: }
                   3957: 
                   3958: # ----------------------------------------- Send log queries and wait for reply
                   3959: 
                   3960: sub log_query {
                   3961:     my ($uname,$udom,$query,%filters)=@_;
                   3962:     my $uhome=&homeserver($uname,$udom);
                   3963:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3964:     my $uhost=$hostname{$uhome};
1.241     www      3965:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3966:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3967:                        $uhome);
1.479     albertel 3968:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3969:     return get_query_reply($queryid);
                   3970: }
                   3971: 
1.508     raeburn  3972: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3973: 
                   3974: sub fetch_enrollment_query {
1.511     raeburn  3975:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3976:     my $homeserver;
1.547     raeburn  3977:     my $maxtries = 1;
1.508     raeburn  3978:     if ($context eq 'automated') {
                   3979:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3980:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3981:     } else {
                   3982:         $homeserver = &homeserver($cnum,$dom);
                   3983:     }
1.506     raeburn  3984:     my $host=$hostname{$homeserver};
                   3985:     my $cmd = '';
                   3986:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3987:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3988:     }
                   3989:     $cmd =~ s/%%$//;
                   3990:     $cmd = &escape($cmd);
                   3991:     my $query = 'fetchenrollment';
1.620     albertel 3992:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3993:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3994:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3995:         return 'error: '.$queryid;
                   3996:     }
1.506     raeburn  3997:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3998:     my $tries = 1;
                   3999:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4000:         $reply = &get_query_reply($queryid);
                   4001:         $tries ++;
                   4002:     }
1.526     raeburn  4003:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4004:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4005:     } else {
1.515     raeburn  4006:         my @responses = split/:/,$reply;
                   4007:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   4008:             foreach (@responses) {
                   4009:                 my ($key,$value) = split/=/,$_;
                   4010:                 $$replyref{$key} = $value;
                   4011:             }
                   4012:         } else {
1.506     raeburn  4013:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   4014:             foreach (@responses) {
                   4015:                 my ($key,$value) = split/=/,$_;
                   4016:                 $$replyref{$key} = $value;
                   4017:                 if ($value > 0) {
                   4018:                     foreach (@{$$affiliatesref{$key}}) {
                   4019:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   4020:                         my $destname = $pathname.'/'.$filename;
                   4021:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4022:                         if ($xml_classlist =~ /^error/) {
                   4023:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4024:                         } else {
1.506     raeburn  4025:                             if ( open(FILE,">$destname") ) {
                   4026:                                 print FILE &unescape($xml_classlist);
                   4027:                                 close(FILE);
1.526     raeburn  4028:                             } else {
                   4029:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4030:                             }
                   4031:                         }
                   4032:                     }
                   4033:                 }
                   4034:             }
                   4035:         }
                   4036:         return 'ok';
                   4037:     }
                   4038:     return 'error';
                   4039: }
                   4040: 
1.242     www      4041: sub get_query_reply {
                   4042:     my $queryid=shift;
1.240     www      4043:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4044:     my $reply='';
                   4045:     for (1..100) {
                   4046: 	sleep 2;
                   4047:         if (-e $replyfile.'.end') {
1.448     albertel 4048: 	    if (open(my $fh,$replyfile)) {
1.240     www      4049:                $reply.=<$fh>;
1.448     albertel 4050:                close($fh);
1.240     www      4051: 	   } else { return 'error: reply_file_error'; }
1.242     www      4052:            return &unescape($reply);
                   4053: 	}
1.240     www      4054:     }
1.242     www      4055:     return 'timeout:'.$queryid;
1.240     www      4056: }
                   4057: 
                   4058: sub courselog_query {
1.241     www      4059: #
                   4060: # possible filters:
                   4061: # url: url or symb
                   4062: # username
                   4063: # domain
                   4064: # action: view, submit, grade
                   4065: # start: timestamp
                   4066: # end: timestamp
                   4067: #
1.240     www      4068:     my (%filters)=@_;
1.620     albertel 4069:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4070:     if ($filters{'url'}) {
                   4071: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4072:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4073:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4074:     }
1.620     albertel 4075:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4076:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4077:     return &log_query($cname,$cdom,'courselog',%filters);
                   4078: }
                   4079: 
                   4080: sub userlog_query {
                   4081:     my ($uname,$udom,%filters)=@_;
                   4082:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4083: }
                   4084: 
1.506     raeburn  4085: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4086: 
                   4087: sub auto_run {
1.508     raeburn  4088:     my ($cnum,$cdom) = @_;
                   4089:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4090:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4091:     return $response;
                   4092: }
1.776     albertel 4093: 
1.506     raeburn  4094: sub auto_get_sections {
1.508     raeburn  4095:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4096:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4097:     my @secs = ();
1.511     raeburn  4098:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4099:     unless ($response eq 'refused') {
                   4100:         @secs = split/:/,$response;
                   4101:     }
                   4102:     return @secs;
                   4103: }
1.776     albertel 4104: 
1.506     raeburn  4105: sub auto_new_course {
1.508     raeburn  4106:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4107:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4108:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4109:     return $response;
                   4110: }
1.776     albertel 4111: 
1.506     raeburn  4112: sub auto_validate_courseID {
1.508     raeburn  4113:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4114:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4115:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4116:     return $response;
                   4117: }
1.776     albertel 4118: 
1.506     raeburn  4119: sub auto_create_password {
1.508     raeburn  4120:     my ($cnum,$cdom,$authparam) = @_;
                   4121:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4122:     my $create_passwd = 0;
                   4123:     my $authchk = '';
1.511     raeburn  4124:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4125:     if ($response eq 'refused') {
                   4126:         $authchk = 'refused';
                   4127:     } else {
                   4128:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4129:     }
                   4130:     return ($authparam,$create_passwd,$authchk);
                   4131: }
                   4132: 
1.706     raeburn  4133: sub auto_photo_permission {
                   4134:     my ($cnum,$cdom,$students) = @_;
                   4135:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4136:     my ($outcome,$perm_reqd,$conditions) = 
                   4137: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4138:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4139: 	return (undef,undef);
                   4140:     }
1.706     raeburn  4141:     return ($outcome,$perm_reqd,$conditions);
                   4142: }
                   4143: 
                   4144: sub auto_checkphotos {
                   4145:     my ($uname,$udom,$pid) = @_;
                   4146:     my $homeserver = &homeserver($uname,$udom);
                   4147:     my ($result,$resulttype);
                   4148:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4149: 				   &escape($uname).':'.&escape($pid),
                   4150: 				   $homeserver));
1.709     albertel 4151:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4152: 	return (undef,undef);
                   4153:     }
1.706     raeburn  4154:     if ($outcome) {
                   4155:         ($result,$resulttype) = split(/:/,$outcome);
                   4156:     } 
                   4157:     return ($result,$resulttype);
                   4158: }
                   4159: 
                   4160: sub auto_photochoice {
                   4161:     my ($cnum,$cdom) = @_;
                   4162:     my $homeserver = &homeserver($cnum,$cdom);
                   4163:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4164: 						       &escape($cdom),
                   4165: 						       $homeserver)));
1.709     albertel 4166:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4167: 	return (undef,undef);
                   4168:     }
1.706     raeburn  4169:     return ($update,$comment);
                   4170: }
                   4171: 
                   4172: sub auto_photoupdate {
                   4173:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4174:     my $homeserver = &homeserver($cnum,$dom);
                   4175:     my $host=$hostname{$homeserver};
                   4176:     my $cmd = '';
                   4177:     my $maxtries = 1;
                   4178:     foreach (keys %{$affiliatesref}) {
                   4179:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4180:     }
                   4181:     $cmd =~ s/%%$//;
                   4182:     $cmd = &escape($cmd);
                   4183:     my $query = 'institutionalphotos';
                   4184:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4185:     unless ($queryid=~/^\Q$host\E\_/) {
                   4186:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4187:         return 'error: '.$queryid;
                   4188:     }
                   4189:     my $reply = &get_query_reply($queryid);
                   4190:     my $tries = 1;
                   4191:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4192:         $reply = &get_query_reply($queryid);
                   4193:         $tries ++;
                   4194:     }
                   4195:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4196:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4197:     } else {
                   4198:         my @responses = split(/:/,$reply);
                   4199:         my $outcome = shift(@responses); 
                   4200:         foreach my $item (@responses) {
                   4201:             my ($key,$value) = split(/=/,$item);
                   4202:             $$photo{$key} = $value;
                   4203:         }
                   4204:         return $outcome;
                   4205:     }
                   4206:     return 'error';
                   4207: }
                   4208: 
1.521     raeburn  4209: sub auto_instcode_format {
                   4210:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   4211:     my $courses = '';
1.772     raeburn  4212:     my @homeservers;
1.521     raeburn  4213:     if ($caller eq 'global') {
1.584     raeburn  4214:         foreach my $tryserver (keys %libserv) {
                   4215:             if ($hostdom{$tryserver} eq $codedom) {
1.772     raeburn  4216:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
                   4217:                     push(@homeservers,$tryserver);
                   4218:                 }
1.584     raeburn  4219:             }
                   4220:         }
1.521     raeburn  4221:     } else {
1.772     raeburn  4222:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4223:     }
                   4224:     foreach (keys %{$instcodes}) {
                   4225:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   4226:     }
                   4227:     chop($courses);
1.772     raeburn  4228:     my $ok_response = 0;
                   4229:     my $response;
                   4230:     while (@homeservers > 0 && $ok_response == 0) {
                   4231:         my $server = shift(@homeservers); 
                   4232:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4233:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4234:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
                   4235:                                                             split/:/,$response;
                   4236:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4237:             push(@{$codetitles},&str2array($codetitles_str));
                   4238:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4239:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4240:             $ok_response = 1;
                   4241:         }
                   4242:     }
                   4243:     if ($ok_response) {
1.521     raeburn  4244:         return 'ok';
1.772     raeburn  4245:     } else {
                   4246:         return $response;
1.521     raeburn  4247:     }
                   4248: }
                   4249: 
1.777     albertel 4250: sub auto_validate_class_sec {
1.773     raeburn  4251:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4252:     my $homeserver = &homeserver($cnum,$cdom);
                   4253:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4254:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4255:     return $response;
                   4256: }
                   4257: 
1.679     raeburn  4258: # ------------------------------------------------------- Course Group routines
                   4259: 
                   4260: sub get_coursegroups {
1.683     raeburn  4261:     my ($cdom,$cnum,$group) = @_;
                   4262:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4263: }
                   4264: 
                   4265: sub modify_coursegroup {
                   4266:     my ($cdom,$cnum,$groupsettings) = @_;
                   4267:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4268: }
                   4269: 
                   4270: sub modify_group_roles {
                   4271:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4272:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4273:     my $role = 'gr/'.&escape($userprivs);
                   4274:     my ($uname,$udom) = split(/:/,$user);
                   4275:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4276:     if ($result eq 'ok') {
                   4277:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4278:     }
1.679     raeburn  4279:     return $result;
                   4280: }
                   4281: 
                   4282: sub modify_coursegroup_membership {
                   4283:     my ($cdom,$cnum,$membership) = @_;
                   4284:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4285:     return $result;
                   4286: }
                   4287: 
1.682     raeburn  4288: sub get_active_groups {
                   4289:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4290:     my $now = time;
                   4291:     my %groups = ();
                   4292:     foreach my $key (keys(%env)) {
                   4293:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4294:             my ($start,$end) = split(/\./,$env{$key});
                   4295:             if (($end!=0) && ($end<$now)) { next; }
                   4296:             if (($start!=0) && ($start>$now)) { next; }
                   4297:             if ($1 eq $cdom && $2 eq $cnum) {
                   4298:                 $groups{$3} = $env{$key} ;
                   4299:             }
                   4300:         }
                   4301:     }
                   4302:     return %groups;
                   4303: }
                   4304: 
1.683     raeburn  4305: sub get_group_membership {
                   4306:     my ($cdom,$cnum,$group) = @_;
                   4307:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4308: }
                   4309: 
                   4310: sub get_users_groups {
                   4311:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4312:     my @usersgroups;
1.683     raeburn  4313:     my $cachetime=1800;
                   4314:     $courseid=~s/\_/\//g;
                   4315:     $courseid=~s/^(\w)/\/$1/;
                   4316: 
                   4317:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4318:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4319:     if (defined($cached)) {
1.734     albertel 4320:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4321:     } else {  
                   4322:         $grouplist = '';
                   4323:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4324:         my ($tmp) = keys(%roleshash);
                   4325:         if ($tmp=~/^error:/) {
                   4326:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4327:         } else {
                   4328:             my $access_end = $env{'course.'.$courseid.
                   4329:                                   '.default_enrollment_end_date'};
                   4330:             my $now = time;
1.734     albertel 4331:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4332:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4333:                     my $group = $1;
                   4334:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4335:                         my $start = $2;
                   4336:                         my $end = $1;
                   4337:                         if ($start == -1) { next; } # deleted from group
                   4338:                         if (($start!=0) && ($start>$now)) { next; }
                   4339:                         if (($end!=0) && ($end<$now)) {
                   4340:                             if ($access_end && $access_end < $now) {
                   4341:                                 if ($access_end - $end < 86400) {
                   4342:                                     push(@usersgroups,$group);
                   4343:                                 }
                   4344:                             }
                   4345:                             next;
                   4346:                         }
                   4347:                         push(@usersgroups,$group);
                   4348:                     }
1.683     raeburn  4349:                 }
                   4350:             }
1.733     raeburn  4351:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4352:             $grouplist = join(':',@usersgroups);
                   4353:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4354:         }
                   4355:     }
1.733     raeburn  4356:     return @usersgroups;
1.683     raeburn  4357: }
                   4358: 
                   4359: sub devalidate_getgroups_cache {
                   4360:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4361:     my $courseid = $cdom.'_'.$cnum;
                   4362:     $courseid=~s/\_/\//g;
                   4363:     $courseid=~s/^(\w)/\/$1/;
                   4364:     my $hashid="$udom:$uname:$courseid";
                   4365:     &devalidate_cache_new('getgroups',$hashid);
                   4366: }
                   4367: 
1.12      www      4368: # ------------------------------------------------------------------ Plain Text
                   4369: 
                   4370: sub plaintext {
1.742     raeburn  4371:     my ($short,$type,$cid) = @_;
1.758     albertel 4372:     if ($short =~ /^cr/) {
                   4373: 	return (split('/',$short))[-1];
                   4374:     }
1.742     raeburn  4375:     if (!defined($cid)) {
                   4376:         $cid = $env{'request.course.id'};
                   4377:     }
                   4378:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4379:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4380:                                           '.plaintext'});
                   4381:     }
                   4382:     my %rolenames = (
                   4383:                       Course => 'std',
                   4384:                       Group => 'alt1',
                   4385:                     );
                   4386:     if (defined($type) && 
                   4387:          defined($rolenames{$type}) && 
                   4388:          defined($prp{$short}{$rolenames{$type}})) {
                   4389:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4390:     } else {
                   4391:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4392:     }
1.12      www      4393: }
                   4394: 
                   4395: # ----------------------------------------------------------------- Assign Role
                   4396: 
                   4397: sub assignrole {
1.357     www      4398:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4399:     my $mrole;
                   4400:     if ($role =~ /^cr\//) {
1.393     www      4401:         my $cwosec=$url;
                   4402:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4403: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4404:            &logthis('Refused custom assignrole: '.
                   4405:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4406: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4407:            return 'refused'; 
                   4408:         }
1.21      www      4409:         $mrole='cr';
1.678     raeburn  4410:     } elsif ($role =~ /^gr\//) {
                   4411:         my $cwogrp=$url;
                   4412:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4413:         unless (&allowed('mdg',$cwogrp)) {
                   4414:             &logthis('Refused group assignrole: '.
                   4415:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4416:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4417:             return 'refused';
                   4418:         }
                   4419:         $mrole='gr';
1.21      www      4420:     } else {
1.82      www      4421:         my $cwosec=$url;
1.83      www      4422:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4423:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4424:            &logthis('Refused assignrole: '.
                   4425:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4426: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4427:            return 'refused'; 
                   4428:         }
1.21      www      4429:         $mrole=$role;
                   4430:     }
1.620     albertel 4431:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4432:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4433:     if ($end) { $command.='_'.$end; }
1.21      www      4434:     if ($start) {
                   4435: 	if ($end) { 
1.81      www      4436:            $command.='_'.$start; 
1.21      www      4437:         } else {
1.81      www      4438:            $command.='_0_'.$start;
1.21      www      4439:         }
                   4440:     }
1.739     raeburn  4441:     my $origstart = $start;
                   4442:     my $origend = $end;
1.357     www      4443: # actually delete
                   4444:     if ($deleteflag) {
1.373     www      4445: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4446: # modify command to delete the role
1.620     albertel 4447:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4448:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4449: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4450: # set start and finish to negative values for userrolelog
                   4451:            $start=-1;
                   4452:            $end=-1;
                   4453:         }
                   4454:     }
                   4455: # send command
1.349     www      4456:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4457: # log new user role if status is ok
1.349     www      4458:     if ($answer eq 'ok') {
1.663     raeburn  4459: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4460: # for course roles, perform group memberships changes triggered by role change.
                   4461:         unless ($role =~ /^gr/) {
                   4462:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4463:                                              $origstart);
                   4464:         }
1.349     www      4465:     }
                   4466:     return $answer;
1.169     harris41 4467: }
                   4468: 
                   4469: # -------------------------------------------------- Modify user authentication
1.197     www      4470: # Overrides without validation
                   4471: 
1.169     harris41 4472: sub modifyuserauth {
                   4473:     my ($udom,$uname,$umode,$upass)=@_;
                   4474:     my $uhome=&homeserver($uname,$udom);
1.197     www      4475:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4476:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4477:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4478:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4479:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4480: 		     &escape($upass),$uhome);
1.620     albertel 4481:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4482:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4483:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4484:     &log($udom,,$uname,$uhome,
1.620     albertel 4485:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4486:                                      $env{'user.name'}.', '.$umode.
1.197     www      4487:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4488:     unless ($reply eq 'ok') {
1.197     www      4489:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4490: 	return 'error: '.$reply;
                   4491:     }   
1.170     harris41 4492:     return 'ok';
1.80      www      4493: }
                   4494: 
1.81      www      4495: # --------------------------------------------------------------- Modify a user
1.80      www      4496: 
1.81      www      4497: sub modifyuser {
1.206     matthew  4498:     my ($udom,    $uname, $uid,
                   4499:         $umode,   $upass, $first,
                   4500:         $middle,  $last,  $gene,
1.387     www      4501:         $forceid, $desiredhome, $email)=@_;
1.198     www      4502:     $udom=~s/\W//g;
                   4503:     $uname=~s/\W//g;
1.81      www      4504:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4505:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4506: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4507:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4508:                                      ' desiredhome not specified'). 
1.620     albertel 4509:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4510:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4511:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4512: # ----------------------------------------------------------------- Create User
1.406     albertel 4513:     if (($uhome eq 'no_host') && 
                   4514: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4515:         my $unhome='';
1.209     matthew  4516:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4517:             $unhome = $desiredhome;
1.620     albertel 4518: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4519: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4520:         } else { # load balancing routine for determining $unhome
1.80      www      4521:             my $tryserver;
1.81      www      4522:             my $loadm=10000000;
1.80      www      4523:             foreach $tryserver (keys %libserv) {
                   4524: 	       if ($hostdom{$tryserver} eq $udom) {
                   4525:                   my $answer=reply('load',$tryserver);
                   4526:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4527: 		      $loadm=$answer;
                   4528:                       $unhome=$tryserver;
                   4529:                   }
                   4530: 	       }
                   4531: 	    }
                   4532:         }
                   4533:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4534: 	    return 'error: unable to find a home server for '.$uname.
                   4535:                    ' in domain '.$udom;
1.80      www      4536:         }
                   4537:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4538:                          &escape($upass),$unhome);
                   4539: 	unless ($reply eq 'ok') {
                   4540:             return 'error: '.$reply;
                   4541:         }   
1.230     stredwic 4542:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4543:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4544: 	    return 'error: unable verify users home machine.';
1.80      www      4545:         }
1.209     matthew  4546:     }   # End of creation of new user
1.80      www      4547: # ---------------------------------------------------------------------- Add ID
                   4548:     if ($uid) {
                   4549:        $uid=~tr/A-Z/a-z/;
                   4550:        my %uidhash=&idrget($udom,$uname);
1.196     www      4551:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4552:          && (!$forceid)) {
1.80      www      4553: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4554: 	      return 'error: user id "'.$uid.'" does not match '.
                   4555:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4556:           }
                   4557:        } else {
                   4558: 	  &idput($udom,($uname => $uid));
                   4559:        }
                   4560:     }
                   4561: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4562:     my @tmp=&get('environment',
1.134     albertel 4563: 		   ['firstname','middlename','lastname','generation'],
                   4564: 		   $udom,$uname);
1.313     matthew  4565:     my %names;
                   4566:     if ($tmp[0] =~ m/^error:.*/) { 
                   4567:         %names=(); 
                   4568:     } else {
                   4569:         %names = @tmp;
                   4570:     }
1.388     www      4571: #
                   4572: # Make sure to not trash student environment if instructor does not bother
                   4573: # to supply name and email information
                   4574: #
                   4575:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4576:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4577:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4578:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4579:     if ($email) {
                   4580:        $email=~s/[^\w\@\.\-\,]//gs;
                   4581:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4582: 			   $names{'critnotification'} = $email;
                   4583: 			   $names{'permanentemail'} = $email; }
                   4584:     }
1.134     albertel 4585:     my $reply = &put('environment', \%names, $udom,$uname);
                   4586:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4587:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4588:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4589:              $umode.', '.$first.', '.$middle.', '.
                   4590: 	     $last.', '.$gene.' by '.
1.620     albertel 4591:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4592:     return 'ok';
1.80      www      4593: }
                   4594: 
1.81      www      4595: # -------------------------------------------------------------- Modify student
1.80      www      4596: 
1.81      www      4597: sub modifystudent {
                   4598:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4599:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4600:     if (!$cid) {
1.620     albertel 4601: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4602: 	    return 'not_in_class';
                   4603: 	}
1.80      www      4604:     }
                   4605: # --------------------------------------------------------------- Make the user
1.81      www      4606:     my $reply=&modifyuser
1.209     matthew  4607: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4608:          $desiredhome,$email);
1.80      www      4609:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4610:     # This will cause &modify_student_enrollment to get the uid from the
                   4611:     # students environment
                   4612:     $uid = undef if (!$forceid);
1.455     albertel 4613:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4614: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4615:     return $reply;
                   4616: }
                   4617: 
                   4618: sub modify_student_enrollment {
1.515     raeburn  4619:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4620:     my ($cdom,$cnum,$chome);
                   4621:     if (!$cid) {
1.620     albertel 4622: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4623: 	    return 'not_in_class';
                   4624: 	}
1.620     albertel 4625: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4626: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4627:     } else {
                   4628: 	($cdom,$cnum)=split(/_/,$cid);
                   4629:     }
1.620     albertel 4630:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4631:     if (!$chome) {
1.457     raeburn  4632: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4633:     }
1.455     albertel 4634:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4635:     # Make sure the user exists
1.81      www      4636:     my $uhome=&homeserver($uname,$udom);
                   4637:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4638: 	return 'error: no such user';
                   4639:     }
1.297     matthew  4640:     # Get student data if we were not given enough information
                   4641:     if (!defined($first)  || $first  eq '' || 
                   4642:         !defined($last)   || $last   eq '' || 
                   4643:         !defined($uid)    || $uid    eq '' || 
                   4644:         !defined($middle) || $middle eq '' || 
                   4645:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4646:         # They did not supply us with enough data to enroll the student, so
                   4647:         # we need to pick up more information.
1.297     matthew  4648:         my %tmp = &get('environment',
1.294     matthew  4649:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4650:                        ,$udom,$uname);
                   4651: 
1.455     albertel 4652:         #foreach (keys(%tmp)) {
                   4653:         #    &logthis("key $_ = ".$tmp{$_});
                   4654:         #}
1.294     matthew  4655:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4656:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4657:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4658:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4659:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4660:     }
1.556     albertel 4661:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4662:     my $reply=cput('classlist',
                   4663: 		   {"$uname:$udom" => 
1.515     raeburn  4664: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4665: 		   $cdom,$cnum);
1.81      www      4666:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4667: 	return 'error: '.$reply;
1.652     albertel 4668:     } else {
                   4669: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4670:     }
1.297     matthew  4671:     # Add student role to user
1.83      www      4672:     my $uurl='/'.$cid;
1.81      www      4673:     $uurl=~s/\_/\//g;
                   4674:     if ($usec) {
                   4675: 	$uurl.='/'.$usec;
                   4676:     }
                   4677:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4678: }
                   4679: 
1.556     albertel 4680: sub format_name {
                   4681:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4682:     my $name;
                   4683:     if ($first ne 'lastname') {
                   4684: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4685:     } else {
                   4686: 	if ($lastname=~/\S/) {
                   4687: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4688: 	    $name=~s/\s+,/,/;
                   4689: 	} else {
                   4690: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4691: 	}
                   4692:     }
                   4693:     $name=~s/^\s+//;
                   4694:     $name=~s/\s+$//;
                   4695:     $name=~s/\s+/ /g;
                   4696:     return $name;
                   4697: }
                   4698: 
1.84      www      4699: # ------------------------------------------------- Write to course preferences
                   4700: 
                   4701: sub writecoursepref {
                   4702:     my ($courseid,%prefs)=@_;
                   4703:     $courseid=~s/^\///;
                   4704:     $courseid=~s/\_/\//g;
                   4705:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4706:     my $chome=homeserver($cnum,$cdomain);
                   4707:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4708: 	return 'error: no such course';
                   4709:     }
                   4710:     my $cstring='';
1.191     harris41 4711:     foreach (keys %prefs) {
1.84      www      4712: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4713:     }
1.84      www      4714:     $cstring=~s/\&$//;
                   4715:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4716: }
                   4717: 
                   4718: # ---------------------------------------------------------- Make/modify course
                   4719: 
                   4720: sub createcourse {
1.741     raeburn  4721:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4722:         $course_owner,$crstype)=@_;
1.84      www      4723:     $url=&declutter($url);
                   4724:     my $cid='';
1.264     matthew  4725:     unless (&allowed('ccc',$udom)) {
1.84      www      4726:         return 'refused';
                   4727:     }
                   4728: # ------------------------------------------------------------------- Create ID
1.674     www      4729:    my $uname=int(1+rand(9)).
                   4730:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4731:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4732:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4733: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4734:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4735:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4736:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4737:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4738:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4739:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4740:            return 'error: unable to generate unique course-ID';
                   4741:        } 
                   4742:    }
1.264     matthew  4743: # ------------------------------------------------ Check supplied server name
1.620     albertel 4744:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4745:     if (! exists($libserv{$course_server})) {
                   4746:         return 'error:bad server name '.$course_server;
                   4747:     }
1.84      www      4748: # ------------------------------------------------------------- Make the course
                   4749:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4750:                       $course_server);
1.84      www      4751:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4752:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4753:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4754: 	return 'error: no such course';
                   4755:     }
1.271     www      4756: # ----------------------------------------------------------------- Course made
1.516     raeburn  4757: # log existence
                   4758:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4759:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4760:                   &escape($crstype),$uhome);
1.358     www      4761:     &flushcourselogs();
                   4762: # set toplevel url
1.271     www      4763:     my $topurl=$url;
                   4764:     unless ($nonstandard) {
                   4765: # ------------------------------------------ For standard courses, make top url
                   4766:         my $mapurl=&clutter($url);
1.278     www      4767:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4768:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4769: <map>
                   4770: <resource id="1" type="start"></resource>
                   4771: <resource id="2" src="$mapurl"></resource>
                   4772: <resource id="3" type="finish"></resource>
                   4773: <link index="1" from="1" to="2"></link>
                   4774: <link index="2" from="2" to="3"></link>
                   4775: </map>
                   4776: ENDINITMAP
                   4777:         $topurl=&declutter(
1.638     albertel 4778:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4779:                           );
                   4780:     }
                   4781: # ----------------------------------------------------------- Write preferences
1.84      www      4782:     &writecoursepref($udom.'_'.$uname,
                   4783:                      ('description' => $description,
1.271     www      4784:                       'url'         => $topurl));
1.84      www      4785:     return '/'.$udom.'/'.$uname;
                   4786: }
                   4787: 
1.21      www      4788: # ---------------------------------------------------------- Assign Custom Role
                   4789: 
                   4790: sub assigncustomrole {
1.357     www      4791:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4792:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4793:                        $end,$start,$deleteflag);
1.21      www      4794: }
                   4795: 
                   4796: # ----------------------------------------------------------------- Revoke Role
                   4797: 
                   4798: sub revokerole {
1.357     www      4799:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4800:     my $now=time;
1.357     www      4801:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4802: }
                   4803: 
                   4804: # ---------------------------------------------------------- Revoke Custom Role
                   4805: 
                   4806: sub revokecustomrole {
1.357     www      4807:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4808:     my $now=time;
1.357     www      4809:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4810:            $deleteflag);
1.17      www      4811: }
                   4812: 
1.533     banghart 4813: # ------------------------------------------------------------ Disk usage
1.535     albertel 4814: sub diskusage {
1.533     banghart 4815:     my ($udom,$uname,$directoryRoot)=@_;
                   4816:     $directoryRoot =~ s/\/$//;
1.535     albertel 4817:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4818:     return $listing;
1.512     banghart 4819: }
                   4820: 
1.566     banghart 4821: sub is_locked {
                   4822:     my ($file_name, $domain, $user) = @_;
                   4823:     my @check;
                   4824:     my $is_locked;
                   4825:     push @check, $file_name;
1.613     albertel 4826:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4827: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4828:     my ($tmp)=keys(%locked);
                   4829:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4830:     
1.566     banghart 4831:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4832:         $is_locked = 'false';
                   4833:         foreach my $entry (@{$locked{$file_name}}) {
                   4834:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4835:                $is_locked = 'true';
                   4836:                last;
1.745     raeburn  4837:            }
                   4838:        }
1.566     banghart 4839:     } else {
                   4840:         $is_locked = 'false';
                   4841:     }
                   4842: }
                   4843: 
1.759     albertel 4844: sub declutter_portfile {
                   4845:     my ($file) = @_;
                   4846:     &logthis("got $file");
                   4847:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4848:     &logthis("ret $file");
                   4849:     return $file;
                   4850: }
                   4851: 
1.559     banghart 4852: # ------------------------------------------------------------- Mark as Read Only
                   4853: 
                   4854: sub mark_as_readonly {
                   4855:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4856:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4857:     my ($tmp)=keys(%current_permissions);
                   4858:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4859:     foreach my $file (@{$files}) {
1.759     albertel 4860: 	$file = &declutter_portfile($file);
1.561     banghart 4861:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4862:     }
1.613     albertel 4863:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4864:     return;
                   4865: }
                   4866: 
1.572     banghart 4867: # ------------------------------------------------------------Save Selected Files
                   4868: 
                   4869: sub save_selected_files {
                   4870:     my ($user, $path, @files) = @_;
                   4871:     my $filename = $user."savedfiles";
1.573     banghart 4872:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4873:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4874:     foreach my $file (@files) {
1.620     albertel 4875:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4876:     }
                   4877:     foreach my $file (@other_files) {
1.574     banghart 4878:         print (OUT $file."\n");
1.572     banghart 4879:     }
1.574     banghart 4880:     close (OUT);
1.572     banghart 4881:     return 'ok';
                   4882: }
                   4883: 
1.574     banghart 4884: sub clear_selected_files {
                   4885:     my ($user) = @_;
                   4886:     my $filename = $user."savedfiles";
                   4887:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4888:     print (OUT undef);
                   4889:     close (OUT);
                   4890:     return ("ok");    
                   4891: }
                   4892: 
1.572     banghart 4893: sub files_in_path {
                   4894:     my ($user, $path) = @_;
                   4895:     my $filename = $user."savedfiles";
                   4896:     my %return_files;
1.574     banghart 4897:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4898:     while (my $line_in = <IN>) {
1.574     banghart 4899:         chomp ($line_in);
                   4900:         my @paths_and_file = split (m!/!, $line_in);
                   4901:         my $file_part = pop (@paths_and_file);
                   4902:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4903:         $path_part.='/';
                   4904:         my $path_and_file = $path_part.$file_part;
                   4905:         if ($path_part eq $path) {
                   4906:             $return_files{$file_part}= 'selected';
                   4907:         }
                   4908:     }
1.574     banghart 4909:     close (IN);
                   4910:     return (\%return_files);
1.572     banghart 4911: }
                   4912: 
                   4913: # called in portfolio select mode, to show files selected NOT in current directory
                   4914: sub files_not_in_path {
                   4915:     my ($user, $path) = @_;
                   4916:     my $filename = $user."savedfiles";
                   4917:     my @return_files;
                   4918:     my $path_part;
1.574     banghart 4919:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4920:     while (<IN>) {
                   4921:         #ok, I know it's clunky, but I want it to work
                   4922:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4923:         my $file_part = pop (@paths_and_file);
                   4924:         chomp ($file_part);
                   4925:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4926:         $path_part .= '/';
                   4927:         my $path_and_file = $path_part.$file_part;
                   4928:         if ($path_part ne $path) {
1.574     banghart 4929:             push (@return_files, ($path_and_file));
1.572     banghart 4930:         }
                   4931:     }
1.574     banghart 4932:     close (OUT);
                   4933:     return (@return_files);
1.572     banghart 4934: }
                   4935: 
1.745     raeburn  4936: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4937: 
1.745     raeburn  4938: sub get_portfile_permissions {
                   4939:     my ($domain,$user) = @_;
1.613     albertel 4940:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4941:     my ($tmp)=keys(%current_permissions);
                   4942:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4943:     return \%current_permissions;
                   4944: }
                   4945: 
                   4946: #---------------------------------------------Get portfolio file access controls
                   4947: 
1.749     raeburn  4948: sub get_access_controls {
1.745     raeburn  4949:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4950:     my %access;
                   4951:     my $real_file = $file;
                   4952:     $file =~ s/\.meta$//;
1.745     raeburn  4953:     if (defined($file)) {
1.749     raeburn  4954:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4955:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 4956:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  4957:             }
                   4958:         }
1.745     raeburn  4959:     } else {
1.749     raeburn  4960:         foreach my $key (keys(%{$current_permissions})) {
                   4961:             if ($key =~ /\0accesscontrol$/) {
                   4962:                 if (defined($group)) {
                   4963:                     if ($key !~ m-^\Q$group\E/-) {
                   4964:                         next;
                   4965:                     }
                   4966:                 }
                   4967:                 my ($fullpath) = split(/\0/,$key);
                   4968:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4969:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4970:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4971:                     }
                   4972:                 }
                   4973:             }
                   4974:         }
                   4975:     }
                   4976:     return %access;
                   4977: }
                   4978: 
                   4979: sub modify_access_controls {
                   4980:     my ($file_name,$changes,$domain,$user)=@_;
                   4981:     my ($outcome,$deloutcome);
                   4982:     my %store_permissions;
                   4983:     my %new_values;
                   4984:     my %new_control;
                   4985:     my %translation;
                   4986:     my @deletions = ();
                   4987:     my $now = time;
                   4988:     if (exists($$changes{'activate'})) {
                   4989:         if (ref($$changes{'activate'}) eq 'HASH') {
                   4990:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   4991:             my $numnew = scalar(@newitems);
                   4992:             for (my $i=0; $i<$numnew; $i++) {
                   4993:                 my $newkey = $newitems[$i];
                   4994:                 my $newid = &Apache::loncommon::get_cgi_id();
                   4995:                 $newkey =~ s/^(\d+)/$newid/;
                   4996:                 $translation{$1} = $newid;
                   4997:                 $new_values{$file_name."\0".$newkey} = 
                   4998:                                           $$changes{'activate'}{$newitems[$i]};
                   4999:                 $new_control{$newkey} = $now;
                   5000:             }
                   5001:         }
                   5002:     }
                   5003:     my %todelete;
                   5004:     my %changed_items;
                   5005:     foreach my $action ('delete','update') {
                   5006:         if (exists($$changes{$action})) {
                   5007:             if (ref($$changes{$action}) eq 'HASH') {
                   5008:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5009:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5010:                     if ($action eq 'delete') { 
                   5011:                         $todelete{$itemnum} = 1;
                   5012:                     } else {
                   5013:                         $changed_items{$itemnum} = $key;
                   5014:                     }
                   5015:                 }
1.745     raeburn  5016:             }
                   5017:         }
1.749     raeburn  5018:     }
                   5019:     # get lock on access controls for file.
                   5020:     my $lockhash = {
                   5021:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5022:                                                        ':'.$env{'user.domain'},
                   5023:                    }; 
                   5024:     my $tries = 0;
                   5025:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5026:    
                   5027:     while (($gotlock ne 'ok') && $tries <3) {
                   5028:         $tries ++;
                   5029:         sleep 1;
                   5030:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5031:     }
                   5032:     if ($gotlock eq 'ok') {
                   5033:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5034:         my ($tmp)=keys(%curr_permissions);
                   5035:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5036:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5037:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5038:             if (ref($curr_controls) eq 'HASH') {
                   5039:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5040:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5041:                     if (defined($todelete{$itemnum})) {
                   5042:                         push(@deletions,$file_name."\0".$control_item);
                   5043:                     } else {
                   5044:                         if (defined($changed_items{$itemnum})) {
                   5045:                             $new_control{$changed_items{$itemnum}} = $now;
                   5046:                             push(@deletions,$file_name."\0".$control_item);
                   5047:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5048:                         } else {
                   5049:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5050:                         }
                   5051:                     }
1.745     raeburn  5052:                 }
                   5053:             }
                   5054:         }
1.749     raeburn  5055:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5056:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5057:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5058:         #  remove lock
                   5059:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5060:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5061:     } else {
                   5062:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5063:     }
1.749     raeburn  5064:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5065: }
                   5066: 
                   5067: #------------------------------------------------------Get Marked as Read Only
                   5068: 
                   5069: sub get_marked_as_readonly {
                   5070:     my ($domain,$user,$what,$group) = @_;
                   5071:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5072:     my @readonly_files;
1.629     banghart 5073:     my $cmp1=$what;
                   5074:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5075:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5076:         if (defined($group)) {
                   5077:             if ($file_name !~ m-^\Q$group\E/-) {
                   5078:                 next;
                   5079:             }
                   5080:         }
1.561     banghart 5081:         if (ref($value) eq "ARRAY"){
                   5082:             foreach my $stored_what (@{$value}) {
1.629     banghart 5083:                 my $cmp2=$stored_what;
1.759     albertel 5084:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5085:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5086:                 }
1.629     banghart 5087:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5088:                     push(@readonly_files, $file_name);
1.745     raeburn  5089:                     last;
1.563     banghart 5090:                 } elsif (!defined($what)) {
                   5091:                     push(@readonly_files, $file_name);
1.745     raeburn  5092:                     last;
1.561     banghart 5093:                 }
                   5094:             }
1.745     raeburn  5095:         }
1.561     banghart 5096:     }
                   5097:     return @readonly_files;
                   5098: }
1.577     banghart 5099: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5100: 
1.577     banghart 5101: sub get_marked_as_readonly_hash {
1.745     raeburn  5102:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5103:     my %readonly_files;
1.745     raeburn  5104:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5105:         if (defined($group)) {
                   5106:             if ($file_name !~ m-^\Q$group\E/-) {
                   5107:                 next;
                   5108:             }
                   5109:         }
1.577     banghart 5110:         if (ref($value) eq "ARRAY"){
                   5111:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5112:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5113:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5114:                         if ($lock_descriptor eq 'graded') {
                   5115:                             $readonly_files{$file_name} = 'graded';
                   5116:                         } elsif ($lock_descriptor eq 'handback') {
                   5117:                             $readonly_files{$file_name} = 'handback';
                   5118:                         } else {
                   5119:                             if (!exists($readonly_files{$file_name})) {
                   5120:                                 $readonly_files{$file_name} = 'locked';
                   5121:                             }
                   5122:                         }
1.745     raeburn  5123:                     }
1.750     banghart 5124:                 } 
1.577     banghart 5125:             }
                   5126:         } 
                   5127:     }
                   5128:     return %readonly_files;
                   5129: }
1.559     banghart 5130: # ------------------------------------------------------------ Unmark as Read Only
                   5131: 
                   5132: sub unmark_as_readonly {
1.629     banghart 5133:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5134:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5135:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5136:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5137:     my $symb_crs = $what;
                   5138:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5139:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5140:     my ($tmp)=keys(%current_permissions);
                   5141:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5142:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5143:     foreach my $file (@readonly_files) {
1.759     albertel 5144: 	my $clean_file = &declutter_portfile($file);
                   5145: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5146: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5147:         my @new_locks;
                   5148:         my @del_keys;
                   5149:         if (ref($current_locks) eq "ARRAY"){
                   5150:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5151:                 my $compare=$locker;
1.749     raeburn  5152:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5153:                     $compare=join('',@{$locker});
1.746     raeburn  5154:                     if ($compare ne $symb_crs) {
                   5155:                         push(@new_locks, $locker);
                   5156:                     }
1.563     banghart 5157:                 }
                   5158:             }
1.650     albertel 5159:             if (scalar(@new_locks) > 0) {
1.563     banghart 5160:                 $current_permissions{$file} = \@new_locks;
                   5161:             } else {
                   5162:                 push(@del_keys, $file);
1.613     albertel 5163:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5164:                 delete($current_permissions{$file});
1.563     banghart 5165:             }
                   5166:         }
1.561     banghart 5167:     }
1.613     albertel 5168:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5169:     return;
                   5170: }
1.512     banghart 5171: 
1.17      www      5172: # ------------------------------------------------------------ Directory lister
                   5173: 
                   5174: sub dirlist {
1.253     stredwic 5175:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5176: 
1.18      www      5177:     $uri=~s/^\///;
                   5178:     $uri=~s/\/$//;
1.253     stredwic 5179:     my ($udom, $uname);
                   5180:     (undef,$udom,$uname)=split(/\//,$uri);
                   5181:     if(defined($userdomain)) {
                   5182:         $udom = $userdomain;
                   5183:     }
                   5184:     if(defined($username)) {
                   5185:         $uname = $username;
                   5186:     }
                   5187: 
                   5188:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5189:     if(defined($alternateDirectoryRoot)) {
                   5190:         $dirRoot = $alternateDirectoryRoot;
                   5191:         $dirRoot =~ s/\/$//;
1.751     banghart 5192:     }
1.253     stredwic 5193: 
                   5194:     if($udom) {
                   5195:         if($uname) {
1.605     matthew  5196:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5197:                               homeserver($uname,$udom));
1.605     matthew  5198:             my @listing_results;
                   5199:             if ($listing eq 'unknown_cmd') {
                   5200:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5201:                                homeserver($uname,$udom));
                   5202:                 @listing_results = split(/:/,$listing);
                   5203:             } else {
                   5204:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5205:             }
                   5206:             return @listing_results;
1.253     stredwic 5207:         } elsif(!defined($alternateDirectoryRoot)) {
                   5208:             my $tryserver;
                   5209:             my %allusers=();
                   5210:             foreach $tryserver (keys %libserv) {
                   5211:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5212:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5213:                                       $udom, $tryserver);
1.605     matthew  5214:                     my @listing_results;
                   5215:                     if ($listing eq 'unknown_cmd') {
                   5216:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5217:                                        $udom, $tryserver);
                   5218:                         @listing_results = split(/:/,$listing);
                   5219:                     } else {
                   5220:                         @listing_results =
                   5221:                             map { &unescape($_); } split(/:/,$listing);
                   5222:                     }
                   5223:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5224:                         $listing_results[0] ne 'empty'       &&
                   5225:                         $listing_results[0] ne 'con_lost') {
                   5226:                         foreach (@listing_results) {
1.253     stredwic 5227:                             my ($entry,@stat)=split(/&/,$_);
                   5228:                             $allusers{$entry}=1;
                   5229:                         }
                   5230:                     }
1.191     harris41 5231:                 }
1.253     stredwic 5232:             }
                   5233:             my $alluserstr='';
                   5234:             foreach (sort keys %allusers) {
                   5235:                 $alluserstr.=$_.'&user:';
                   5236:             }
                   5237:             $alluserstr=~s/:$//;
                   5238:             return split(/:/,$alluserstr);
                   5239:         } else {
                   5240:             my @emptyResults = ();
                   5241:             push(@emptyResults, 'missing user name');
                   5242:             return split(':',@emptyResults);
                   5243:         }
                   5244:     } elsif(!defined($alternateDirectoryRoot)) {
                   5245:         my $tryserver;
                   5246:         my %alldom=();
                   5247:         foreach $tryserver (keys %libserv) {
                   5248:             $alldom{$hostdom{$tryserver}}=1;
                   5249:         }
                   5250:         my $alldomstr='';
                   5251:         foreach (sort keys %alldom) {
1.397     albertel 5252:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5253:         }
                   5254:         $alldomstr=~s/:$//;
                   5255:         return split(/:/,$alldomstr);       
                   5256:     } else {
                   5257:         my @emptyResults = ();
                   5258:         push(@emptyResults, 'missing domain');
                   5259:         return split(':',@emptyResults);
1.275     stredwic 5260:     }
                   5261: }
                   5262: 
                   5263: # --------------------------------------------- GetFileTimestamp
                   5264: # This function utilizes dirlist and returns the date stamp for
                   5265: # when it was last modified.  It will also return an error of -1
                   5266: # if an error occurs
                   5267: 
1.410     matthew  5268: ##
                   5269: ## FIXME: This subroutine assumes its caller knows something about the
                   5270: ## directory structure of the home server for the student ($root).
                   5271: ## Not a good assumption to make.  Since this is for looking up files
                   5272: ## in user directories, the full path should be constructed by lond, not
                   5273: ## whatever machine we request data from.
                   5274: ##
1.275     stredwic 5275: sub GetFileTimestamp {
                   5276:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5277:     $studentDomain=~s/\W//g;
                   5278:     $studentName=~s/\W//g;
                   5279:     my $subdir=$studentName.'__';
                   5280:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5281:     my $proname="$studentDomain/$subdir/$studentName";
                   5282:     $proname .= '/'.$filename;
1.375     matthew  5283:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5284:                                               $studentName, $root);
1.275     stredwic 5285:     my @stats = split('&', $fileStat);
                   5286:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5287:         # @stats contains first the filename, then the stat output
                   5288:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5289:     } else {
                   5290:         return -1;
1.253     stredwic 5291:     }
1.26      www      5292: }
                   5293: 
1.712     albertel 5294: sub stat_file {
                   5295:     my ($uri) = @_;
1.722     albertel 5296:     $uri = &clutter($uri);
                   5297: 
                   5298:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 5299:     if ($uri =~ m-^/adm/-) {
                   5300: 	$uri=~s-^/adm/wrapper/-/-;
                   5301: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 5302:     }
1.712     albertel 5303:     my ($udom,$uname,$file,$dir);
                   5304:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5305: 	($udom,$uname,$file) =
                   5306: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5307: 	$file = 'userfiles/'.$file;
1.740     www      5308: 	$dir = &propath($udom,$uname);
1.712     albertel 5309:     }
                   5310:     if ($uri =~ m-^/res/-) {
                   5311: 	($udom,$uname) = 
                   5312: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5313: 	$file = $uri;
                   5314:     }
                   5315: 
                   5316:     if (!$udom || !$uname || !$file) {
                   5317: 	# unable to handle the uri
                   5318: 	return ();
                   5319:     }
                   5320: 
                   5321:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5322:     my @stats = split('&', $result);
1.721     banghart 5323:     
1.712     albertel 5324:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5325: 	shift(@stats); #filename is first
                   5326: 	return @stats;
                   5327:     }
                   5328:     return ();
                   5329: }
                   5330: 
1.26      www      5331: # -------------------------------------------------------- Value of a Condition
                   5332: 
1.713     albertel 5333: # gets the value of a specific preevaluated condition
                   5334: #    stored in the string  $env{user.state.<cid>}
                   5335: # or looks up a condition reference in the bighash and if if hasn't
                   5336: # already been evaluated recurses into docondval to get the value of
                   5337: # the condition, then memoizing it to 
                   5338: #   $env{user.state.<cid>.<condition>}
1.40      www      5339: sub directcondval {
                   5340:     my $number=shift;
1.620     albertel 5341:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5342: 	&Apache::lonuserstate::evalstate();
                   5343:     }
1.713     albertel 5344:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5345: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5346:     } elsif ($number =~ /^_/) {
                   5347: 	my $sub_condition;
                   5348: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5349: 		&GDBM_READER(),0640)) {
                   5350: 	    $sub_condition=$bighash{'conditions'.$number};
                   5351: 	    untie(%bighash);
                   5352: 	}
                   5353: 	my $value = &docondval($sub_condition);
                   5354: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5355: 	return $value;
                   5356:     }
1.620     albertel 5357:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5358:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5359:     } else {
                   5360:        return 2;
                   5361:     }
                   5362: }
                   5363: 
1.713     albertel 5364: # get the collection of conditions for this resource
1.26      www      5365: sub condval {
                   5366:     my $condidx=shift;
1.54      www      5367:     my $allpathcond='';
1.713     albertel 5368:     foreach my $cond (split(/\|/,$condidx)) {
                   5369: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5370: 	    $allpathcond.=
                   5371: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5372: 	}
1.191     harris41 5373:     }
1.54      www      5374:     $allpathcond=~s/\|$//;
1.713     albertel 5375:     return &docondval($allpathcond);
                   5376: }
                   5377: 
                   5378: #evaluates an expression of conditions
                   5379: sub docondval {
                   5380:     my ($allpathcond) = @_;
                   5381:     my $result=0;
                   5382:     if ($env{'request.course.id'}
                   5383: 	&& defined($allpathcond)) {
                   5384: 	my $operand='|';
                   5385: 	my @stack;
                   5386: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5387: 	    if ($chunk eq '(') {
                   5388: 		push @stack,($operand,$result);
                   5389: 	    } elsif ($chunk eq ')') {
                   5390: 		my $before=pop @stack;
                   5391: 		if (pop @stack eq '&') {
                   5392: 		    $result=$result>$before?$before:$result;
                   5393: 		} else {
                   5394: 		    $result=$result>$before?$result:$before;
                   5395: 		}
                   5396: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5397: 		$operand=$chunk;
                   5398: 	    } else {
                   5399: 		my $new=directcondval($chunk);
                   5400: 		if ($operand eq '&') {
                   5401: 		    $result=$result>$new?$new:$result;
                   5402: 		} else {
                   5403: 		    $result=$result>$new?$result:$new;
                   5404: 		}
                   5405: 	    }
                   5406: 	}
1.26      www      5407:     }
                   5408:     return $result;
1.421     albertel 5409: }
                   5410: 
                   5411: # ---------------------------------------------------- Devalidate courseresdata
                   5412: 
                   5413: sub devalidatecourseresdata {
                   5414:     my ($coursenum,$coursedomain)=@_;
                   5415:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5416:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5417: }
                   5418: 
1.763     www      5419: 
1.200     www      5420: # --------------------------------------------------- Course Resourcedata Query
                   5421: 
1.624     albertel 5422: sub get_courseresdata {
                   5423:     my ($coursenum,$coursedomain)=@_;
1.200     www      5424:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5425:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5426:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5427:     my %dumpreply;
1.417     albertel 5428:     unless (defined($cached)) {
1.624     albertel 5429: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5430: 	$result=\%dumpreply;
1.251     albertel 5431: 	my ($tmp) = keys(%dumpreply);
                   5432: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5433: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5434: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5435: 	    return $tmp;
1.416     albertel 5436: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5437: 	    $result=undef;
1.599     albertel 5438: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5439: 	}
                   5440:     }
1.624     albertel 5441:     return $result;
                   5442: }
                   5443: 
1.633     albertel 5444: sub devalidateuserresdata {
                   5445:     my ($uname,$udom)=@_;
                   5446:     my $hashid="$udom:$uname";
                   5447:     &devalidate_cache_new('userres',$hashid);
                   5448: }
                   5449: 
1.624     albertel 5450: sub get_userresdata {
                   5451:     my ($uname,$udom)=@_;
                   5452:     #most student don\'t have any data set, check if there is some data
                   5453:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5454: 
                   5455:     my $hashid="$udom:$uname";
                   5456:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5457:     if (!defined($cached)) {
                   5458: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5459: 	$result=\%resourcedata;
                   5460: 	&do_cache_new('userres',$hashid,$result,600);
                   5461:     }
                   5462:     my ($tmp)=keys(%$result);
                   5463:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5464: 	return $result;
                   5465:     }
                   5466:     #error 2 occurs when the .db doesn't exist
                   5467:     if ($tmp!~/error: 2 /) {
1.672     albertel 5468: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5469: 		 " Trying to get resource data for ".
                   5470: 		 $uname." at ".$udom.": ".
                   5471: 		 $tmp."</font>");
                   5472:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5473: 	#&EXT_cache_set($udom,$uname);
                   5474: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5475: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5476:     }
                   5477:     return $tmp;
                   5478: }
                   5479: 
                   5480: sub resdata {
                   5481:     my ($name,$domain,$type,@which)=@_;
                   5482:     my $result;
                   5483:     if ($type eq 'course') {
                   5484: 	$result=&get_courseresdata($name,$domain);
                   5485:     } elsif ($type eq 'user') {
                   5486: 	$result=&get_userresdata($name,$domain);
                   5487:     }
                   5488:     if (!ref($result)) { return $result; }    
1.251     albertel 5489:     foreach my $item (@which) {
1.417     albertel 5490: 	if (defined($result->{$item})) {
                   5491: 	    return $result->{$item};
1.251     albertel 5492: 	}
1.250     albertel 5493:     }
1.291     albertel 5494:     return undef;
1.200     www      5495: }
                   5496: 
1.379     matthew  5497: #
                   5498: # EXT resource caching routines
                   5499: #
                   5500: 
                   5501: sub clear_EXT_cache_status {
1.383     albertel 5502:     &delenv('cache.EXT.');
1.379     matthew  5503: }
                   5504: 
                   5505: sub EXT_cache_status {
                   5506:     my ($target_domain,$target_user) = @_;
1.383     albertel 5507:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5508:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5509:         # We know already the user has no data
                   5510:         return 1;
                   5511:     } else {
                   5512:         return 0;
                   5513:     }
                   5514: }
                   5515: 
                   5516: sub EXT_cache_set {
                   5517:     my ($target_domain,$target_user) = @_;
1.383     albertel 5518:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5519:     #&appenv($cachename => time);
1.379     matthew  5520: }
                   5521: 
1.28      www      5522: # --------------------------------------------------------- Value of a Variable
1.58      www      5523: sub EXT {
1.715     albertel 5524: 
1.395     albertel 5525:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5526:     unless ($varname) { return ''; }
1.218     albertel 5527:     #get real user name/domain, courseid and symb
                   5528:     my $courseid;
1.359     albertel 5529:     my $publicuser;
1.427     www      5530:     if ($symbparm) {
                   5531: 	$symbparm=&get_symb_from_alias($symbparm);
                   5532:     }
1.218     albertel 5533:     if (!($uname && $udom)) {
1.360     albertel 5534:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5535: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5536:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5537:     } else {
1.620     albertel 5538: 	$courseid=$env{'request.course.id'};
1.218     albertel 5539:     }
1.48      www      5540:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5541:     my $rest;
1.320     albertel 5542:     if (defined($therest[0])) {
1.48      www      5543:        $rest=join('.',@therest);
                   5544:     } else {
                   5545:        $rest='';
                   5546:     }
1.320     albertel 5547: 
1.57      www      5548:     my $qualifierrest=$qualifier;
                   5549:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5550:     my $spacequalifierrest=$space;
                   5551:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5552:     if ($realm eq 'user') {
1.48      www      5553: # --------------------------------------------------------------- user.resource
                   5554: 	if ($space eq 'resource') {
1.651     albertel 5555: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5556: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5557: 		 &&
1.744     albertel 5558: 		 ($symbparm eq &symbread()) ) {	
                   5559: 		# if we are in the middle of processing the resource the
                   5560: 		# get the value we are planning on committing
                   5561:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5562:                     return $Apache::lonhomework::results{$qualifierrest};
                   5563:                 } else {
                   5564:                     return $Apache::lonhomework::history{$qualifierrest};
                   5565:                 }
1.335     albertel 5566: 	    } else {
1.359     albertel 5567: 		my %restored;
1.620     albertel 5568: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5569: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5570: 		} else {
                   5571: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5572: 		}
1.335     albertel 5573: 		return $restored{$qualifierrest};
                   5574: 	    }
1.48      www      5575: # ----------------------------------------------------------------- user.access
                   5576:         } elsif ($space eq 'access') {
1.218     albertel 5577: 	    # FIXME - not supporting calls for a specific user
1.48      www      5578:             return &allowed($qualifier,$rest);
                   5579: # ------------------------------------------ user.preferences, user.environment
                   5580:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5581: 	    if (($uname eq $env{'user.name'}) &&
                   5582: 		($udom eq $env{'user.domain'})) {
                   5583: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5584: 	    } else {
1.359     albertel 5585: 		my %returnhash;
                   5586: 		if (!$publicuser) {
                   5587: 		    %returnhash=&userenvironment($udom,$uname,
                   5588: 						 $qualifierrest);
                   5589: 		}
1.218     albertel 5590: 		return $returnhash{$qualifierrest};
                   5591: 	    }
1.48      www      5592: # ----------------------------------------------------------------- user.course
                   5593:         } elsif ($space eq 'course') {
1.218     albertel 5594: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5595:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5596: # ------------------------------------------------------------------- user.role
                   5597:         } elsif ($space eq 'role') {
1.218     albertel 5598: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5599:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5600:             if ($qualifier eq 'value') {
                   5601: 		return $role;
                   5602:             } elsif ($qualifier eq 'extent') {
                   5603:                 return $where;
                   5604:             }
                   5605: # ----------------------------------------------------------------- user.domain
                   5606:         } elsif ($space eq 'domain') {
1.218     albertel 5607:             return $udom;
1.48      www      5608: # ------------------------------------------------------------------- user.name
                   5609:         } elsif ($space eq 'name') {
1.218     albertel 5610:             return $uname;
1.48      www      5611: # ---------------------------------------------------- Any other user namespace
1.29      www      5612:         } else {
1.359     albertel 5613: 	    my %reply;
                   5614: 	    if (!$publicuser) {
                   5615: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5616: 	    }
                   5617: 	    return $reply{$qualifierrest};
1.48      www      5618:         }
1.236     www      5619:     } elsif ($realm eq 'query') {
                   5620: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5621:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5622: 						[$spacequalifierrest]);
1.620     albertel 5623: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5624:    } elsif ($realm eq 'request') {
1.48      www      5625: # ------------------------------------------------------------- request.browser
                   5626:         if ($space eq 'browser') {
1.430     www      5627: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5628: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5629: 		    return 1;
                   5630: 		} else {
                   5631: 		    return 0;
                   5632: 		}
                   5633: 	    } else {
1.620     albertel 5634: 		return $env{'browser.'.$qualifier};
1.430     www      5635: 	    }
1.57      www      5636: # ------------------------------------------------------------ request.filename
                   5637:         } else {
1.620     albertel 5638:             return $env{'request.'.$spacequalifierrest};
1.29      www      5639:         }
1.28      www      5640:     } elsif ($realm eq 'course') {
1.48      www      5641: # ---------------------------------------------------------- course.description
1.620     albertel 5642:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5643:     } elsif ($realm eq 'resource') {
1.165     www      5644: 
1.620     albertel 5645: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5646: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5647: 	}
1.693     albertel 5648: 
                   5649: 	if ($space eq 'title') {
                   5650: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5651: 	    return &gettitle($symbparm);
                   5652: 	}
                   5653: 	
                   5654: 	if ($space eq 'map') {
                   5655: 	    my ($map) = &decode_symb($symbparm);
                   5656: 	    return &symbread($map);
                   5657: 	}
                   5658: 
                   5659: 	my ($section, $group, @groups);
1.593     albertel 5660: 	my ($courselevelm,$courselevel);
1.539     albertel 5661: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5662: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5663: 
1.218     albertel 5664: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5665: 
1.60      www      5666: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5667: 	    my $symbp=$symbparm;
1.735     albertel 5668: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5669: 
                   5670: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5671: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5672: 
1.620     albertel 5673: 	    if (($env{'user.name'} eq $uname) &&
                   5674: 		($env{'user.domain'} eq $udom)) {
                   5675: 		$section=$env{'request.course.sec'};
1.733     raeburn  5676:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5677:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5678: 	    } else {
1.539     albertel 5679: 		if (! defined($usection)) {
1.551     albertel 5680: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5681: 		} else {
                   5682: 		    $section = $usection;
                   5683: 		}
1.733     raeburn  5684:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5685: 	    }
                   5686: 
                   5687: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5688: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5689: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5690: 
1.593     albertel 5691: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5692: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5693: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5694: 
1.60      www      5695: # ----------------------------------------------------------- first, check user
1.624     albertel 5696: 
                   5697: 	    my $userreply=&resdata($uname,$udom,'user',
                   5698: 				       ($courselevelr,$courselevelm,
                   5699: 					$courselevel));
                   5700: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5701: 
1.594     albertel 5702: # ------------------------------------------------ second, check some of course
1.684     raeburn  5703:             my $coursereply;
1.691     raeburn  5704:             if (@groups > 0) {
                   5705:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5706:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5707:                 if (defined($coursereply)) { return $coursereply; }
                   5708:             }
1.96      www      5709: 
1.684     raeburn  5710: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5711: 				     $env{'course.'.$courseid.'.domain'},
                   5712: 				     'course',
                   5713: 				     ($seclevelr,$seclevelm,$seclevel,
                   5714: 				      $courselevelr));
1.287     albertel 5715: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5716: 
1.60      www      5717: # ------------------------------------------------------ third, check map parms
1.218     albertel 5718: 	    my %parmhash=();
                   5719: 	    my $thisparm='';
                   5720: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5721: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5722: 		    &GDBM_READER(),0640)) {
1.218     albertel 5723: 		$thisparm=$parmhash{$symbparm};
                   5724: 		untie(%parmhash);
                   5725: 	    }
                   5726: 	    if ($thisparm) { return $thisparm; }
                   5727: 	}
1.594     albertel 5728: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5729: 
1.218     albertel 5730: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5731: 	my $filename;
                   5732: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5733: 	if ($symbparm) {
1.409     www      5734: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5735: 	} else {
1.620     albertel 5736: 	    $filename=$env{'request.filename'};
1.282     albertel 5737: 	}
                   5738: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5739: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5740: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5741: 	if (defined($metadata)) { return $metadata; }
1.142     www      5742: 
1.594     albertel 5743: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5744: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5745: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5746: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5747: 				     $env{'course.'.$courseid.'.domain'},
                   5748: 				     'course',
                   5749: 				     ($courselevelm,$courselevel));
1.593     albertel 5750: 	    if (defined($coursereply)) { return $coursereply; }
                   5751: 	}
1.145     www      5752: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5753: 	unless ($space eq '0') {
1.336     albertel 5754: 	    my @parts=split(/_/,$space);
                   5755: 	    my $id=pop(@parts);
                   5756: 	    my $part=join('_',@parts);
                   5757: 	    if ($part eq '') { $part='0'; }
                   5758: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5759: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5760: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5761: 	}
1.395     albertel 5762: 	if ($recurse) { return undef; }
                   5763: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5764: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5765: 
1.48      www      5766: # ---------------------------------------------------- Any other user namespace
                   5767:     } elsif ($realm eq 'environment') {
                   5768: # ----------------------------------------------------------------- environment
1.620     albertel 5769: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5770: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5771: 	} else {
1.770     albertel 5772: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5773: 		return '';
                   5774: 	    }
1.219     albertel 5775: 	    my %returnhash=&userenvironment($udom,$uname,
                   5776: 					    $spacequalifierrest);
                   5777: 	    return $returnhash{$spacequalifierrest};
                   5778: 	}
1.28      www      5779:     } elsif ($realm eq 'system') {
1.48      www      5780: # ----------------------------------------------------------------- system.time
                   5781: 	if ($space eq 'time') {
                   5782: 	    return time;
                   5783:         }
1.696     albertel 5784:     } elsif ($realm eq 'server') {
                   5785: # ----------------------------------------------------------------- system.time
                   5786: 	if ($space eq 'name') {
                   5787: 	    return $ENV{'SERVER_NAME'};
                   5788:         }
1.28      www      5789:     }
1.48      www      5790:     return '';
1.61      www      5791: }
                   5792: 
1.691     raeburn  5793: sub check_group_parms {
                   5794:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5795:     my @groupitems = ();
                   5796:     my $resultitem;
                   5797:     my @levels = ($symbparm,$mapparm,$what);
                   5798:     foreach my $group (@{$groups}) {
                   5799:         foreach my $level (@levels) {
                   5800:              my $item = $courseid.'.['.$group.'].'.$level;
                   5801:              push(@groupitems,$item);
                   5802:         }
                   5803:     }
                   5804:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5805:                             $env{'course.'.$courseid.'.domain'},
                   5806:                                      'course',@groupitems);
                   5807:     return $coursereply;
                   5808: }
                   5809: 
                   5810: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5811:     my ($courseid,@groups) = @_;
                   5812:     @groups = sort(@groups);
1.691     raeburn  5813:     return @groups;
                   5814: }
                   5815: 
1.395     albertel 5816: sub packages_tab_default {
                   5817:     my ($uri,$varname)=@_;
                   5818:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5819: 
                   5820:     my (@extension,@specifics,$do_default);
                   5821:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5822: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5823: 	if ($pack_type eq 'default') {
                   5824: 	    $do_default=1;
                   5825: 	} elsif ($pack_type eq 'extension') {
                   5826: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5827: 	} else {
                   5828: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5829: 	}
                   5830:     }
                   5831:     # first look for a package that matches the requested part id
                   5832:     foreach my $package (@specifics) {
                   5833: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5834: 	next if ($pack_part ne $part);
                   5835: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5836: 	    return $packagetab{"$pack_type&$name&default"};
                   5837: 	}
                   5838:     }
                   5839:     # look for any possible matching non extension_ package
                   5840:     foreach my $package (@specifics) {
                   5841: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5842: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5843: 	    return $packagetab{"$pack_type&$name&default"};
                   5844: 	}
1.585     albertel 5845: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5846: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5847: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5848: 	}
                   5849:     }
1.738     albertel 5850:     # look for any posible extension_ match
                   5851:     foreach my $package (@extension) {
                   5852: 	my ($package,$pack_type)=@{$package};
                   5853: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5854: 	    return $packagetab{"$pack_type&$name&default"};
                   5855: 	}
                   5856: 	if (defined($packagetab{$package."&$name&default"})) {
                   5857: 	    return $packagetab{$package."&$name&default"};
                   5858: 	}
                   5859:     }
                   5860:     # look for a global default setting
                   5861:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5862: 	return $packagetab{"default&$name&default"};
                   5863:     }
1.395     albertel 5864:     return undef;
                   5865: }
                   5866: 
1.334     albertel 5867: sub add_prefix_and_part {
                   5868:     my ($prefix,$part)=@_;
                   5869:     my $keyroot;
                   5870:     if (defined($prefix) && $prefix !~ /^__/) {
                   5871: 	# prefix that has a part already
                   5872: 	$keyroot=$prefix;
                   5873:     } elsif (defined($prefix)) {
                   5874: 	# prefix that is missing a part
                   5875: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5876:     } else {
                   5877: 	# no prefix at all
                   5878: 	if (defined($part)) { $keyroot='_'.$part; }
                   5879:     }
                   5880:     return $keyroot;
                   5881: }
                   5882: 
1.71      www      5883: # ---------------------------------------------------------------- Get metadata
                   5884: 
1.599     albertel 5885: my %metaentry;
1.71      www      5886: sub metadata {
1.176     www      5887:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5888:     $uri=&declutter($uri);
1.288     albertel 5889:     # if it is a non metadata possible uri return quickly
1.529     albertel 5890:     if (($uri eq '') || 
                   5891: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5892: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5893:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5894: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5895: 	return undef;
1.288     albertel 5896:     }
1.73      www      5897:     my $filename=$uri;
                   5898:     $uri=~s/\.meta$//;
1.172     www      5899: #
                   5900: # Is the metadata already cached?
1.177     www      5901: # Look at timestamp of caching
1.172     www      5902: # Everything is cached by the main uri, libraries are never directly cached
                   5903: #
1.428     albertel 5904:     if (!defined($liburi)) {
1.599     albertel 5905: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5906: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5907:     }
                   5908:     {
1.172     www      5909: #
                   5910: # Is this a recursive call for a library?
                   5911: #
1.599     albertel 5912: #	if (! exists($metacache{$uri})) {
                   5913: #	    $metacache{$uri}={};
                   5914: #	}
1.171     www      5915:         if ($liburi) {
                   5916: 	    $liburi=&declutter($liburi);
                   5917:             $filename=$liburi;
1.401     bowersj2 5918:         } else {
1.599     albertel 5919: 	    &devalidate_cache_new('meta',$uri);
                   5920: 	    undef(%metaentry);
1.401     bowersj2 5921: 	}
1.140     www      5922:         my %metathesekeys=();
1.73      www      5923:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5924: 	my $metastring;
1.768     albertel 5925: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5926: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5927: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5928: 	    $metastring=&getfile($file);
1.489     albertel 5929: 	}
1.208     albertel 5930:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5931:         my $token;
1.140     www      5932:         undef %metathesekeys;
1.71      www      5933:         while ($token=$parser->get_token) {
1.339     albertel 5934: 	    if ($token->[0] eq 'S') {
                   5935: 		if (defined($token->[2]->{'package'})) {
1.172     www      5936: #
                   5937: # This is a package - get package info
                   5938: #
1.339     albertel 5939: 		    my $package=$token->[2]->{'package'};
                   5940: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5941: 		    if (defined($token->[2]->{'id'})) { 
                   5942: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5943: 		    }
1.599     albertel 5944: 		    if ($metaentry{':packages'}) {
                   5945: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5946: 		    } else {
1.599     albertel 5947: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5948: 		    }
1.736     albertel 5949: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5950: 			my $part=$keyroot;
                   5951: 			$part=~s/^\_//;
1.736     albertel 5952: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5953: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5954: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5955: 			    # ignore package.tab specified default values
                   5956:                             # here &package_tab_default() will fetch those
                   5957: 			    if ($subp eq 'default') { next; }
1.736     albertel 5958: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5959: 			    my $unikey;
                   5960: 			    if ($pack =~ /_0$/) {
                   5961: 				$unikey='parameter_0_'.$name;
                   5962: 				$part=0;
                   5963: 			    } else {
                   5964: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5965: 			    }
1.339     albertel 5966: 			    if ($subp eq 'display') {
                   5967: 				$value.=' [Part: '.$part.']';
                   5968: 			    }
1.599     albertel 5969: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5970: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5971: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5972: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5973: 			    }
1.599     albertel 5974: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5975: 				$metaentry{':'.$unikey}=
                   5976: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5977: 			    }
1.339     albertel 5978: 			}
                   5979: 		    }
                   5980: 		} else {
1.172     www      5981: #
                   5982: # This is not a package - some other kind of start tag
1.339     albertel 5983: #
                   5984: 		    my $entry=$token->[1];
                   5985: 		    my $unikey;
                   5986: 		    if ($entry eq 'import') {
                   5987: 			$unikey='';
                   5988: 		    } else {
                   5989: 			$unikey=$entry;
                   5990: 		    }
                   5991: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5992: 
                   5993: 		    if (defined($token->[2]->{'id'})) { 
                   5994: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5995: 		    }
1.175     www      5996: 
1.339     albertel 5997: 		    if ($entry eq 'import') {
1.175     www      5998: #
                   5999: # Importing a library here
1.339     albertel 6000: #
                   6001: 			if ($depthcount<20) {
                   6002: 			    my $location=$parser->get_text('/import');
                   6003: 			    my $dir=$filename;
                   6004: 			    $dir=~s|[^/]*$||;
                   6005: 			    $location=&filelocation($dir,$location);
1.736     albertel 6006: 			    my $metadata = 
                   6007: 				&metadata($uri,'keys', $location,$unikey,
                   6008: 					  $depthcount+1);
                   6009: 			    foreach my $meta (split(',',$metadata)) {
                   6010: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6011: 				$metathesekeys{$meta}=1;
1.339     albertel 6012: 			    }
                   6013: 			}
                   6014: 		    } else { 
                   6015: 			
                   6016: 			if (defined($token->[2]->{'name'})) { 
                   6017: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6018: 			}
                   6019: 			$metathesekeys{$unikey}=1;
1.736     albertel 6020: 			foreach my $param (@{$token->[3]}) {
                   6021: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6022: 				$token->[2]->{$param};
1.339     albertel 6023: 			}
                   6024: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6025: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6026: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6027: 		 # only ws inside the tag, and not in default, so use default
                   6028: 		 # as value
1.599     albertel 6029: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6030: 			} else {
1.321     albertel 6031: 		  # either something interesting inside the tag or default
                   6032:                   # uninteresting
1.599     albertel 6033: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6034: 			}
1.172     www      6035: # end of not-a-package not-a-library import
1.339     albertel 6036: 		    }
1.172     www      6037: # end of not-a-package start tag
1.339     albertel 6038: 		}
1.172     www      6039: # the next is the end of "start tag"
1.339     albertel 6040: 	    }
                   6041: 	}
1.483     albertel 6042: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6043: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6044: 	    #no specific packages #how's our extension
                   6045: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6046: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6047: 					 \%metathesekeys);
                   6048: 	}
1.599     albertel 6049: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6050: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6051: 		#no specific packages well let's get default then
                   6052: 		if ($key!~/^default&/) { next; }
1.488     albertel 6053: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6054: 					     \%metathesekeys);
                   6055: 	    }
                   6056: 	}
1.338     www      6057: # are there custom rights to evaluate
1.599     albertel 6058: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6059: 
1.338     www      6060:     #
                   6061:     # Importing a rights file here
1.339     albertel 6062:     #
                   6063: 	    unless ($depthcount) {
1.599     albertel 6064: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6065: 		my $dir=$filename;
                   6066: 		$dir=~s|[^/]*$||;
                   6067: 		$location=&filelocation($dir,$location);
1.736     albertel 6068: 		my $rights_metadata =
                   6069: 		    &metadata($uri,'keys',$location,'_rights',
                   6070: 			      $depthcount+1);
                   6071: 		foreach my $rights (split(',',$rights_metadata)) {
                   6072: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6073: 		    $metathesekeys{$rights}=1;
1.339     albertel 6074: 		}
                   6075: 	    }
                   6076: 	}
1.737     albertel 6077: 	# uniqifiy package listing
                   6078: 	my %seen;
                   6079: 	my @uniq_packages =
                   6080: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6081: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6082: 
                   6083: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6084: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6085: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6086: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6087: # this is the end of "was not already recently cached
1.71      www      6088:     }
1.599     albertel 6089:     return $metaentry{':'.$what};
1.261     albertel 6090: }
                   6091: 
1.488     albertel 6092: sub metadata_create_package_def {
1.483     albertel 6093:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6094:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6095:     if ($subp eq 'default') { next; }
                   6096:     
1.599     albertel 6097:     if (defined($metaentry{':packages'})) {
                   6098: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6099:     } else {
1.599     albertel 6100: 	$metaentry{':packages'}=$package;
1.483     albertel 6101:     }
                   6102:     my $value=$packagetab{$key};
                   6103:     my $unikey;
                   6104:     $unikey='parameter_0_'.$name;
1.599     albertel 6105:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6106:     $$metathesekeys{$unikey}=1;
1.599     albertel 6107:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6108: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6109:     }
1.599     albertel 6110:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6111: 	$metaentry{':'.$unikey}=
                   6112: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6113:     }
                   6114: }
                   6115: 
1.261     albertel 6116: sub metadata_generate_part0 {
                   6117:     my ($metadata,$metacache,$uri) = @_;
                   6118:     my %allnames;
1.737     albertel 6119:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6120: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6121: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6122: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6123: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6124: 	    $allnames{$name}=$part;
                   6125: 	  }
                   6126: 	}
                   6127:     }
                   6128:     foreach my $name (keys(%allnames)) {
                   6129:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6130:       my $key=":parameter_0_$name";
1.261     albertel 6131:       $$metacache{"$key.part"}='0';
                   6132:       $$metacache{"$key.name"}=$name;
1.428     albertel 6133:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6134: 					   $allnames{$name}.'_'.$name.
                   6135: 					   '.type'};
1.428     albertel 6136:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6137: 			     '.display'};
1.644     www      6138:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6139:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6140:       $$metacache{"$key.display"}=$olddis;
                   6141:     }
1.71      www      6142: }
                   6143: 
1.764     albertel 6144: # ------------------------------------------------------ Devalidate title cache
                   6145: 
                   6146: sub devalidate_title_cache {
                   6147:     my ($url)=@_;
                   6148:     if (!$env{'request.course.id'}) { return; }
                   6149:     my $symb=&symbread($url);
                   6150:     if (!$symb) { return; }
                   6151:     my $key=$env{'request.course.id'}."\0".$symb;
                   6152:     &devalidate_cache_new('title',$key);
                   6153: }
                   6154: 
1.301     www      6155: # ------------------------------------------------- Get the title of a resource
                   6156: 
                   6157: sub gettitle {
                   6158:     my $urlsymb=shift;
                   6159:     my $symb=&symbread($urlsymb);
1.534     albertel 6160:     if ($symb) {
1.620     albertel 6161: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6162: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6163: 	if (defined($cached)) { 
                   6164: 	    return $result;
                   6165: 	}
1.534     albertel 6166: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6167: 	my $title='';
                   6168: 	my %bighash;
1.620     albertel 6169: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6170: 		&GDBM_READER(),0640)) {
                   6171: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6172: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6173: 	    untie %bighash;
                   6174: 	}
                   6175: 	$title=~s/\&colon\;/\:/gs;
                   6176: 	if ($title) {
1.599     albertel 6177: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6178: 	}
                   6179: 	$urlsymb=$url;
                   6180:     }
                   6181:     my $title=&metadata($urlsymb,'title');
                   6182:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6183:     return $title;
1.301     www      6184: }
1.613     albertel 6185: 
1.614     albertel 6186: sub get_slot {
                   6187:     my ($which,$cnum,$cdom)=@_;
                   6188:     if (!$cnum || !$cdom) {
                   6189: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 6190: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6191: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6192:     }
1.703     albertel 6193:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6194:     my %slotinfo;
                   6195:     if (exists($remembered{$key})) {
                   6196: 	$slotinfo{$which} = $remembered{$key};
                   6197:     } else {
                   6198: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6199: 	&Apache::lonhomework::showhash(%slotinfo);
                   6200: 	my ($tmp)=keys(%slotinfo);
                   6201: 	if ($tmp=~/^error:/) { return (); }
                   6202: 	$remembered{$key} = $slotinfo{$which};
                   6203:     }
1.616     albertel 6204:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6205: 	return %{$slotinfo{$which}};
                   6206:     }
                   6207:     return $slotinfo{$which};
1.614     albertel 6208: }
1.31      www      6209: # ------------------------------------------------- Update symbolic store links
                   6210: 
                   6211: sub symblist {
                   6212:     my ($mapname,%newhash)=@_;
1.438     www      6213:     $mapname=&deversion(&declutter($mapname));
1.31      www      6214:     my %hash;
1.620     albertel 6215:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6216:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6217:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6218: 	    foreach my $url (keys %newhash) {
                   6219: 		next if ($url eq 'last_known'
                   6220: 			 && $env{'form.no_update_last_known'});
                   6221: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6222: 						    $newhash{$url}->[1],
                   6223: 						    $newhash{$url}->[0]);
1.191     harris41 6224:             }
1.31      www      6225:             if (untie(%hash)) {
                   6226: 		return 'ok';
                   6227:             }
                   6228:         }
                   6229:     }
                   6230:     return 'error';
1.212     www      6231: }
                   6232: 
                   6233: # --------------------------------------------------------------- Verify a symb
                   6234: 
                   6235: sub symbverify {
1.510     www      6236:     my ($symb,$thisurl)=@_;
                   6237:     my $thisfn=$thisurl;
                   6238: # wrapper not part of symbs
                   6239:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 6240:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      6241:     $thisfn=&declutter($thisfn);
1.215     www      6242: # direct jump to resource in page or to a sequence - will construct own symbs
                   6243:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6244: # check URL part
1.409     www      6245:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6246: 
1.431     www      6247:     unless ($url eq $thisfn) { return 0; }
1.213     www      6248: 
1.216     www      6249:     $symb=&symbclean($symb);
1.510     www      6250:     $thisurl=&deversion($thisurl);
1.439     www      6251:     $thisfn=&deversion($thisfn);
1.213     www      6252: 
                   6253:     my %bighash;
                   6254:     my $okay=0;
1.431     www      6255: 
1.620     albertel 6256:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6257:                             &GDBM_READER(),0640)) {
1.510     www      6258:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6259:         unless ($ids) { 
1.510     www      6260:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6261:         }
                   6262:         if ($ids) {
                   6263: # ------------------------------------------------------------------- Has ID(s)
                   6264: 	    foreach (split(/\,/,$ids)) {
1.644     www      6265: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6266:                if (
                   6267:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6268:    eq $symb) { 
1.620     albertel 6269: 		   if (($env{'request.role.adv'}) ||
                   6270: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6271: 		       $okay=1; 
                   6272: 		   }
                   6273: 	       }
1.216     www      6274: 	   }
                   6275:         }
1.213     www      6276: 	untie(%bighash);
                   6277:     }
                   6278:     return $okay;
1.31      www      6279: }
                   6280: 
1.210     www      6281: # --------------------------------------------------------------- Clean-up symb
                   6282: 
                   6283: sub symbclean {
                   6284:     my $symb=shift;
1.568     albertel 6285:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6286: # remove version from map
                   6287:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6288: 
1.210     www      6289: # remove version from URL
                   6290:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6291: 
1.507     www      6292: # remove wrapper
                   6293: 
1.510     www      6294:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6295:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6296:     return $symb;
1.409     www      6297: }
                   6298: 
                   6299: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6300: 
                   6301: sub encode_symb {
                   6302:     my ($map,$resid,$url)=@_;
                   6303:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6304: }
1.409     www      6305: 
                   6306: sub decode_symb {
1.568     albertel 6307:     my $symb=shift;
                   6308:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6309:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6310:     return (&fixversion($map),$resid,&fixversion($url));
                   6311: }
                   6312: 
                   6313: sub fixversion {
                   6314:     my $fn=shift;
1.609     banghart 6315:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6316:     my %bighash;
                   6317:     my $uri=&clutter($fn);
1.620     albertel 6318:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6319: # is this cached?
1.599     albertel 6320:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6321:     if (defined($cached)) { return $result; }
                   6322: # unfortunately not cached, or expired
1.620     albertel 6323:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6324: 	    &GDBM_READER(),0640)) {
                   6325:  	if ($bighash{'version_'.$uri}) {
                   6326:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6327:  	    unless (($version eq 'mostrecent') || 
                   6328: 		    ($version==&getversion($uri))) {
1.440     www      6329:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6330:  	    }
                   6331:  	}
                   6332:  	untie %bighash;
1.413     www      6333:     }
1.599     albertel 6334:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6335: }
                   6336: 
                   6337: sub deversion {
                   6338:     my $url=shift;
                   6339:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6340:     return $url;
1.210     www      6341: }
                   6342: 
1.31      www      6343: # ------------------------------------------------------ Return symb list entry
                   6344: 
                   6345: sub symbread {
1.249     www      6346:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6347:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6348:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6349: # no filename provided? try from environment
1.44      www      6350:     unless ($thisfn) {
1.620     albertel 6351:         if ($env{'request.symb'}) {
                   6352: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6353: 	}
1.620     albertel 6354: 	$thisfn=$env{'request.filename'};
1.44      www      6355:     }
1.569     albertel 6356:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6357: # is that filename actually a symb? Verify, clean, and return
                   6358:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6359: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6360: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6361: 	}
1.242     www      6362:     }
1.44      www      6363:     $thisfn=declutter($thisfn);
1.31      www      6364:     my %hash;
1.37      www      6365:     my %bighash;
                   6366:     my $syval='';
1.620     albertel 6367:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6368:         my $targetfn = $thisfn;
1.609     banghart 6369:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6370:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6371:         }
1.687     albertel 6372: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6373: 	    $targetfn=$1;
                   6374: 	}
1.620     albertel 6375:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6376:                       &GDBM_READER(),0640)) {
1.481     raeburn  6377: 	    $syval=$hash{$targetfn};
1.37      www      6378:             untie(%hash);
                   6379:         }
                   6380: # ---------------------------------------------------------- There was an entry
                   6381:         if ($syval) {
1.601     albertel 6382: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6383: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6384: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6385: 		    #return $env{$cache_str}='';
1.601     albertel 6386: 		#}    
                   6387: 		#$syval.=$1;
                   6388: 	    #}
1.37      www      6389:         } else {
                   6390: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6391:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6392:                             &GDBM_READER(),0640)) {
1.37      www      6393: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6394:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6395:               unless ($ids) { 
                   6396:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6397:               }
                   6398:               unless ($ids) {
                   6399: # alias?
                   6400: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6401:               }
1.37      www      6402:               if ($ids) {
                   6403: # ------------------------------------------------------------------- Has ID(s)
                   6404:                  my @possibilities=split(/\,/,$ids);
1.39      www      6405:                  if ($#possibilities==0) {
                   6406: # ----------------------------------------------- There is only one possibility
1.37      www      6407: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6408: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6409: 						    $resid,$thisfn);
1.249     www      6410:                  } elsif (!$donotrecurse) {
1.39      www      6411: # ------------------------------------------ There is more than one possibility
                   6412:                      my $realpossible=0;
1.191     harris41 6413:                      foreach (@possibilities) {
1.39      www      6414: 			 my $file=$bighash{'src_'.$_};
                   6415:                          if (&allowed('bre',$file)) {
                   6416:          		    my ($mapid,$resid)=split(/\./,$_);
                   6417:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6418: 				$realpossible++;
1.626     albertel 6419:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6420: 						    $resid,$thisfn);
1.39      www      6421:                             }
                   6422: 			 }
1.191     harris41 6423:                      }
1.39      www      6424: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6425:                  } else {
                   6426:                      $syval='';
1.37      www      6427:                  }
                   6428: 	      }
                   6429:               untie(%bighash)
1.481     raeburn  6430:            }
1.31      www      6431:         }
1.62      www      6432:         if ($syval) {
1.620     albertel 6433: 	    return $env{$cache_str}=$syval;
1.62      www      6434:         }
1.31      www      6435:     }
1.44      www      6436:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6437:     return $env{$cache_str}='';
1.31      www      6438: }
                   6439: 
                   6440: # ---------------------------------------------------------- Return random seed
                   6441: 
1.32      www      6442: sub numval {
                   6443:     my $txt=shift;
                   6444:     $txt=~tr/A-J/0-9/;
                   6445:     $txt=~tr/a-j/0-9/;
                   6446:     $txt=~tr/K-T/0-9/;
                   6447:     $txt=~tr/k-t/0-9/;
                   6448:     $txt=~tr/U-Z/0-5/;
                   6449:     $txt=~tr/u-z/0-5/;
                   6450:     $txt=~s/\D//g;
1.564     albertel 6451:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6452:     return int($txt);
1.368     albertel 6453: }
                   6454: 
1.484     albertel 6455: sub numval2 {
                   6456:     my $txt=shift;
                   6457:     $txt=~tr/A-J/0-9/;
                   6458:     $txt=~tr/a-j/0-9/;
                   6459:     $txt=~tr/K-T/0-9/;
                   6460:     $txt=~tr/k-t/0-9/;
                   6461:     $txt=~tr/U-Z/0-5/;
                   6462:     $txt=~tr/u-z/0-5/;
                   6463:     $txt=~s/\D//g;
                   6464:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6465:     my $total;
                   6466:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6467:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6468:     return int($total);
                   6469: }
                   6470: 
1.575     albertel 6471: sub numval3 {
                   6472:     use integer;
                   6473:     my $txt=shift;
                   6474:     $txt=~tr/A-J/0-9/;
                   6475:     $txt=~tr/a-j/0-9/;
                   6476:     $txt=~tr/K-T/0-9/;
                   6477:     $txt=~tr/k-t/0-9/;
                   6478:     $txt=~tr/U-Z/0-5/;
                   6479:     $txt=~tr/u-z/0-5/;
                   6480:     $txt=~s/\D//g;
                   6481:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6482:     my $total;
                   6483:     foreach my $val (@txts) { $total+=$val; }
                   6484:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6485:     return $total;
                   6486: }
                   6487: 
1.675     albertel 6488: sub digest {
                   6489:     my ($data)=@_;
                   6490:     my $digest=&Digest::MD5::md5($data);
                   6491:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6492:     my ($e,$f);
                   6493:     {
                   6494:         use integer;
                   6495:         $e=($a+$b);
                   6496:         $f=($c+$d);
                   6497:         if ($_64bit) {
                   6498:             $e=(($e<<32)>>32);
                   6499:             $f=(($f<<32)>>32);
                   6500:         }
                   6501:     }
                   6502:     if (wantarray) {
                   6503: 	return ($e,$f);
                   6504:     } else {
                   6505: 	my $g;
                   6506: 	{
                   6507: 	    use integer;
                   6508: 	    $g=($e+$f);
                   6509: 	    if ($_64bit) {
                   6510: 		$g=(($g<<32)>>32);
                   6511: 	    }
                   6512: 	}
                   6513: 	return $g;
                   6514:     }
                   6515: }
                   6516: 
1.368     albertel 6517: sub latest_rnd_algorithm_id {
1.675     albertel 6518:     return '64bit5';
1.366     albertel 6519: }
1.32      www      6520: 
1.503     albertel 6521: sub get_rand_alg {
                   6522:     my ($courseid)=@_;
                   6523:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6524:     if ($courseid) {
1.620     albertel 6525: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6526:     }
                   6527:     return &latest_rnd_algorithm_id();
                   6528: }
                   6529: 
1.562     albertel 6530: sub validCODE {
                   6531:     my ($CODE)=@_;
                   6532:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6533:     return 0;
                   6534: }
                   6535: 
1.491     albertel 6536: sub getCODE {
1.620     albertel 6537:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6538:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6539: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6540: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6541: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6542:     }
                   6543:     return undef;
                   6544: }
                   6545: 
1.31      www      6546: sub rndseed {
1.155     albertel 6547:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6548: 
                   6549:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6550:     if (!$symb) {
1.366     albertel 6551: 	unless ($symb=$wsymb) { return time; }
                   6552:     }
                   6553:     if (!$courseid) { $courseid=$wcourseid; }
                   6554:     if (!$domain) { $domain=$wdomain; }
                   6555:     if (!$username) { $username=$wusername }
1.503     albertel 6556:     my $which=&get_rand_alg();
1.491     albertel 6557:     if (defined(&getCODE())) {
1.675     albertel 6558: 	if ($which eq '64bit5') {
                   6559: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6560: 	} elsif ($which eq '64bit4') {
1.575     albertel 6561: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6562: 	} else {
                   6563: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6564: 	}
1.675     albertel 6565:     } elsif ($which eq '64bit5') {
                   6566: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6567:     } elsif ($which eq '64bit4') {
                   6568: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6569:     } elsif ($which eq '64bit3') {
                   6570: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6571:     } elsif ($which eq '64bit2') {
                   6572: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6573:     } elsif ($which eq '64bit') {
                   6574: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6575:     }
                   6576:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6577: }
                   6578: 
                   6579: sub rndseed_32bit {
                   6580:     my ($symb,$courseid,$domain,$username)=@_;
                   6581:     {
                   6582: 	use integer;
                   6583: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6584: 	my $symbseed=numval($symb) << 22;
                   6585: 	my $namechck=unpack("%32C*",$username) << 17;
                   6586: 	my $nameseed=numval($username) << 12;
                   6587: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6588: 	my $courseseed=unpack("%32C*",$courseid);
                   6589: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6590: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6591: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6592: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6593: 	return $num;
                   6594:     }
                   6595: }
                   6596: 
                   6597: sub rndseed_64bit {
                   6598:     my ($symb,$courseid,$domain,$username)=@_;
                   6599:     {
                   6600: 	use integer;
                   6601: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6602: 	my $symbseed=numval($symb) << 10;
                   6603: 	my $namechck=unpack("%32S*",$username);
                   6604: 	
                   6605: 	my $nameseed=numval($username) << 21;
                   6606: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6607: 	my $courseseed=unpack("%32S*",$courseid);
                   6608: 	
                   6609: 	my $num1=$symbchck+$symbseed+$namechck;
                   6610: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6611: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6612: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6613: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6614: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6615: 	return "$num1,$num2";
1.155     albertel 6616:     }
1.366     albertel 6617: }
                   6618: 
1.443     albertel 6619: sub rndseed_64bit2 {
                   6620:     my ($symb,$courseid,$domain,$username)=@_;
                   6621:     {
                   6622: 	use integer;
                   6623: 	# strings need to be an even # of cahracters long, it it is odd the
                   6624:         # last characters gets thrown away
                   6625: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6626: 	my $symbseed=numval($symb) << 10;
                   6627: 	my $namechck=unpack("%32S*",$username.' ');
                   6628: 	
                   6629: 	my $nameseed=numval($username) << 21;
1.501     albertel 6630: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6631: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6632: 	
                   6633: 	my $num1=$symbchck+$symbseed+$namechck;
                   6634: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6635: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6636: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6637: 	return "$num1,$num2";
                   6638:     }
                   6639: }
                   6640: 
                   6641: sub rndseed_64bit3 {
                   6642:     my ($symb,$courseid,$domain,$username)=@_;
                   6643:     {
                   6644: 	use integer;
                   6645: 	# strings need to be an even # of cahracters long, it it is odd the
                   6646:         # last characters gets thrown away
                   6647: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6648: 	my $symbseed=numval2($symb) << 10;
                   6649: 	my $namechck=unpack("%32S*",$username.' ');
                   6650: 	
                   6651: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6652: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6653: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6654: 	
                   6655: 	my $num1=$symbchck+$symbseed+$namechck;
                   6656: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6657: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6658: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6659: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6660: 	
1.503     albertel 6661: 	return "$num1:$num2";
1.443     albertel 6662:     }
                   6663: }
                   6664: 
1.575     albertel 6665: sub rndseed_64bit4 {
                   6666:     my ($symb,$courseid,$domain,$username)=@_;
                   6667:     {
                   6668: 	use integer;
                   6669: 	# strings need to be an even # of cahracters long, it it is odd the
                   6670:         # last characters gets thrown away
                   6671: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6672: 	my $symbseed=numval3($symb) << 10;
                   6673: 	my $namechck=unpack("%32S*",$username.' ');
                   6674: 	
                   6675: 	my $nameseed=numval3($username) << 21;
                   6676: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6677: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6678: 	
                   6679: 	my $num1=$symbchck+$symbseed+$namechck;
                   6680: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6681: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6682: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6683: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6684: 	
                   6685: 	return "$num1:$num2";
                   6686:     }
                   6687: }
                   6688: 
1.675     albertel 6689: sub rndseed_64bit5 {
                   6690:     my ($symb,$courseid,$domain,$username)=@_;
                   6691:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6692:     return "$num1:$num2";
                   6693: }
                   6694: 
1.366     albertel 6695: sub rndseed_CODE_64bit {
                   6696:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6697:     {
1.366     albertel 6698: 	use integer;
1.443     albertel 6699: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6700: 	my $symbseed=numval2($symb);
1.491     albertel 6701: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6702: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6703: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6704: 	my $num1=$symbseed+$CODEchck;
                   6705: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6706: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6707: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6708: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6709: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6710: 	return "$num1:$num2";
1.366     albertel 6711:     }
                   6712: }
                   6713: 
1.575     albertel 6714: sub rndseed_CODE_64bit4 {
                   6715:     my ($symb,$courseid,$domain,$username)=@_;
                   6716:     {
                   6717: 	use integer;
                   6718: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6719: 	my $symbseed=numval3($symb);
                   6720: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6721: 	my $CODEseed=numval3(&getCODE());
                   6722: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6723: 	my $num1=$symbseed+$CODEchck;
                   6724: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6725: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6726: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6727: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6728: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6729: 	return "$num1:$num2";
                   6730:     }
                   6731: }
                   6732: 
1.675     albertel 6733: sub rndseed_CODE_64bit5 {
                   6734:     my ($symb,$courseid,$domain,$username)=@_;
                   6735:     my $code = &getCODE();
                   6736:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6737:     return "$num1:$num2";
                   6738: }
                   6739: 
1.366     albertel 6740: sub setup_random_from_rndseed {
                   6741:     my ($rndseed)=@_;
1.503     albertel 6742:     if ($rndseed =~/([,:])/) {
                   6743: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6744: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6745:     } else {
                   6746: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6747:     }
1.36      albertel 6748: }
                   6749: 
1.474     albertel 6750: sub latest_receipt_algorithm_id {
                   6751:     return 'receipt2';
                   6752: }
                   6753: 
1.480     www      6754: sub recunique {
                   6755:     my $fucourseid=shift;
                   6756:     my $unique;
1.620     albertel 6757:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6758: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6759:     } else {
                   6760: 	$unique=$perlvar{'lonReceipt'};
                   6761:     }
                   6762:     return unpack("%32C*",$unique);
                   6763: }
                   6764: 
                   6765: sub recprefix {
                   6766:     my $fucourseid=shift;
                   6767:     my $prefix;
1.620     albertel 6768:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6769: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6770:     } else {
                   6771: 	$prefix=$perlvar{'lonHostID'};
                   6772:     }
                   6773:     return unpack("%32C*",$prefix);
                   6774: }
                   6775: 
1.76      www      6776: sub ireceipt {
1.474     albertel 6777:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6778:     my $cuname=unpack("%32C*",$funame);
                   6779:     my $cudom=unpack("%32C*",$fudom);
                   6780:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6781:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6782:     my $cunique=&recunique($fucourseid);
1.474     albertel 6783:     my $cpart=unpack("%32S*",$part);
1.480     www      6784:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6785:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6786: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6787: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6788: 			       " and ".($cpart%$cudom));
                   6789: 			       
                   6790: 	$return.= ($cunique%$cuname+
                   6791: 		   $cunique%$cudom+
                   6792: 		   $cusymb%$cuname+
                   6793: 		   $cusymb%$cudom+
                   6794: 		   $cucourseid%$cuname+
                   6795: 		   $cucourseid%$cudom+
                   6796: 		   $cpart%$cuname+
                   6797: 		   $cpart%$cudom);
                   6798:     } else {
                   6799: 	$return.= ($cunique%$cuname+
                   6800: 		   $cunique%$cudom+
                   6801: 		   $cusymb%$cuname+
                   6802: 		   $cusymb%$cudom+
                   6803: 		   $cucourseid%$cuname+
                   6804: 		   $cucourseid%$cudom);
                   6805:     }
                   6806:     return $return;
1.76      www      6807: }
                   6808: 
                   6809: sub receipt {
1.474     albertel 6810:     my ($part)=@_;
                   6811:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6812:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6813: }
1.260     ng       6814: 
1.36      albertel 6815: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6816: # returns either the contents of the file or 
                   6817: # -1 if the file doesn't exist
1.481     raeburn  6818: #
                   6819: # if the target is a file that was uploaded via DOCS, 
                   6820: # a check will be made to see if a current copy exists on the local server,
                   6821: # if it does this will be served, otherwise a copy will be retrieved from
                   6822: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6823: # the local server.   
1.472     albertel 6824: 
1.36      albertel 6825: sub getfile {
1.538     albertel 6826:     my ($file) = @_;
1.609     banghart 6827:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6828:     &repcopy($file);
                   6829:     return &readfile($file);
                   6830: }
                   6831: 
                   6832: sub repcopy_userfile {
                   6833:     my ($file)=@_;
1.609     banghart 6834:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6835:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6836:     my ($cdom,$cnum,$filename) = 
                   6837: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6838:     my ($info,$rtncode);
                   6839:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6840:     if (-e "$file") {
                   6841: 	my @fileinfo = stat($file);
                   6842: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6843: 	if ($lwpresp ne 'ok') {
                   6844: 	    if ($rtncode eq '404') {
1.538     albertel 6845: 		unlink($file);
1.482     albertel 6846: 	    }
1.517     albertel 6847: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6848: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6849: 	    #my $response=$ua->request($request);
                   6850: 	    #if ($response->is_success()) {
                   6851: 	#	return $response->content;
                   6852: 	#    } else {
                   6853: 	#	return -1;
                   6854: 	#    }
1.482     albertel 6855: 	    return -1;
                   6856: 	}
                   6857: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6858: 	    return 'ok';
1.482     albertel 6859: 	}
                   6860: 	$info = '';
1.538     albertel 6861: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6862: 	if ($lwpresp ne 'ok') {
                   6863: 	    return -1;
                   6864: 	}
                   6865:     } else {
1.538     albertel 6866: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6867: 	if ($lwpresp ne 'ok') {
1.517     albertel 6868: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6869: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6870: 	    my $response=$ua->request($request);
                   6871: 	    if ($response->is_success()) {
1.538     albertel 6872: 		$info=$response->content;
1.517     albertel 6873: 	    } else {
                   6874: 		return -1;
                   6875: 	    }
1.482     albertel 6876: 	}
                   6877: 	my @parts = ($cdom,$cnum); 
                   6878: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6879: 	    push @parts, split(/\//,$1);
1.518     albertel 6880: 	}
1.538     albertel 6881: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6882: 	foreach my $part (@parts) {
                   6883: 	    $path .= '/'.$part;
                   6884: 	    if (!-e $path) {
                   6885: 		mkdir($path,0770);
                   6886: 	    }
                   6887: 	}
                   6888:     }
1.538     albertel 6889:     open(FILE,">$file");
1.482     albertel 6890:     print FILE $info;
                   6891:     close(FILE);
1.607     raeburn  6892:     return 'ok';
1.481     raeburn  6893: }
                   6894: 
1.517     albertel 6895: sub tokenwrapper {
                   6896:     my $uri=shift;
1.552     albertel 6897:     $uri=~s|^http\://([^/]+)||;
                   6898:     $uri=~s|^/||;
1.620     albertel 6899:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6900:     my $token=$1;
1.552     albertel 6901:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6902:     if ($udom && $uname && $file) {
                   6903: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6904:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6905:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6906:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6907:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6908:     } else {
                   6909:         return '/adm/notfound.html';
                   6910:     }
                   6911: }
                   6912: 
1.481     raeburn  6913: sub getuploaded {
                   6914:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6915:     $uri=~s/^\///;
                   6916:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6917:     my $ua=new LWP::UserAgent;
                   6918:     my $request=new HTTP::Request($reqtype,$uri);
                   6919:     my $response=$ua->request($request);
                   6920:     $$rtncode = $response->code;
1.482     albertel 6921:     if (! $response->is_success()) {
                   6922: 	return 'failed';
                   6923:     }      
                   6924:     if ($reqtype eq 'HEAD') {
1.486     www      6925: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6926:     } elsif ($reqtype eq 'GET') {
                   6927: 	$$info = $response->content;
1.472     albertel 6928:     }
1.482     albertel 6929:     return 'ok';
1.36      albertel 6930: }
                   6931: 
1.481     raeburn  6932: sub readfile {
                   6933:     my $file = shift;
                   6934:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6935:     my $fh;
                   6936:     open($fh,"<$file");
                   6937:     my $a='';
                   6938:     while (<$fh>) { $a .=$_; }
                   6939:     return $a;
                   6940: }
                   6941: 
1.36      albertel 6942: sub filelocation {
1.590     banghart 6943:     my ($dir,$file) = @_;
                   6944:     my $location;
                   6945:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6946: 
                   6947:     if ($file =~ m-^/adm/-) {
                   6948: 	$file=~s-^/adm/wrapper/-/-;
                   6949: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6950:     }
1.590     banghart 6951:     if ($file=~m:^/~:) { # is a contruction space reference
                   6952:         $location = $file;
                   6953:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6954:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6955: 	# is a correct contruction space reference
                   6956:         $location = $file;
1.609     banghart 6957:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6958:         my ($udom,$uname,$filename)=
1.609     banghart 6959:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6960:         my $home=&homeserver($uname,$udom);
                   6961:         my $is_me=0;
                   6962:         my @ids=&current_machine_ids();
                   6963:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6964:         if ($is_me) {
1.740     www      6965:   	    $location=&propath($udom,$uname).
1.590     banghart 6966:   	      '/userfiles/'.$filename;
                   6967:         } else {
                   6968:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6969:   	      $udom.'/'.$uname.'/'.$filename;
                   6970:         }
                   6971:     } else {
                   6972:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6973:         $file=~s:^/res/:/:;
                   6974:         if ( !( $file =~ m:^/:) ) {
                   6975:             $location = $dir. '/'.$file;
                   6976:         } else {
                   6977:             $location = '/home/httpd/html/res'.$file;
                   6978:         }
1.59      albertel 6979:     }
1.590     banghart 6980:     $location=~s://+:/:g; # remove duplicate /
                   6981:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6982:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6983:     return $location;
1.46      www      6984: }
1.36      albertel 6985: 
1.46      www      6986: sub hreflocation {
                   6987:     my ($dir,$file)=@_;
1.460     albertel 6988:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6989: 	$file=filelocation($dir,$file);
1.700     albertel 6990:     } elsif ($file=~m-^/adm/-) {
                   6991: 	$file=~s-^/adm/wrapper/-/-;
                   6992: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6993:     }
                   6994:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6995: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6996:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6997: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6998:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6999: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7000: 	    -/uploaded/$1/$2/-x;
1.46      www      7001:     }
1.462     albertel 7002:     return $file;
1.465     albertel 7003: }
                   7004: 
                   7005: sub current_machine_domains {
                   7006:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7007:     my @domains;
                   7008:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7009: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7010: 	if ($hostname eq $name) {
                   7011: 	    push(@domains,$hostdom{$id});
                   7012: 	}
                   7013:     }
                   7014:     return @domains;
                   7015: }
                   7016: 
                   7017: sub current_machine_ids {
                   7018:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7019:     my @ids;
                   7020:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7021: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7022: 	if ($hostname eq $name) {
                   7023: 	    push(@ids,$id);
                   7024: 	}
                   7025:     }
                   7026:     return @ids;
1.31      www      7027: }
                   7028: 
                   7029: # ------------------------------------------------------------- Declutters URLs
                   7030: 
                   7031: sub declutter {
                   7032:     my $thisfn=shift;
1.569     albertel 7033:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7034:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7035:     $thisfn=~s/^\///;
1.697     albertel 7036:     $thisfn=~s|^adm/wrapper/||;
                   7037:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7038:     $thisfn=~s/^res\///;
1.235     www      7039:     $thisfn=~s/\?.+$//;
1.268     www      7040:     return $thisfn;
                   7041: }
                   7042: 
                   7043: # ------------------------------------------------------------- Clutter up URLs
                   7044: 
                   7045: sub clutter {
                   7046:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7047:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7048:        $thisfn='/res'.$thisfn; 
                   7049:     }
1.694     albertel 7050:     if ($thisfn !~m|/adm|) {
1.695     albertel 7051: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7052: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7053: 	} else {
                   7054: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7055: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7056: 	    if ($embstyle eq 'ssi'
                   7057: 		|| ($embstyle eq 'hdn')
                   7058: 		|| ($embstyle eq 'rat')
                   7059: 		|| ($embstyle eq 'prv')
                   7060: 		|| ($embstyle eq 'ign')) {
                   7061: 		#do nothing with these
                   7062: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7063: 		|| ($embstyle eq 'emb')
                   7064: 		|| ($embstyle eq 'wrp')) {
                   7065: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7066: 	    } elsif ($embstyle eq 'unk'
                   7067: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7068: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7069: 	    } else {
1.718     www      7070: #		&logthis("Got a blank emb style");
1.695     albertel 7071: 	    }
1.694     albertel 7072: 	}
                   7073:     }
1.31      www      7074:     return $thisfn;
1.12      www      7075: }
                   7076: 
1.557     albertel 7077: sub freeze_escape {
                   7078:     my ($value)=@_;
                   7079:     if (ref($value)) {
                   7080: 	$value=&nfreeze($value);
                   7081: 	return '__FROZEN__'.&escape($value);
                   7082:     }
                   7083:     return &escape($value);
                   7084: }
                   7085: 
1.11      www      7086: 
1.557     albertel 7087: sub thaw_unescape {
                   7088:     my ($value)=@_;
                   7089:     if ($value =~ /^__FROZEN__/) {
                   7090: 	substr($value,0,10,undef);
                   7091: 	$value=&unescape($value);
                   7092: 	return &thaw($value);
                   7093:     }
                   7094:     return &unescape($value);
                   7095: }
                   7096: 
1.436     albertel 7097: sub correct_line_ends {
                   7098:     my ($result)=@_;
                   7099:     $$result =~s/\r\n/\n/mg;
                   7100:     $$result =~s/\r/\n/mg;
1.415     albertel 7101: }
1.1       albertel 7102: # ================================================================ Main Program
                   7103: 
1.184     www      7104: sub goodbye {
1.204     albertel 7105:    &logthis("Starting Shut down");
1.443     albertel 7106: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7107:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7108: #converted
1.599     albertel 7109: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7110:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7111: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7112: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7113: #1.1 only
1.599     albertel 7114: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7115: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7116: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7117: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7118:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7119:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7120:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7121:    &flushcourselogs();
                   7122:    &logthis("Shutting down");
                   7123: }
                   7124: 
1.179     www      7125: BEGIN {
1.228     harris41 7126: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7127:     unless ($readit) {
1.217     harris41 7128: {
1.781     raeburn  7129:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7130:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7131: }
1.1       albertel 7132: 
1.327     albertel 7133: # ------------------------------------------------------------ Read domain file
                   7134: {
                   7135:     %domaindescription = ();
                   7136:     %domain_auth_def = ();
                   7137:     %domain_auth_arg_def = ();
1.448     albertel 7138:     my $fh;
                   7139:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7140:        while (<$fh>) {
1.390     matthew  7141:            next if (/^(\#|\s*$)/);
                   7142: #           next if /^\#/;
1.327     albertel 7143:            chomp;
1.403     www      7144:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7145: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7146: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7147:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7148: 	   $domaindescription{$domain}=$domain_description;
                   7149: 	   $domain_lang_def{$domain}=$def_lang;
                   7150: 	   $domain_city{$domain}=$city;
                   7151: 	   $domain_longi{$domain}=$longi;
                   7152: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7153:            $domain_primary{$domain}=$primary;
1.403     www      7154: 
1.448     albertel 7155:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7156: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7157: 	}
1.327     albertel 7158:     }
1.448     albertel 7159:     close ($fh);
1.327     albertel 7160: }
                   7161: 
                   7162: 
1.1       albertel 7163: # ------------------------------------------------------------- Read hosts file
                   7164: {
1.448     albertel 7165:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7166: 
                   7167:     while (my $configline=<$config>) {
1.303     matthew  7168:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7169:        chomp($configline);
1.595     albertel 7170:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7171:        $name=~s/\s//g;
1.595     albertel 7172:        if ($id && $domain && $role && $name) {
1.252     albertel 7173: 	 $hostname{$id}=$name;
                   7174: 	 $hostdom{$id}=$domain;
                   7175: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7176:        }
1.1       albertel 7177:     }
1.448     albertel 7178:     close($config);
1.619     albertel 7179:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7180:     #&get_iphost();
1.1       albertel 7181: }
                   7182: 
1.598     albertel 7183: sub get_iphost {
                   7184:     if (%iphost) { return %iphost; }
1.653     albertel 7185:     my %name_to_ip;
1.598     albertel 7186:     foreach my $id (keys(%hostname)) {
                   7187: 	my $name=$hostname{$id};
1.653     albertel 7188: 	my $ip;
                   7189: 	if (!exists($name_to_ip{$name})) {
                   7190: 	    $ip = gethostbyname($name);
                   7191: 	    if (!$ip || length($ip) ne 4) {
                   7192: 		&logthis("Skipping host $id name $name no IP found\n");
                   7193: 		next;
                   7194: 	    }
                   7195: 	    $ip=inet_ntoa($ip);
                   7196: 	    $name_to_ip{$name} = $ip;
                   7197: 	} else {
                   7198: 	    $ip = $name_to_ip{$name};
1.598     albertel 7199: 	}
                   7200: 	push(@{$iphost{$ip}},$id);
                   7201:     }
                   7202:     return %iphost;
                   7203: }
                   7204: 
1.1       albertel 7205: # ------------------------------------------------------ Read spare server file
                   7206: {
1.448     albertel 7207:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7208: 
                   7209:     while (my $configline=<$config>) {
                   7210:        chomp($configline);
1.284     matthew  7211:        if ($configline) {
1.1       albertel 7212:           $spareid{$configline}=1;
                   7213:        }
                   7214:     }
1.448     albertel 7215:     close($config);
1.1       albertel 7216: }
1.11      www      7217: # ------------------------------------------------------------ Read permissions
                   7218: {
1.448     albertel 7219:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7220: 
                   7221:     while (my $configline=<$config>) {
1.448     albertel 7222: 	chomp($configline);
                   7223: 	if ($configline) {
                   7224: 	    my ($role,$perm)=split(/ /,$configline);
                   7225: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7226: 	}
1.11      www      7227:     }
1.448     albertel 7228:     close($config);
1.11      www      7229: }
                   7230: 
                   7231: # -------------------------------------------- Read plain texts for permissions
                   7232: {
1.448     albertel 7233:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7234: 
                   7235:     while (my $configline=<$config>) {
1.448     albertel 7236: 	chomp($configline);
                   7237: 	if ($configline) {
1.742     raeburn  7238: 	    my ($short,@plain)=split(/:/,$configline);
                   7239:             %{$prp{$short}} = ();
                   7240: 	    if (@plain > 0) {
                   7241:                 $prp{$short}{'std'} = $plain[0];
                   7242:                 for (my $i=1; $i<@plain; $i++) {
                   7243:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7244:                 }
                   7245:             }
1.448     albertel 7246: 	}
1.135     www      7247:     }
1.448     albertel 7248:     close($config);
1.135     www      7249: }
                   7250: 
                   7251: # ---------------------------------------------------------- Read package table
                   7252: {
1.448     albertel 7253:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7254: 
                   7255:     while (my $configline=<$config>) {
1.483     albertel 7256: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7257: 	chomp($configline);
                   7258: 	my ($short,$plain)=split(/:/,$configline);
                   7259: 	my ($pack,$name)=split(/\&/,$short);
                   7260: 	if ($plain ne '') {
                   7261: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7262: 	    $packagetab{$short}=$plain; 
                   7263: 	}
1.11      www      7264:     }
1.448     albertel 7265:     close($config);
1.329     matthew  7266: }
                   7267: 
                   7268: # ------------- set up temporary directory
                   7269: {
                   7270:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7271: 
1.11      www      7272: }
                   7273: 
1.599     albertel 7274: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7275: 
1.281     www      7276: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7277: $dumpcount=0;
1.22      www      7278: 
1.163     harris41 7279: &logtouch();
1.672     albertel 7280: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7281: $readit=1;
1.564     albertel 7282:     {
                   7283: 	use integer;
                   7284: 	my $test=(2**32)+1;
1.568     albertel 7285: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7286: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7287:     }
1.195     www      7288: }
1.1       albertel 7289: }
1.179     www      7290: 
1.1       albertel 7291: 1;
1.191     harris41 7292: __END__
                   7293: 
1.243     albertel 7294: =pod
                   7295: 
1.191     harris41 7296: =head1 NAME
                   7297: 
1.243     albertel 7298: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7299: 
                   7300: =head1 SYNOPSIS
                   7301: 
1.243     albertel 7302: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7303: 
                   7304:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7305: 
1.243     albertel 7306: Common parameters:
                   7307: 
                   7308: =over 4
                   7309: 
                   7310: =item *
                   7311: 
                   7312: $uname : an internal username (if $cname expecting a course Id specifically)
                   7313: 
                   7314: =item *
                   7315: 
                   7316: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7317: 
                   7318: =item *
                   7319: 
                   7320: $symb : a resource instance identifier
                   7321: 
                   7322: =item *
                   7323: 
                   7324: $namespace : the name of a .db file that contains the data needed or
                   7325: being set.
                   7326: 
                   7327: =back
                   7328: 
1.394     bowersj2 7329: =head1 OVERVIEW
1.191     harris41 7330: 
1.394     bowersj2 7331: lonnet provides subroutines which interact with the
                   7332: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7333: about classes, users, and resources.
1.243     albertel 7334: 
                   7335: For many of these objects you can also use this to store data about
                   7336: them or modify them in various ways.
1.191     harris41 7337: 
1.394     bowersj2 7338: =head2 Symbs
1.191     harris41 7339: 
1.394     bowersj2 7340: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7341: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7342: map, the resource number of the resource in the map, and the URL of
                   7343: the resource itself. The latter is somewhat redundant, but might help
                   7344: if maps change.
                   7345: 
                   7346: An example is
                   7347: 
                   7348:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7349: 
                   7350: The respective map entry is
                   7351: 
                   7352:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7353:   title="Problem 2">
                   7354:  </resource>
                   7355: 
                   7356: Symbs are used by the random number generator, as well as to store and
                   7357: restore data specific to a certain instance of for example a problem.
                   7358: 
                   7359: =head2 Storing And Retrieving Data
                   7360: 
                   7361: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7362: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7363: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7364: is is the non-critical message twin of cstore. These functions are for
                   7365: handlers to store a perl hash to a user's permanent data space in an
                   7366: easy manner, and to retrieve it again on another call. It is expected
                   7367: that a handler would use this once at the beginning to retrieve data,
                   7368: and then again once at the end to send only the new data back.
                   7369: 
                   7370: The data is stored in the user's data directory on the user's
                   7371: homeserver under the ID of the course.
                   7372: 
                   7373: The hash that is returned by restore will have all of the previous
                   7374: value for all of the elements of the hash.
                   7375: 
                   7376: Example:
                   7377: 
                   7378:  #creating a hash
                   7379:  my %hash;
                   7380:  $hash{'foo'}='bar';
                   7381: 
                   7382:  #storing it
                   7383:  &Apache::lonnet::cstore(\%hash);
                   7384: 
                   7385:  #changing a value
                   7386:  $hash{'foo'}='notbar';
                   7387: 
                   7388:  #adding a new value
                   7389:  $hash{'bar'}='foo';
                   7390:  &Apache::lonnet::cstore(\%hash);
                   7391: 
                   7392:  #retrieving the hash
                   7393:  my %history=&Apache::lonnet::restore();
                   7394: 
                   7395:  #print the hash
                   7396:  foreach my $key (sort(keys(%history))) {
                   7397:    print("\%history{$key} = $history{$key}");
                   7398:  }
                   7399: 
                   7400: Will print out:
1.191     harris41 7401: 
1.394     bowersj2 7402:  %history{1:foo} = bar
                   7403:  %history{1:keys} = foo:timestamp
                   7404:  %history{1:timestamp} = 990455579
                   7405:  %history{2:bar} = foo
                   7406:  %history{2:foo} = notbar
                   7407:  %history{2:keys} = foo:bar:timestamp
                   7408:  %history{2:timestamp} = 990455580
                   7409:  %history{bar} = foo
                   7410:  %history{foo} = notbar
                   7411:  %history{timestamp} = 990455580
                   7412:  %history{version} = 2
                   7413: 
                   7414: Note that the special hash entries C<keys>, C<version> and
                   7415: C<timestamp> were added to the hash. C<version> will be equal to the
                   7416: total number of versions of the data that have been stored. The
                   7417: C<timestamp> attribute will be the UNIX time the hash was
                   7418: stored. C<keys> is available in every historical section to list which
                   7419: keys were added or changed at a specific historical revision of a
                   7420: hash.
                   7421: 
                   7422: B<Warning>: do not store the hash that restore returns directly. This
                   7423: will cause a mess since it will restore the historical keys as if the
                   7424: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7425: 
1.394     bowersj2 7426: Calling convention:
1.191     harris41 7427: 
1.394     bowersj2 7428:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7429:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7430: 
1.394     bowersj2 7431: For more detailed information, see lonnet specific documentation.
1.191     harris41 7432: 
1.394     bowersj2 7433: =head1 RETURN MESSAGES
1.191     harris41 7434: 
1.394     bowersj2 7435: =over 4
1.191     harris41 7436: 
1.394     bowersj2 7437: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7438: 
1.394     bowersj2 7439: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7440: when the connection is brought back up
1.191     harris41 7441: 
1.394     bowersj2 7442: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7443: for later delivery
1.191     harris41 7444: 
1.394     bowersj2 7445: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7446: 
1.394     bowersj2 7447: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7448: that was requested
1.191     harris41 7449: 
1.243     albertel 7450: =back
1.191     harris41 7451: 
1.243     albertel 7452: =head1 PUBLIC SUBROUTINES
1.191     harris41 7453: 
1.243     albertel 7454: =head2 Session Environment Functions
1.191     harris41 7455: 
1.243     albertel 7456: =over 4
1.191     harris41 7457: 
1.394     bowersj2 7458: =item * 
                   7459: X<appenv()>
                   7460: B<appenv(%hash)>: the value of %hash is written to
                   7461: the user envirnoment file, and will be restored for each access this
1.620     albertel 7462: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7463: process
1.191     harris41 7464: 
                   7465: =item *
1.394     bowersj2 7466: X<delenv()>
                   7467: B<delenv($regexp)>: removes all items from the session
                   7468: environment file that matches the regular expression in $regexp. The
1.620     albertel 7469: values are also delted from the current processes %env.
1.191     harris41 7470: 
1.243     albertel 7471: =back
                   7472: 
                   7473: =head2 User Information
1.191     harris41 7474: 
1.243     albertel 7475: =over 4
1.191     harris41 7476: 
                   7477: =item *
1.394     bowersj2 7478: X<queryauthenticate()>
                   7479: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7480: authentication scheme
                   7481: 
                   7482: =item *
1.394     bowersj2 7483: X<authenticate()>
                   7484: B<authenticate($uname,$upass,$udom)>: try to
                   7485: authenticate user from domain's lib servers (first use the current
                   7486: one). C<$upass> should be the users password.
1.191     harris41 7487: 
                   7488: =item *
1.394     bowersj2 7489: X<homeserver()>
                   7490: B<homeserver($uname,$udom)>: find the server which has
                   7491: the user's directory and files (there must be only one), this caches
                   7492: the answer, and also caches if there is a borken connection.
1.191     harris41 7493: 
                   7494: =item *
1.394     bowersj2 7495: X<idget()>
                   7496: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7497: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7498: username, and only 1 username per ID in a specific domain) (returns
                   7499: hash: id=>name,id=>name)
1.191     harris41 7500: 
                   7501: =item *
1.394     bowersj2 7502: X<idrget()>
                   7503: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7504: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7505: 
                   7506: =item *
1.394     bowersj2 7507: X<idput()>
                   7508: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7509: 
                   7510: =item *
1.394     bowersj2 7511: X<rolesinit()>
                   7512: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7513: 
                   7514: =item *
1.551     albertel 7515: X<getsection()>
                   7516: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7517: course $cname, return section name/number or '' for "not in course"
                   7518: and '-1' for "no section"
                   7519: 
                   7520: =item *
1.394     bowersj2 7521: X<userenvironment()>
                   7522: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7523: passed in @what from the requested user's environment, returns a hash
                   7524: 
                   7525: =back
                   7526: 
                   7527: =head2 User Roles
                   7528: 
                   7529: =over 4
                   7530: 
                   7531: =item *
                   7532: 
                   7533: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7534: actions
                   7535:  F: full access
                   7536:  U,I,K: authentication modes (cxx only)
                   7537:  '': forbidden
                   7538:  1: user needs to choose course
                   7539:  2: browse allowed
1.766     albertel 7540:  A: passphrase authentication needed
1.243     albertel 7541: 
                   7542: =item *
                   7543: 
                   7544: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7545: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7546: and course level
                   7547: 
                   7548: =item *
                   7549: 
                   7550: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7551: explanation of a user role term
                   7552: 
                   7553: =back
                   7554: 
                   7555: =head2 User Modification
                   7556: 
                   7557: =over 4
                   7558: 
                   7559: =item *
                   7560: 
                   7561: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7562: user for the level given by URL.  Optional start and end dates (leave empty
                   7563: string or zero for "no date")
1.191     harris41 7564: 
                   7565: =item *
                   7566: 
1.243     albertel 7567: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7568: change a users, password, possible return values are: ok,
                   7569: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7570: refused
1.191     harris41 7571: 
                   7572: =item *
                   7573: 
1.243     albertel 7574: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7575: 
                   7576: =item *
                   7577: 
1.243     albertel 7578: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7579: modify user
1.191     harris41 7580: 
                   7581: =item *
                   7582: 
1.286     matthew  7583: modifystudent
                   7584: 
                   7585: modify a students enrollment and identification information.
                   7586: The course id is resolved based on the current users environment.  
                   7587: This means the envoking user must be a course coordinator or otherwise
                   7588: associated with a course.
                   7589: 
1.297     matthew  7590: This call is essentially a wrapper for lonnet::modifyuser and
                   7591: lonnet::modify_student_enrollment
1.286     matthew  7592: 
                   7593: Inputs: 
                   7594: 
                   7595: =over 4
                   7596: 
                   7597: =item B<$udom> Students loncapa domain
                   7598: 
                   7599: =item B<$uname> Students loncapa login name
                   7600: 
                   7601: =item B<$uid> Students id/student number
                   7602: 
                   7603: =item B<$umode> Students authentication mode
                   7604: 
                   7605: =item B<$upass> Students password
                   7606: 
                   7607: =item B<$first> Students first name
                   7608: 
                   7609: =item B<$middle> Students middle name
                   7610: 
                   7611: =item B<$last> Students last name
                   7612: 
                   7613: =item B<$gene> Students generation
                   7614: 
                   7615: =item B<$usec> Students section in course
                   7616: 
                   7617: =item B<$end> Unix time of the roles expiration
                   7618: 
                   7619: =item B<$start> Unix time of the roles start date
                   7620: 
                   7621: =item B<$forceid> If defined, allow $uid to be changed
                   7622: 
                   7623: =item B<$desiredhome> server to use as home server for student
                   7624: 
                   7625: =back
1.297     matthew  7626: 
                   7627: =item *
                   7628: 
                   7629: modify_student_enrollment
                   7630: 
                   7631: Change a students enrollment status in a class.  The environment variable
                   7632: 'role.request.course' must be defined for this function to proceed.
                   7633: 
                   7634: Inputs:
                   7635: 
                   7636: =over 4
                   7637: 
                   7638: =item $udom, students domain
                   7639: 
                   7640: =item $uname, students name
                   7641: 
                   7642: =item $uid, students user id
                   7643: 
                   7644: =item $first, students first name
                   7645: 
                   7646: =item $middle
                   7647: 
                   7648: =item $last
                   7649: 
                   7650: =item $gene
                   7651: 
                   7652: =item $usec
                   7653: 
                   7654: =item $end
                   7655: 
                   7656: =item $start
                   7657: 
                   7658: =back
                   7659: 
1.191     harris41 7660: 
                   7661: =item *
                   7662: 
1.243     albertel 7663: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7664: custom role; give a custom role to a user for the level given by URL.  Specify
                   7665: name and domain of role author, and role name
1.191     harris41 7666: 
                   7667: =item *
                   7668: 
1.243     albertel 7669: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7670: 
                   7671: =item *
                   7672: 
1.243     albertel 7673: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7674: 
                   7675: =back
                   7676: 
                   7677: =head2 Course Infomation
                   7678: 
                   7679: =over 4
1.191     harris41 7680: 
                   7681: =item *
                   7682: 
1.631     albertel 7683: coursedescription($courseid) : returns a hash of information about the
                   7684: specified course id, including all environment settings for the
                   7685: course, the description of the course will be in the hash under the
                   7686: key 'description'
1.191     harris41 7687: 
                   7688: =item *
                   7689: 
1.624     albertel 7690: resdata($name,$domain,$type,@which) : request for current parameter
                   7691: setting for a specific $type, where $type is either 'course' or 'user',
                   7692: @what should be a list of parameters to ask about. This routine caches
                   7693: answers for 5 minutes.
1.243     albertel 7694: 
                   7695: =back
                   7696: 
                   7697: =head2 Course Modification
                   7698: 
                   7699: =over 4
1.191     harris41 7700: 
                   7701: =item *
                   7702: 
1.243     albertel 7703: writecoursepref($courseid,%prefs) : write preferences (environment
                   7704: database) for a course
1.191     harris41 7705: 
                   7706: =item *
                   7707: 
1.243     albertel 7708: createcourse($udom,$description,$url) : make/modify course
                   7709: 
                   7710: =back
                   7711: 
                   7712: =head2 Resource Subroutines
                   7713: 
                   7714: =over 4
1.191     harris41 7715: 
                   7716: =item *
                   7717: 
1.243     albertel 7718: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7719: 
                   7720: =item *
                   7721: 
1.243     albertel 7722: repcopy($filename) : subscribes to the requested file, and attempts to
                   7723: replicate from the owning library server, Might return
1.607     raeburn  7724: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7725: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7726: resource. Expects the local filesystem pathname
                   7727: (/home/httpd/html/res/....)
                   7728: 
                   7729: =back
                   7730: 
                   7731: =head2 Resource Information
                   7732: 
                   7733: =over 4
1.191     harris41 7734: 
                   7735: =item *
                   7736: 
1.243     albertel 7737: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7738: a vairety of different possible values, $varname should be a request
                   7739: string, and the other parameters can be used to specify who and what
                   7740: one is asking about.
                   7741: 
                   7742: Possible values for $varname are environment.lastname (or other item
                   7743: from the envirnment hash), user.name (or someother aspect about the
                   7744: user), resource.0.maxtries (or some other part and parameter of a
                   7745: resource)
1.204     albertel 7746: 
                   7747: =item *
                   7748: 
1.243     albertel 7749: directcondval($number) : get current value of a condition; reads from a state
                   7750: string
1.204     albertel 7751: 
                   7752: =item *
                   7753: 
1.243     albertel 7754: condval($condidx) : value of condition index based on state
1.204     albertel 7755: 
                   7756: =item *
                   7757: 
1.243     albertel 7758: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7759: resource's metadata, $what should be either a specific key, or either
                   7760: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7761: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7762: 
                   7763: this function automatically caches all requests
1.191     harris41 7764: 
                   7765: =item *
                   7766: 
1.243     albertel 7767: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7768: network of library servers; returns file handle of where SQL and regex results
                   7769: will be stored for query
1.191     harris41 7770: 
                   7771: =item *
                   7772: 
1.243     albertel 7773: symbread($filename) : return symbolic list entry (filename argument optional);
                   7774: returns the data handle
1.191     harris41 7775: 
                   7776: =item *
                   7777: 
1.243     albertel 7778: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7779: a possible symb for the URL in $thisfn, and if is an encryypted
                   7780: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7781: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7782: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7783: 
1.191     harris41 7784: 
                   7785: =item *
                   7786: 
1.243     albertel 7787: symbclean($symb) : removes versions numbers from a symb, returns the
                   7788: cleaned symb
1.191     harris41 7789: 
                   7790: =item *
                   7791: 
1.243     albertel 7792: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7793: course map, user must be in a course for it to work.
1.191     harris41 7794: 
                   7795: =item *
                   7796: 
1.243     albertel 7797: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7798: 
                   7799: =item *
                   7800: 
1.243     albertel 7801: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7802: a random seed, all arguments are optional, if they aren't sent it uses the
                   7803: environment to derive them. Note: if symb isn't sent and it can't get one
                   7804: from &symbread it will use the current time as its return value
1.191     harris41 7805: 
                   7806: =item *
                   7807: 
1.243     albertel 7808: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7809: unfakeable, receipt
1.191     harris41 7810: 
                   7811: =item *
                   7812: 
1.620     albertel 7813: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7814: 
                   7815: =item *
                   7816: 
1.243     albertel 7817: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7818: 
                   7819: =item *
                   7820: 
1.243     albertel 7821: 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 7822: 
                   7823: =item *
                   7824: 
1.243     albertel 7825: 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 7826: 
                   7827: =item *
                   7828: 
1.243     albertel 7829: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7830: 
                   7831: =item *
                   7832: 
1.243     albertel 7833: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7834: forcing spreadsheet to reevaluate the resource scores next time.
                   7835: 
                   7836: =back
                   7837: 
                   7838: =head2 Storing/Retreiving Data
                   7839: 
                   7840: =over 4
1.191     harris41 7841: 
                   7842: =item *
                   7843: 
1.243     albertel 7844: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7845: for this url; hashref needs to be given and should be a \%hashname; the
                   7846: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7847: be derived from the env
1.191     harris41 7848: 
                   7849: =item *
                   7850: 
1.243     albertel 7851: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7852: uses critical subroutine
1.191     harris41 7853: 
                   7854: =item *
                   7855: 
1.243     albertel 7856: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7857: all args are optional
1.191     harris41 7858: 
                   7859: =item *
                   7860: 
1.717     albertel 7861: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7862: dumps the complete (or key matching regexp) namespace into a hash
                   7863: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7864: normally &store()ed into
                   7865: 
                   7866: $range should be either an integer '100' (give me the first 100
                   7867:                                            matching records)
                   7868:               or be  two integers sperated by a - with no spaces
                   7869:                  '30-50' (give me the 30th through the 50th matching
                   7870:                           records)
                   7871: 
                   7872: 
                   7873: =item *
                   7874: 
                   7875: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7876: replaces a &store() version of data with a replacement set of data
                   7877: for a particular resource in a namespace passed in the $storehash hash 
                   7878: reference
                   7879: 
                   7880: =item *
                   7881: 
1.243     albertel 7882: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7883: works very similar to store/cstore, but all data is stored in a
                   7884: temporary location and can be reset using tmpreset, $storehash should
                   7885: be a hash reference, returns nothing on success
1.191     harris41 7886: 
                   7887: =item *
                   7888: 
1.243     albertel 7889: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7890: similar to restore, but all data is stored in a temporary location and
                   7891: can be reset using tmpreset. Returns a hash of values on success,
                   7892: error string otherwise.
1.191     harris41 7893: 
                   7894: =item *
                   7895: 
1.243     albertel 7896: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7897: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7898: 
                   7899: =item *
                   7900: 
1.243     albertel 7901: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7902: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7903: 
                   7904: =item *
                   7905: 
1.243     albertel 7906: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7907: namesp ($udom and $uname are optional)
1.191     harris41 7908: 
                   7909: =item *
                   7910: 
1.702     albertel 7911: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7912: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7913: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7914: 
1.702     albertel 7915: $range should be either an integer '100' (give me the first 100
                   7916:                                            matching records)
                   7917:               or be  two integers sperated by a - with no spaces
                   7918:                  '30-50' (give me the 30th through the 50th matching
                   7919:                           records)
1.449     matthew  7920: =item *
                   7921: 
                   7922: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7923: $store can be a scalar, an array reference, or if the amount to be 
                   7924: incremented is > 1, a hash reference.
                   7925: 
                   7926: ($udom and $uname are optional)
1.191     harris41 7927: 
                   7928: =item *
                   7929: 
1.243     albertel 7930: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7931: ($udom and $uname are optional)
1.191     harris41 7932: 
                   7933: =item *
                   7934: 
1.243     albertel 7935: cput($namespace,$storehash,$udom,$uname) : critical put
                   7936: ($udom and $uname are optional)
1.191     harris41 7937: 
                   7938: =item *
                   7939: 
1.748     albertel 7940: newput($namespace,$storehash,$udom,$uname) :
                   7941: 
                   7942: Attempts to store the items in the $storehash, but only if they don't
                   7943: currently exist, if this succeeds you can be certain that you have 
                   7944: successfully created a new key value pair in the $namespace db.
                   7945: 
                   7946: 
                   7947: Args:
                   7948:  $namespace: name of database to store values to
                   7949:  $storehash: hashref to store to the db
                   7950:  $udom: (optional) domain of user containing the db
                   7951:  $uname: (optional) name of user caontaining the db
                   7952: 
                   7953: Returns:
                   7954:  'ok' -> succeeded in storing all keys of $storehash
                   7955:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7956:                         least <key> already existed in the db (other
                   7957:                         requested keys may also already exist)
                   7958:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7959:  'con_lost' -> unable to contact request server
                   7960:  'refused' -> action was not allowed by remote machine
                   7961: 
                   7962: 
                   7963: =item *
                   7964: 
1.243     albertel 7965: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7966: reference filled in from namesp (encrypts the return communication)
                   7967: ($udom and $uname are optional)
1.191     harris41 7968: 
                   7969: =item *
                   7970: 
1.243     albertel 7971: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7972: critical subroutine
                   7973: 
                   7974: =back
                   7975: 
                   7976: =head2 Network Status Functions
                   7977: 
                   7978: =over 4
1.191     harris41 7979: 
                   7980: =item *
                   7981: 
                   7982: dirlist($uri) : return directory list based on URI
                   7983: 
                   7984: =item *
                   7985: 
1.243     albertel 7986: spareserver() : find server with least workload from spare.tab
                   7987: 
                   7988: =back
                   7989: 
                   7990: =head2 Apache Request
                   7991: 
                   7992: =over 4
1.191     harris41 7993: 
                   7994: =item *
                   7995: 
1.243     albertel 7996: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7997: localhost, posts hash
                   7998: 
                   7999: =back
                   8000: 
                   8001: =head2 Data to String to Data
                   8002: 
                   8003: =over 4
1.191     harris41 8004: 
                   8005: =item *
                   8006: 
1.243     albertel 8007: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8008: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8009: 
                   8010: =item *
                   8011: 
1.243     albertel 8012: hashref2str($hashref) : convert a hashref into a string complete with
                   8013: escaping and '=' and '&' separators, supports elements that are
                   8014: arrayrefs and hashrefs
1.191     harris41 8015: 
                   8016: =item *
                   8017: 
1.243     albertel 8018: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8019: with escaping and '&' separators, supports elements that are arrayrefs
                   8020: and hashrefs
1.191     harris41 8021: 
                   8022: =item *
                   8023: 
1.243     albertel 8024: str2hash($string) : convert string to hash using unescaping and
                   8025: splitting on '=' and '&', supports elements that are arrayrefs and
                   8026: hashrefs
1.191     harris41 8027: 
                   8028: =item *
                   8029: 
1.243     albertel 8030: str2array($string) : convert string to hash using unescaping and
                   8031: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8032: 
                   8033: =back
                   8034: 
                   8035: =head2 Logging Routines
                   8036: 
                   8037: =over 4
                   8038: 
                   8039: These routines allow one to make log messages in the lonnet.log and
                   8040: lonnet.perm logfiles.
1.191     harris41 8041: 
                   8042: =item *
                   8043: 
1.243     albertel 8044: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8045: 
                   8046: =item *
                   8047: 
1.243     albertel 8048: logthis() : append message to the normal lonnet.log file, it gets
                   8049: preiodically rolled over and deleted.
1.191     harris41 8050: 
                   8051: =item *
                   8052: 
1.243     albertel 8053: logperm() : append a permanent message to lonnet.perm.log, this log
                   8054: file never gets deleted by any automated portion of the system, only
                   8055: messages of critical importance should go in here.
                   8056: 
                   8057: =back
                   8058: 
                   8059: =head2 General File Helper Routines
                   8060: 
                   8061: =over 4
1.191     harris41 8062: 
                   8063: =item *
                   8064: 
1.481     raeburn  8065: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8066: (a) files in /uploaded
                   8067:   (i) If a local copy of the file exists - 
                   8068:       compares modification date of local copy with last-modified date for 
                   8069:       definitive version stored on home server for course. If local copy is 
                   8070:       stale, requests a new version from the home server and stores it. 
                   8071:       If the original has been removed from the home server, then local copy 
                   8072:       is unlinked.
                   8073:   (ii) If local copy does not exist -
                   8074:       requests the file from the home server and stores it. 
                   8075:   
                   8076:   If $caller is 'uploadrep':  
                   8077:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8078:     for request for files originally uploaded via DOCS. 
                   8079:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8080:   
                   8081:   Otherwise:
                   8082:      This indicates a call from the content generation phase of the request.
                   8083:      -  returns the entire contents of the file or -1.
                   8084:      
                   8085: (b) files in /res
                   8086:    - returns the entire contents of a file or -1; 
                   8087:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8088: 
1.712     albertel 8089: 
                   8090: =item *
                   8091: 
                   8092: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8093:                   reference
                   8094: 
                   8095: returns either a stat() list of data about the file or an empty list
                   8096: if the file doesn't exist or couldn't find out about it (connection
                   8097: problems or user unknown)
                   8098: 
1.191     harris41 8099: =item *
                   8100: 
1.243     albertel 8101: filelocation($dir,$file) : returns file system location of a file
                   8102: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8103: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8104: and a file of ../bob will become /a/bob)
1.191     harris41 8105: 
                   8106: =item *
                   8107: 
                   8108: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8109: filelocation except for hrefs
                   8110: 
                   8111: =item *
                   8112: 
                   8113: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8114: 
1.243     albertel 8115: =back
                   8116: 
1.608     albertel 8117: =head2 Usererfile file routines (/uploaded*)
                   8118: 
                   8119: =over 4
                   8120: 
                   8121: =item *
                   8122: 
                   8123: userfileupload(): main rotine for putting a file in a user or course's
                   8124:                   filespace, arguments are,
                   8125: 
1.620     albertel 8126:  formname - required - this is the name of the element in $env where the
1.608     albertel 8127:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8128:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8129:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8130:  coursedoc - if true, store the file in the course of the active role
                   8131:              of the current user
                   8132:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8133:          if undefined, it will be placed in "unknown"
                   8134: 
                   8135:  (This routine calls clean_filename() to remove any dangerous
                   8136:  characters from the filename, and then calls finuserfileupload() to
                   8137:  complete the transaction)
                   8138: 
                   8139:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8140:  and /adm/notfound.html if unsuccessful
                   8141: 
                   8142: =item *
                   8143: 
                   8144: clean_filename(): routine for cleaing a filename up for storage in
                   8145:                  userfile space, argument is:
                   8146: 
                   8147:  filename - proposed filename
                   8148: 
                   8149: returns: the new clean filename
                   8150: 
                   8151: =item *
                   8152: 
                   8153: finishuserfileupload(): routine that creaes and sends the file to
                   8154: userspace, probably shouldn't be called directly
                   8155: 
                   8156:   docuname: username or courseid of destination for the file
                   8157:   docudom: domain of user/course of destination for the file
                   8158:   formname: same as for userfileupload()
                   8159:   fname: filename (inculding subdirectories) for the file
                   8160: 
                   8161:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8162:  and /adm/notfound.html if unsuccessful
                   8163: 
                   8164: =item *
                   8165: 
                   8166: renameuserfile(): renames an existing userfile to a new name
                   8167: 
                   8168:   Args:
                   8169:    docuname: username or courseid of destination for the file
                   8170:    docudom: domain of user/course of destination for the file
                   8171:    old: current file name (including any subdirs under userfiles)
                   8172:    new: desired file name (including any subdirs under userfiles)
                   8173: 
                   8174: =item *
                   8175: 
                   8176: mkdiruserfile(): creates a directory is a userfiles dir
                   8177: 
                   8178:   Args:
                   8179:    docuname: username or courseid of destination for the file
                   8180:    docudom: domain of user/course of destination for the file
                   8181:    dir: dir to create (including any subdirs under userfiles)
                   8182: 
                   8183: =item *
                   8184: 
                   8185: removeuserfile(): removes a file that exists in userfiles
                   8186: 
                   8187:   Args:
                   8188:    docuname: username or courseid of destination for the file
                   8189:    docudom: domain of user/course of destination for the file
                   8190:    fname: filname to delete (including any subdirs under userfiles)
                   8191: 
                   8192: =item *
                   8193: 
                   8194: removeuploadedurl(): convience function for removeuserfile()
                   8195: 
                   8196:   Args:
                   8197:    url:  a full /uploaded/... url to delete
                   8198: 
1.747     albertel 8199: =item * 
                   8200: 
                   8201: get_portfile_permissions():
                   8202:   Args:
                   8203:     domain: domain of user or course contain the portfolio files
                   8204:     user: name of user or num of course contain the portfolio files
                   8205:   Returns:
                   8206:     hashref of a dump of the proper file_permissions.db
                   8207:    
                   8208: 
                   8209: =item * 
                   8210: 
                   8211: get_access_controls():
                   8212: 
                   8213: Args:
                   8214:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8215:   group: (optional) the group you want the files associated with
                   8216:   file: (optional) the file you want access info on
                   8217: 
                   8218: Returns:
1.749     raeburn  8219:     a hash (keys are file names) of hashes containing
                   8220:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8221:         values are XML containing access control settings (see below) 
1.747     albertel 8222: 
                   8223: Internal notes:
                   8224: 
1.749     raeburn  8225:  access controls are stored in file_permissions.db as key=value pairs.
                   8226:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8227:         where scope -> public,guest,course,group,domains or users.
                   8228:               end -> UNIX time for end of access (0 -> no end date)
                   8229:               start -> UNIX time for start of access
                   8230: 
                   8231:     value -> XML description of access control
                   8232:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8233:             <start></start>
                   8234:             <end></end>
                   8235: 
                   8236:             <password></password>  for scope type = guest
                   8237: 
                   8238:             <domain></domain>     for scope type = course or group
                   8239:             <number></number>
                   8240:             <roles id="">
                   8241:              <role></role>
                   8242:              <access></access>
                   8243:              <section></section>
                   8244:              <group></group>
                   8245:             </roles>
                   8246: 
                   8247:             <dom></dom>         for scope type = domains
                   8248: 
                   8249:             <users>             for scope type = users
                   8250:              <user>
                   8251:               <uname></uname>
                   8252:               <udom></udom>
                   8253:              </user>
                   8254:             </users>
                   8255:            </scope> 
                   8256:               
                   8257:  Access data is also aggregated for each file in an additional key=value pair:
                   8258:  key -> path to file/file_name\0accesscontrol 
                   8259:  value -> reference to hash
                   8260:           hash contains key = value pairs
                   8261:           where key = uniqueID:scope_end_start
                   8262:                 value = UNIX time record was last updated
                   8263: 
                   8264:           Used to improve speed of look-ups of access controls for each file.  
                   8265:  
                   8266:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8267: 
                   8268: modify_access_controls():
                   8269: 
                   8270: Modifies access controls for a portfolio file
                   8271: Args
                   8272: 1. file name
                   8273: 2. reference to hash of required changes,
                   8274: 3. domain
                   8275: 4. username
                   8276:   where domain,username are the domain of the portfolio owner 
                   8277:   (either a user or a course) 
                   8278: 
                   8279: Returns:
                   8280: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8281: 2. result of deletions ('ok' or 'error', with error message).
                   8282: 3. reference to hash of any new or updated access controls.
                   8283: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8284:    key = integer (inbound ID)
                   8285:    value = uniqueID  
1.747     albertel 8286: 
1.608     albertel 8287: =back
                   8288: 
1.243     albertel 8289: =head2 HTTP Helper Routines
                   8290: 
                   8291: =over 4
                   8292: 
1.191     harris41 8293: =item *
                   8294: 
                   8295: escape() : unpack non-word characters into CGI-compatible hex codes
                   8296: 
                   8297: =item *
                   8298: 
                   8299: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8300: 
1.243     albertel 8301: =back
                   8302: 
                   8303: =head1 PRIVATE SUBROUTINES
                   8304: 
                   8305: =head2 Underlying communication routines (Shouldn't call)
                   8306: 
                   8307: =over 4
                   8308: 
                   8309: =item *
                   8310: 
                   8311: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8312: 
                   8313: =item *
                   8314: 
                   8315: reply() : uses subreply to send a message to remote machine, logs all failures
                   8316: 
                   8317: =item *
                   8318: 
                   8319: critical() : passes a critical message to another server; if cannot
                   8320: get through then place message in connection buffer directory and
                   8321: returns con_delayed, if incapable of saving message, returns
                   8322: con_failed
                   8323: 
                   8324: =item *
                   8325: 
                   8326: reconlonc() : tries to reconnect lonc client processes.
                   8327: 
                   8328: =back
                   8329: 
                   8330: =head2 Resource Access Logging
                   8331: 
                   8332: =over 4
                   8333: 
                   8334: =item *
                   8335: 
                   8336: flushcourselogs() : flush (save) buffer logs and access logs
                   8337: 
                   8338: =item *
                   8339: 
                   8340: courselog($what) : save message for course in hash
                   8341: 
                   8342: =item *
                   8343: 
                   8344: courseacclog($what) : save message for course using &courselog().  Perform
                   8345: special processing for specific resource types (problems, exams, quizzes, etc).
                   8346: 
1.191     harris41 8347: =item *
                   8348: 
                   8349: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8350: as a PerlChildExitHandler
1.243     albertel 8351: 
                   8352: =back
                   8353: 
                   8354: =head2 Other
                   8355: 
                   8356: =over 4
                   8357: 
                   8358: =item *
                   8359: 
                   8360: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8361: 
                   8362: =back
                   8363: 
                   8364: =cut

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